blob: efd99544f5a9974ee145aa655a8a41e9cf6e3060 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* POSIX module implementation */
2
Jesus Ceaab70e2a2012-10-05 01:48:08 +02003/* This file is also used for Windows NT/MS-Win. In that case the
4 module actually calls itself 'nt', not 'posix', and a few
Andrew MacIntyre6c73af22002-03-03 03:07:07 +00005 functions are either unimplemented or implemented differently. The source
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00006 assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent
Guido van Rossumad0ee831995-03-01 10:34:45 +00007 of the compiler used. Different compilers define their own feature
Victor Stinnerf427a142014-10-22 12:33:23 +02008 test macro, e.g. '_MSC_VER'. */
Guido van Rossumad0ee831995-03-01 10:34:45 +00009
Thomas Wouters477c8d52006-05-27 19:21:47 +000010#ifdef __APPLE__
11 /*
Victor Stinner8c62be82010-05-06 00:08:46 +000012 * Step 1 of support for weak-linking a number of symbols existing on
Thomas Wouters477c8d52006-05-27 19:21:47 +000013 * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block
14 * at the end of this file for more information.
15 */
16# pragma weak lchown
17# pragma weak statvfs
18# pragma weak fstatvfs
19
20#endif /* __APPLE__ */
21
Thomas Wouters68bc4f92006-03-01 01:05:10 +000022#define PY_SSIZE_T_CLEAN
23
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000024#include "Python.h"
Victor Stinnerd5d9e812019-05-13 12:35:37 +020025#ifdef MS_WINDOWS
26 /* include <windows.h> early to avoid conflict with pycore_condvar.h:
27
28 #define WIN32_LEAN_AND_MEAN
29 #include <windows.h>
30
31 FSCTL_GET_REPARSE_POINT is not exported with WIN32_LEAN_AND_MEAN. */
32# include <windows.h>
33#endif
34
Victor Stinner4a21e572020-04-15 02:35:41 +020035#include "pycore_ceval.h" // _PyEval_ReInitThreads()
36#include "pycore_import.h" // _PyImport_ReInitLock()
Victor Stinner26881c82020-06-02 15:51:37 +020037#include "pycore_initconfig.h" // _PyStatus_EXCEPTION()
Victor Stinner4a21e572020-04-15 02:35:41 +020038#include "pycore_pystate.h" // _PyInterpreterState_GET()
39#include "structmember.h" // PyMemberDef
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020040#ifndef MS_WINDOWS
Victor Stinnerd5d9e812019-05-13 12:35:37 +020041# include "posixmodule.h"
Tim Golden0321cf22014-05-05 19:46:17 +010042#else
Victor Stinnerd5d9e812019-05-13 12:35:37 +020043# include "winreparse.h"
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020044#endif
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000045
Stefan Krahfb7c8ae2016-04-26 17:04:18 +020046/* On android API level 21, 'AT_EACCESS' is not declared although
47 * HAVE_FACCESSAT is defined. */
48#ifdef __ANDROID__
Victor Stinner5eca75d2020-04-15 15:07:31 +020049# undef HAVE_FACCESSAT
Stefan Krahfb7c8ae2016-04-26 17:04:18 +020050#endif
51
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)fa76eee2016-05-28 21:03:48 +000052#include <stdio.h> /* needed for ctermid() */
53
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054#ifdef __cplusplus
55extern "C" {
56#endif
57
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000058PyDoc_STRVAR(posix__doc__,
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000059"This module provides access to operating system functionality that is\n\
60standardized by the C Standard and the POSIX standard (a thinly\n\
61disguised Unix interface). Refer to the library manual and\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000062corresponding Unix manual entries for more information on calls.");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000063
Martin v. Löwis0073f2e2002-11-21 23:52:35 +000064
Ross Lagerwall4d076da2011-03-18 06:56:53 +020065#ifdef HAVE_SYS_UIO_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020066# include <sys/uio.h>
Ross Lagerwall4d076da2011-03-18 06:56:53 +020067#endif
68
Christian Heimes75b96182017-09-05 15:53:09 +020069#ifdef HAVE_SYS_SYSMACROS_H
70/* GNU C Library: major(), minor(), makedev() */
Victor Stinner5eca75d2020-04-15 15:07:31 +020071# include <sys/sysmacros.h>
Christian Heimes75b96182017-09-05 15:53:09 +020072#endif
73
Thomas Wouters0e3f5912006-08-11 14:57:12 +000074#ifdef HAVE_SYS_TYPES_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020075# include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000076#endif /* HAVE_SYS_TYPES_H */
77
78#ifdef HAVE_SYS_STAT_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020079# include <sys/stat.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000080#endif /* HAVE_SYS_STAT_H */
Guido van Rossuma6535fd2001-10-18 19:44:10 +000081
Guido van Rossum36bc6801995-06-14 22:54:23 +000082#ifdef HAVE_SYS_WAIT_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020083# include <sys/wait.h> // WNOHANG
Guido van Rossum36bc6801995-06-14 22:54:23 +000084#endif
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080085#ifdef HAVE_LINUX_WAIT_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020086# include <linux/wait.h> // P_PIDFD
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080087#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +000088
Thomas Wouters0e3f5912006-08-11 14:57:12 +000089#ifdef HAVE_SIGNAL_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020090# include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000091#endif
Guido van Rossuma376cc51996-12-05 23:43:35 +000092
Guido van Rossumb6775db1994-08-01 11:34:53 +000093#ifdef HAVE_FCNTL_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020094# include <fcntl.h>
95#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +000096
Guido van Rossuma6535fd2001-10-18 19:44:10 +000097#ifdef HAVE_GRP_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020098# include <grp.h>
Guido van Rossuma6535fd2001-10-18 19:44:10 +000099#endif
100
Barry Warsaw5676bd12003-01-07 20:57:09 +0000101#ifdef HAVE_SYSEXITS_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200102# include <sysexits.h>
103#endif
Barry Warsaw5676bd12003-01-07 20:57:09 +0000104
Anthony Baxter8a560de2004-10-13 15:30:56 +0000105#ifdef HAVE_SYS_LOADAVG_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200106# include <sys/loadavg.h>
Anthony Baxter8a560de2004-10-13 15:30:56 +0000107#endif
108
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000109#ifdef HAVE_SYS_SENDFILE_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200110# include <sys/sendfile.h>
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000111#endif
112
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +0200113#if defined(__APPLE__)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200114# include <copyfile.h>
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +0200115#endif
116
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500117#ifdef HAVE_SCHED_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200118# include <sched.h>
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500119#endif
120
Pablo Galindoaac4d032019-05-31 19:39:47 +0100121#ifdef HAVE_COPY_FILE_RANGE
Victor Stinner5eca75d2020-04-15 15:07:31 +0200122# include <unistd.h>
Pablo Galindoaac4d032019-05-31 19:39:47 +0100123#endif
124
Benjamin Peterson2dbda072012-03-16 10:12:55 -0500125#if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200126# undef HAVE_SCHED_SETAFFINITY
Benjamin Peterson7b51b8d2012-03-14 22:28:25 -0500127#endif
128
doko@ubuntu.com4a173bc2014-04-17 19:47:16 +0200129#if defined(HAVE_SYS_XATTR_H) && defined(__GLIBC__) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200130# define USE_XATTRS
Benjamin Peterson9428d532011-09-14 11:45:52 -0400131#endif
132
133#ifdef USE_XATTRS
Victor Stinner5eca75d2020-04-15 15:07:31 +0200134# include <sys/xattr.h>
Benjamin Peterson799bd802011-08-31 22:15:17 -0400135#endif
136
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000137#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200138# ifdef HAVE_SYS_SOCKET_H
139# include <sys/socket.h>
140# endif
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000141#endif
142
Victor Stinner8b905bd2011-10-25 13:34:04 +0200143#ifdef HAVE_DLFCN_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200144# include <dlfcn.h>
Victor Stinner8b905bd2011-10-25 13:34:04 +0200145#endif
146
Charles-Francois Natali44feda32013-05-20 14:40:46 +0200147#ifdef __hpux
Victor Stinner5eca75d2020-04-15 15:07:31 +0200148# include <sys/mpctl.h>
Charles-Francois Natali44feda32013-05-20 14:40:46 +0200149#endif
150
151#if defined(__DragonFly__) || \
152 defined(__OpenBSD__) || \
153 defined(__FreeBSD__) || \
154 defined(__NetBSD__) || \
155 defined(__APPLE__)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200156# include <sys/sysctl.h>
Charles-Francois Natali44feda32013-05-20 14:40:46 +0200157#endif
158
Victor Stinner9b1f4742016-09-06 16:18:52 -0700159#ifdef HAVE_LINUX_RANDOM_H
160# include <linux/random.h>
161#endif
162#ifdef HAVE_GETRANDOM_SYSCALL
163# include <sys/syscall.h>
164#endif
165
Antoine Pitroubcf2b592012-02-08 23:28:36 +0100166#if defined(MS_WINDOWS)
167# define TERMSIZE_USE_CONIO
168#elif defined(HAVE_SYS_IOCTL_H)
169# include <sys/ioctl.h>
170# if defined(HAVE_TERMIOS_H)
171# include <termios.h>
172# endif
173# if defined(TIOCGWINSZ)
174# define TERMSIZE_USE_IOCTL
175# endif
176#endif /* MS_WINDOWS */
177
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000178/* Various compilers have only certain posix functions */
Martin v. Löwis4f1cd8b2001-07-26 13:41:06 +0000179/* XXX Gosh I wish these were all moved into pyconfig.h */
Victor Stinner8c62be82010-05-06 00:08:46 +0000180#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
Victor Stinner5eca75d2020-04-15 15:07:31 +0200181# define HAVE_OPENDIR 1
182# define HAVE_SYSTEM 1
183# include <process.h>
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000184#else
Victor Stinner5eca75d2020-04-15 15:07:31 +0200185# ifdef _MSC_VER
186 /* Microsoft compiler */
187# define HAVE_GETPPID 1
188# define HAVE_GETLOGIN 1
189# define HAVE_SPAWNV 1
190# define HAVE_EXECV 1
191# define HAVE_WSPAWNV 1
192# define HAVE_WEXECV 1
193# define HAVE_PIPE 1
194# define HAVE_SYSTEM 1
195# define HAVE_CWAIT 1
196# define HAVE_FSYNC 1
197# define fsync _commit
198# else
199 /* Unix functions that the configure script doesn't check for */
200# ifndef __VXWORKS__
201# define HAVE_EXECV 1
202# define HAVE_FORK 1
203# if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */
204# define HAVE_FORK1 1
205# endif
206# endif
207# define HAVE_GETEGID 1
208# define HAVE_GETEUID 1
209# define HAVE_GETGID 1
210# define HAVE_GETPPID 1
211# define HAVE_GETUID 1
212# define HAVE_KILL 1
213# define HAVE_OPENDIR 1
214# define HAVE_PIPE 1
215# define HAVE_SYSTEM 1
216# define HAVE_WAIT 1
217# define HAVE_TTYNAME 1
218# endif /* _MSC_VER */
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000219#endif /* ! __WATCOMC__ || __QNX__ */
Guido van Rossumad0ee831995-03-01 10:34:45 +0000220
Eddie Elizondob3966632019-11-05 07:16:14 -0800221_Py_IDENTIFIER(__fspath__);
Victor Stinnera2f7c002012-02-08 03:36:25 +0100222
Larry Hastings61272b72014-01-07 12:41:53 -0800223/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +1000224# one of the few times we lie about this name!
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800225module os
Larry Hastings61272b72014-01-07 12:41:53 -0800226[clinic start generated code]*/
Larry Hastings2f936352014-08-05 14:04:04 +1000227/*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
Victor Stinnera2f7c002012-02-08 03:36:25 +0100228
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000229#ifndef _MSC_VER
Guido van Rossum36bc6801995-06-14 22:54:23 +0000230
Martin v. Löwis8eb92a02002-09-19 08:03:21 +0000231#if defined(__sgi)&&_COMPILER_VERSION>=700
232/* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
233 (default) */
234extern char *ctermid_r(char *);
235#endif
236
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000237#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000238
pxinwrf2d7ac72019-05-21 18:46:37 +0800239#if defined(__VXWORKS__)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200240# include <vxCpuLib.h>
241# include <rtpLib.h>
242# include <wait.h>
243# include <taskLib.h>
244# ifndef _P_WAIT
245# define _P_WAIT 0
246# define _P_NOWAIT 1
247# define _P_NOWAITO 1
248# endif
pxinwrf2d7ac72019-05-21 18:46:37 +0800249#endif /* __VXWORKS__ */
250
Pablo Galindo6c6ddf92018-01-29 01:56:10 +0000251#ifdef HAVE_POSIX_SPAWN
Victor Stinner5eca75d2020-04-15 15:07:31 +0200252# include <spawn.h>
Pablo Galindo6c6ddf92018-01-29 01:56:10 +0000253#endif
254
Guido van Rossumb6775db1994-08-01 11:34:53 +0000255#ifdef HAVE_UTIME_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200256# include <utime.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000257#endif /* HAVE_UTIME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000258
Guido van Rossum14ed0b21994-09-29 09:50:09 +0000259#ifdef HAVE_SYS_UTIME_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200260# include <sys/utime.h>
261# define HAVE_UTIME_H /* pretend we do for the rest of this file */
Guido van Rossum14ed0b21994-09-29 09:50:09 +0000262#endif /* HAVE_SYS_UTIME_H */
263
Guido van Rossumb6775db1994-08-01 11:34:53 +0000264#ifdef HAVE_SYS_TIMES_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200265# include <sys/times.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000266#endif /* HAVE_SYS_TIMES_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000267
268#ifdef HAVE_SYS_PARAM_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200269# include <sys/param.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000270#endif /* HAVE_SYS_PARAM_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000271
272#ifdef HAVE_SYS_UTSNAME_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200273# include <sys/utsname.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000274#endif /* HAVE_SYS_UTSNAME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000275
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000276#ifdef HAVE_DIRENT_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200277# include <dirent.h>
278# define NAMLEN(dirent) strlen((dirent)->d_name)
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000279#else
Victor Stinner5eca75d2020-04-15 15:07:31 +0200280# if defined(__WATCOMC__) && !defined(__QNX__)
281# include <direct.h>
282# define NAMLEN(dirent) strlen((dirent)->d_name)
283# else
284# define dirent direct
285# define NAMLEN(dirent) (dirent)->d_namlen
286# endif
287# ifdef HAVE_SYS_NDIR_H
288# include <sys/ndir.h>
289# endif
290# ifdef HAVE_SYS_DIR_H
291# include <sys/dir.h>
292# endif
293# ifdef HAVE_NDIR_H
294# include <ndir.h>
295# endif
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000296#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000297
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000298#ifdef _MSC_VER
Victor Stinner5eca75d2020-04-15 15:07:31 +0200299# ifdef HAVE_DIRECT_H
300# include <direct.h>
301# endif
302# ifdef HAVE_IO_H
303# include <io.h>
304# endif
305# ifdef HAVE_PROCESS_H
306# include <process.h>
307# endif
308# ifndef IO_REPARSE_TAG_SYMLINK
309# define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
310# endif
311# ifndef IO_REPARSE_TAG_MOUNT_POINT
312# define IO_REPARSE_TAG_MOUNT_POINT (0xA0000003L)
313# endif
314# include "osdefs.h" // SEP
315# include <malloc.h>
316# include <windows.h>
317# include <shellapi.h> // ShellExecute()
318# include <lmcons.h> // UNLEN
319# define HAVE_SYMLINK
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000320#endif /* _MSC_VER */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000321
Tim Petersbc2e10e2002-03-03 23:17:02 +0000322#ifndef MAXPATHLEN
Victor Stinner5eca75d2020-04-15 15:07:31 +0200323# if defined(PATH_MAX) && PATH_MAX > 1024
324# define MAXPATHLEN PATH_MAX
325# else
326# define MAXPATHLEN 1024
327# endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000328#endif /* MAXPATHLEN */
329
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000330#ifdef UNION_WAIT
Victor Stinner5eca75d2020-04-15 15:07:31 +0200331 /* Emulate some macros on systems that have a union instead of macros */
332# ifndef WIFEXITED
333# define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
334# endif
335# ifndef WEXITSTATUS
336# define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
337# endif
338# ifndef WTERMSIG
339# define WTERMSIG(u_wait) ((u_wait).w_termsig)
340# endif
341# define WAIT_TYPE union wait
342# define WAIT_STATUS_INT(s) (s.w_status)
343#else
344 /* !UNION_WAIT */
345# define WAIT_TYPE int
346# define WAIT_STATUS_INT(s) (s)
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000347#endif /* UNION_WAIT */
348
Greg Wardb48bc172000-03-01 21:51:56 +0000349/* Don't use the "_r" form if we don't need it (also, won't have a
350 prototype for it, at least on Solaris -- maybe others as well?). */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200351#if defined(HAVE_CTERMID_R)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200352# define USE_CTERMID_R
Greg Wardb48bc172000-03-01 21:51:56 +0000353#endif
354
Fred Drake699f3522000-06-29 21:12:41 +0000355/* choose the appropriate stat and fstat functions and return structs */
Guido van Rossum64529cd2000-06-30 22:45:12 +0000356#undef STAT
Antoine Pitroue47e0932011-01-19 15:21:35 +0000357#undef FSTAT
358#undef STRUCT_STAT
Victor Stinner14b9b112013-06-25 00:37:25 +0200359#ifdef MS_WINDOWS
Victor Stinner5eca75d2020-04-15 15:07:31 +0200360# define STAT win32_stat
361# define LSTAT win32_lstat
362# define FSTAT _Py_fstat_noraise
363# define STRUCT_STAT struct _Py_stat_struct
Fred Drake699f3522000-06-29 21:12:41 +0000364#else
Victor Stinner5eca75d2020-04-15 15:07:31 +0200365# define STAT stat
366# define LSTAT lstat
367# define FSTAT fstat
368# define STRUCT_STAT struct stat
Fred Drake699f3522000-06-29 21:12:41 +0000369#endif
370
Tim Peters11b23062003-04-23 02:39:17 +0000371#if defined(MAJOR_IN_MKDEV)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200372# include <sys/mkdev.h>
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000373#else
Victor Stinner5eca75d2020-04-15 15:07:31 +0200374# if defined(MAJOR_IN_SYSMACROS)
375# include <sys/sysmacros.h>
376# endif
377# if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
378# include <sys/mkdev.h>
379# endif
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000380#endif
Fred Drake699f3522000-06-29 21:12:41 +0000381
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200382#ifdef MS_WINDOWS
Victor Stinner5eca75d2020-04-15 15:07:31 +0200383# define INITFUNC PyInit_nt
384# define MODNAME "nt"
Victor Stinner6036e442015-03-08 01:58:04 +0100385#else
Victor Stinner5eca75d2020-04-15 15:07:31 +0200386# define INITFUNC PyInit_posix
387# define MODNAME "posix"
Victor Stinner6036e442015-03-08 01:58:04 +0100388#endif
389
jcea6c51d512018-01-28 14:00:08 +0100390#if defined(__sun)
391/* Something to implement in autoconf, not present in autoconf 2.69 */
Victor Stinner5eca75d2020-04-15 15:07:31 +0200392# define HAVE_STRUCT_STAT_ST_FSTYPE 1
jcea6c51d512018-01-28 14:00:08 +0100393#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200394
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600395/* memfd_create is either defined in sys/mman.h or sys/memfd.h
396 * linux/memfd.h defines additional flags
397 */
398#ifdef HAVE_SYS_MMAN_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200399# include <sys/mman.h>
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600400#endif
401#ifdef HAVE_SYS_MEMFD_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200402# include <sys/memfd.h>
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600403#endif
404#ifdef HAVE_LINUX_MEMFD_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200405# include <linux/memfd.h>
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600406#endif
407
Gregory P. Smith1d300ce2018-12-30 21:13:02 -0800408#ifdef _Py_MEMORY_SANITIZER
Victor Stinner5eca75d2020-04-15 15:07:31 +0200409# include <sanitizer/msan_interface.h>
Gregory P. Smith1d300ce2018-12-30 21:13:02 -0800410#endif
411
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200412#ifdef HAVE_FORK
413static void
414run_at_forkers(PyObject *lst, int reverse)
415{
416 Py_ssize_t i;
417 PyObject *cpy;
418
419 if (lst != NULL) {
420 assert(PyList_CheckExact(lst));
421
422 /* Use a list copy in case register_at_fork() is called from
423 * one of the callbacks.
424 */
425 cpy = PyList_GetSlice(lst, 0, PyList_GET_SIZE(lst));
426 if (cpy == NULL)
427 PyErr_WriteUnraisable(lst);
428 else {
429 if (reverse)
430 PyList_Reverse(cpy);
431 for (i = 0; i < PyList_GET_SIZE(cpy); i++) {
432 PyObject *func, *res;
433 func = PyList_GET_ITEM(cpy, i);
Jeroen Demeyer7f41c8e2019-07-04 12:35:31 +0200434 res = _PyObject_CallNoArg(func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200435 if (res == NULL)
436 PyErr_WriteUnraisable(func);
437 else
438 Py_DECREF(res);
439 }
440 Py_DECREF(cpy);
441 }
442 }
443}
444
445void
446PyOS_BeforeFork(void)
447{
Victor Stinner81a7be32020-04-14 15:14:01 +0200448 run_at_forkers(_PyInterpreterState_GET()->before_forkers, 1);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200449
450 _PyImport_AcquireLock();
451}
452
453void
454PyOS_AfterFork_Parent(void)
455{
456 if (_PyImport_ReleaseLock() <= 0)
457 Py_FatalError("failed releasing import lock after fork");
458
Victor Stinner81a7be32020-04-14 15:14:01 +0200459 run_at_forkers(_PyInterpreterState_GET()->after_forkers_parent, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200460}
461
462void
463PyOS_AfterFork_Child(void)
464{
Victor Stinner26881c82020-06-02 15:51:37 +0200465 PyStatus status;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200466 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner26881c82020-06-02 15:51:37 +0200467
468 status = _PyGILState_Reinit(runtime);
469 if (_PyStatus_EXCEPTION(status)) {
470 goto fatal_error;
471 }
472
Victor Stinner317bab02020-06-02 18:44:54 +0200473 PyThreadState *tstate = _PyThreadState_GET();
474 _Py_EnsureTstateNotNULL(tstate);
475
476 status = _PyEval_ReInitThreads(tstate);
Victor Stinner26881c82020-06-02 15:51:37 +0200477 if (_PyStatus_EXCEPTION(status)) {
478 goto fatal_error;
479 }
480
481 status = _PyImport_ReInitLock();
482 if (_PyStatus_EXCEPTION(status)) {
483 goto fatal_error;
484 }
485
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200486 _PySignal_AfterFork();
Victor Stinner26881c82020-06-02 15:51:37 +0200487
488 status = _PyRuntimeState_ReInitThreads(runtime);
489 if (_PyStatus_EXCEPTION(status)) {
490 goto fatal_error;
491 }
492
493 status = _PyInterpreterState_DeleteExceptMain(runtime);
494 if (_PyStatus_EXCEPTION(status)) {
495 goto fatal_error;
496 }
Victor Stinner317bab02020-06-02 18:44:54 +0200497 assert(_PyThreadState_GET() == tstate);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200498
Victor Stinner317bab02020-06-02 18:44:54 +0200499 run_at_forkers(tstate->interp->after_forkers_child, 0);
Victor Stinner26881c82020-06-02 15:51:37 +0200500 return;
501
502fatal_error:
503 Py_ExitStatusException(status);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200504}
505
506static int
507register_at_forker(PyObject **lst, PyObject *func)
508{
Gregory P. Smith163468a2017-05-29 10:03:41 -0700509 if (func == NULL) /* nothing to register? do nothing. */
510 return 0;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200511 if (*lst == NULL) {
512 *lst = PyList_New(0);
513 if (*lst == NULL)
514 return -1;
515 }
516 return PyList_Append(*lst, func);
517}
Victor Stinner87255be2020-04-07 23:11:49 +0200518#endif /* HAVE_FORK */
519
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200520
521/* Legacy wrapper */
522void
523PyOS_AfterFork(void)
524{
525#ifdef HAVE_FORK
526 PyOS_AfterFork_Child();
527#endif
528}
529
530
Victor Stinner6036e442015-03-08 01:58:04 +0100531#ifdef MS_WINDOWS
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200532/* defined in fileutils.c */
Benjamin Petersone5024512018-09-12 12:06:42 -0700533void _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
534void _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *,
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200535 ULONG, struct _Py_stat_struct *);
536#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700537
Larry Hastings9cf065c2012-06-22 16:30:09 -0700538
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200539#ifndef MS_WINDOWS
540PyObject *
541_PyLong_FromUid(uid_t uid)
542{
543 if (uid == (uid_t)-1)
544 return PyLong_FromLong(-1);
545 return PyLong_FromUnsignedLong(uid);
546}
547
548PyObject *
549_PyLong_FromGid(gid_t gid)
550{
551 if (gid == (gid_t)-1)
552 return PyLong_FromLong(-1);
553 return PyLong_FromUnsignedLong(gid);
554}
555
556int
557_Py_Uid_Converter(PyObject *obj, void *p)
558{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700559 uid_t uid;
560 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200561 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200562 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700563 unsigned long uresult;
564
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300565 index = _PyNumber_Index(obj);
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700566 if (index == NULL) {
567 PyErr_Format(PyExc_TypeError,
568 "uid should be integer, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800569 _PyType_Name(Py_TYPE(obj)));
Serhiy Storchakab4621892013-02-10 23:28:02 +0200570 return 0;
571 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700572
573 /*
574 * Handling uid_t is complicated for two reasons:
575 * * Although uid_t is (always?) unsigned, it still
576 * accepts -1.
577 * * We don't know its size in advance--it may be
578 * bigger than an int, or it may be smaller than
579 * a long.
580 *
581 * So a bit of defensive programming is in order.
582 * Start with interpreting the value passed
583 * in as a signed long and see if it works.
584 */
585
586 result = PyLong_AsLongAndOverflow(index, &overflow);
587
588 if (!overflow) {
589 uid = (uid_t)result;
590
591 if (result == -1) {
592 if (PyErr_Occurred())
593 goto fail;
594 /* It's a legitimate -1, we're done. */
595 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200596 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700597
598 /* Any other negative number is disallowed. */
599 if (result < 0)
600 goto underflow;
601
602 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200603 if (sizeof(uid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700604 (long)uid != result)
605 goto underflow;
606 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200607 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700608
609 if (overflow < 0)
610 goto underflow;
611
612 /*
613 * Okay, the value overflowed a signed long. If it
614 * fits in an *unsigned* long, it may still be okay,
615 * as uid_t may be unsigned long on this platform.
616 */
617 uresult = PyLong_AsUnsignedLong(index);
618 if (PyErr_Occurred()) {
619 if (PyErr_ExceptionMatches(PyExc_OverflowError))
620 goto overflow;
621 goto fail;
622 }
623
624 uid = (uid_t)uresult;
625
626 /*
627 * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
628 * but this value would get interpreted as (uid_t)-1 by chown
629 * and its siblings. That's not what the user meant! So we
630 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100631 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700632 */
633 if (uid == (uid_t)-1)
634 goto overflow;
635
636 /* Ensure the value wasn't truncated. */
637 if (sizeof(uid_t) < sizeof(long) &&
638 (unsigned long)uid != uresult)
639 goto overflow;
640 /* fallthrough */
641
642success:
643 Py_DECREF(index);
644 *(uid_t *)p = uid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200645 return 1;
646
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700647underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200648 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700649 "uid is less than minimum");
650 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200651
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700652overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200653 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700654 "uid is greater than maximum");
655 /* fallthrough */
656
657fail:
658 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200659 return 0;
660}
661
662int
663_Py_Gid_Converter(PyObject *obj, void *p)
664{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700665 gid_t gid;
666 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200667 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200668 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700669 unsigned long uresult;
670
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300671 index = _PyNumber_Index(obj);
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700672 if (index == NULL) {
673 PyErr_Format(PyExc_TypeError,
674 "gid should be integer, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800675 _PyType_Name(Py_TYPE(obj)));
Serhiy Storchakab4621892013-02-10 23:28:02 +0200676 return 0;
677 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700678
679 /*
680 * Handling gid_t is complicated for two reasons:
681 * * Although gid_t is (always?) unsigned, it still
682 * accepts -1.
683 * * We don't know its size in advance--it may be
684 * bigger than an int, or it may be smaller than
685 * a long.
686 *
687 * So a bit of defensive programming is in order.
688 * Start with interpreting the value passed
689 * in as a signed long and see if it works.
690 */
691
692 result = PyLong_AsLongAndOverflow(index, &overflow);
693
694 if (!overflow) {
695 gid = (gid_t)result;
696
697 if (result == -1) {
698 if (PyErr_Occurred())
699 goto fail;
700 /* It's a legitimate -1, we're done. */
701 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200702 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700703
704 /* Any other negative number is disallowed. */
705 if (result < 0) {
706 goto underflow;
707 }
708
709 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200710 if (sizeof(gid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700711 (long)gid != result)
712 goto underflow;
713 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200714 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700715
716 if (overflow < 0)
717 goto underflow;
718
719 /*
720 * Okay, the value overflowed a signed long. If it
721 * fits in an *unsigned* long, it may still be okay,
722 * as gid_t may be unsigned long on this platform.
723 */
724 uresult = PyLong_AsUnsignedLong(index);
725 if (PyErr_Occurred()) {
726 if (PyErr_ExceptionMatches(PyExc_OverflowError))
727 goto overflow;
728 goto fail;
729 }
730
731 gid = (gid_t)uresult;
732
733 /*
734 * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
735 * but this value would get interpreted as (gid_t)-1 by chown
736 * and its siblings. That's not what the user meant! So we
737 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100738 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700739 */
740 if (gid == (gid_t)-1)
741 goto overflow;
742
743 /* Ensure the value wasn't truncated. */
744 if (sizeof(gid_t) < sizeof(long) &&
745 (unsigned long)gid != uresult)
746 goto overflow;
747 /* fallthrough */
748
749success:
750 Py_DECREF(index);
751 *(gid_t *)p = gid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200752 return 1;
753
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700754underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200755 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700756 "gid is less than minimum");
757 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200758
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700759overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200760 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700761 "gid is greater than maximum");
762 /* fallthrough */
763
764fail:
765 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200766 return 0;
767}
768#endif /* MS_WINDOWS */
769
770
Benjamin Petersoned4aa832016-09-05 17:44:18 -0700771#define _PyLong_FromDev PyLong_FromLongLong
Gregory P. Smith702dada2015-01-28 16:07:52 -0800772
773
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200774#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
775static int
776_Py_Dev_Converter(PyObject *obj, void *p)
777{
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200778 *((dev_t *)p) = PyLong_AsUnsignedLongLong(obj);
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200779 if (PyErr_Occurred())
780 return 0;
781 return 1;
782}
Gregory P. Smith702dada2015-01-28 16:07:52 -0800783#endif /* HAVE_MKNOD && HAVE_MAKEDEV */
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200784
785
Larry Hastings9cf065c2012-06-22 16:30:09 -0700786#ifdef AT_FDCWD
Trent Nelson9a461052012-09-18 21:50:06 -0400787/*
788 * Why the (int) cast? Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
789 * without the int cast, the value gets interpreted as uint (4291925331),
790 * which doesn't play nicely with all the initializer lines in this file that
791 * look like this:
792 * int dir_fd = DEFAULT_DIR_FD;
793 */
794#define DEFAULT_DIR_FD (int)AT_FDCWD
Larry Hastings9cf065c2012-06-22 16:30:09 -0700795#else
796#define DEFAULT_DIR_FD (-100)
797#endif
798
799static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300800_fd_converter(PyObject *o, int *p)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200801{
802 int overflow;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700803 long long_value;
804
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300805 PyObject *index = _PyNumber_Index(o);
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700806 if (index == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700807 return 0;
808 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700809
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300810 assert(PyLong_Check(index));
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700811 long_value = PyLong_AsLongAndOverflow(index, &overflow);
812 Py_DECREF(index);
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300813 assert(!PyErr_Occurred());
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200814 if (overflow > 0 || long_value > INT_MAX) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700815 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700816 "fd is greater than maximum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700817 return 0;
818 }
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200819 if (overflow < 0 || long_value < INT_MIN) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700820 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700821 "fd is less than minimum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700822 return 0;
823 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700824
Larry Hastings9cf065c2012-06-22 16:30:09 -0700825 *p = (int)long_value;
826 return 1;
827}
828
829static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200830dir_fd_converter(PyObject *o, void *p)
831{
832 if (o == Py_None) {
833 *(int *)p = DEFAULT_DIR_FD;
834 return 1;
835 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300836 else if (PyIndex_Check(o)) {
837 return _fd_converter(o, (int *)p);
838 }
839 else {
840 PyErr_Format(PyExc_TypeError,
841 "argument should be integer or None, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800842 _PyType_Name(Py_TYPE(o)));
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300843 return 0;
844 }
Larry Hastings9cf065c2012-06-22 16:30:09 -0700845}
846
Eddie Elizondob3966632019-11-05 07:16:14 -0800847typedef struct {
848 PyObject *billion;
Eddie Elizondob3966632019-11-05 07:16:14 -0800849 PyObject *DirEntryType;
850 PyObject *ScandirIteratorType;
851#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
852 PyObject *SchedParamType;
853#endif
854 PyObject *StatResultType;
855 PyObject *StatVFSResultType;
856 PyObject *TerminalSizeType;
857 PyObject *TimesResultType;
858 PyObject *UnameResultType;
859#if defined(HAVE_WAITID) && !defined(__APPLE__)
860 PyObject *WaitidResultType;
861#endif
862#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
863 PyObject *struct_rusage;
864#endif
865 PyObject *st_mode;
866} _posixstate;
867
Eddie Elizondob3966632019-11-05 07:16:14 -0800868
Hai Shif707d942020-03-16 21:15:01 +0800869static inline _posixstate*
870get_posix_state(PyObject *module)
871{
872 void *state = PyModule_GetState(module);
873 assert(state != NULL);
874 return (_posixstate *)state;
875}
876
Larry Hastings9cf065c2012-06-22 16:30:09 -0700877/*
878 * A PyArg_ParseTuple "converter" function
879 * that handles filesystem paths in the manner
880 * preferred by the os module.
881 *
882 * path_converter accepts (Unicode) strings and their
883 * subclasses, and bytes and their subclasses. What
884 * it does with the argument depends on the platform:
885 *
886 * * On Windows, if we get a (Unicode) string we
887 * extract the wchar_t * and return it; if we get
Steve Dowercc16be82016-09-08 10:35:16 -0700888 * bytes we decode to wchar_t * and return that.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700889 *
890 * * On all other platforms, strings are encoded
891 * to bytes using PyUnicode_FSConverter, then we
892 * extract the char * from the bytes object and
893 * return that.
894 *
895 * path_converter also optionally accepts signed
896 * integers (representing open file descriptors) instead
897 * of path strings.
898 *
899 * Input fields:
900 * path.nullable
901 * If nonzero, the path is permitted to be None.
902 * path.allow_fd
903 * If nonzero, the path is permitted to be a file handle
904 * (a signed int) instead of a string.
905 * path.function_name
906 * If non-NULL, path_converter will use that as the name
907 * of the function in error messages.
Larry Hastings31826802013-10-19 00:09:25 -0700908 * (If path.function_name is NULL it omits the function name.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700909 * path.argument_name
910 * If non-NULL, path_converter will use that as the name
911 * of the parameter in error messages.
912 * (If path.argument_name is NULL it uses "path".)
913 *
914 * Output fields:
915 * path.wide
916 * Points to the path if it was expressed as Unicode
917 * and was not encoded. (Only used on Windows.)
918 * path.narrow
919 * Points to the path if it was expressed as bytes,
Steve Dowercc16be82016-09-08 10:35:16 -0700920 * or it was Unicode and was encoded to bytes. (On Windows,
Martin Panterb1321fb2016-10-10 00:38:21 +0000921 * is a non-zero integer if the path was expressed as bytes.
Steve Dowercc16be82016-09-08 10:35:16 -0700922 * The type is deliberately incompatible to prevent misuse.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700923 * path.fd
924 * Contains a file descriptor if path.accept_fd was true
925 * and the caller provided a signed integer instead of any
926 * sort of string.
927 *
928 * WARNING: if your "path" parameter is optional, and is
929 * unspecified, path_converter will never get called.
930 * So if you set allow_fd, you *MUST* initialize path.fd = -1
931 * yourself!
932 * path.length
933 * The length of the path in characters, if specified as
934 * a string.
935 * path.object
Xiang Zhang04316c42017-01-08 23:26:57 +0800936 * The original object passed in (if get a PathLike object,
937 * the result of PyOS_FSPath() is treated as the original object).
938 * Own a reference to the object.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700939 * path.cleanup
940 * For internal use only. May point to a temporary object.
941 * (Pay no attention to the man behind the curtain.)
942 *
943 * At most one of path.wide or path.narrow will be non-NULL.
944 * If path was None and path.nullable was set,
945 * or if path was an integer and path.allow_fd was set,
946 * both path.wide and path.narrow will be NULL
947 * and path.length will be 0.
Georg Brandlf7875592012-06-24 13:58:31 +0200948 *
Larry Hastings9cf065c2012-06-22 16:30:09 -0700949 * path_converter takes care to not write to the path_t
950 * unless it's successful. However it must reset the
951 * "cleanup" field each time it's called.
952 *
953 * Use as follows:
954 * path_t path;
955 * memset(&path, 0, sizeof(path));
956 * PyArg_ParseTuple(args, "O&", path_converter, &path);
957 * // ... use values from path ...
958 * path_cleanup(&path);
959 *
960 * (Note that if PyArg_Parse fails you don't need to call
961 * path_cleanup(). However it is safe to do so.)
962 */
963typedef struct {
Victor Stinner292c8352012-10-30 02:17:38 +0100964 const char *function_name;
965 const char *argument_name;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700966 int nullable;
967 int allow_fd;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300968 const wchar_t *wide;
Steve Dowercc16be82016-09-08 10:35:16 -0700969#ifdef MS_WINDOWS
970 BOOL narrow;
971#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300972 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700973#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700974 int fd;
975 Py_ssize_t length;
976 PyObject *object;
977 PyObject *cleanup;
978} path_t;
979
Steve Dowercc16be82016-09-08 10:35:16 -0700980#ifdef MS_WINDOWS
981#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
982 {function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
983#else
Larry Hastings2f936352014-08-05 14:04:04 +1000984#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
985 {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
Steve Dowercc16be82016-09-08 10:35:16 -0700986#endif
Larry Hastings31826802013-10-19 00:09:25 -0700987
Larry Hastings9cf065c2012-06-22 16:30:09 -0700988static void
Xiang Zhang04316c42017-01-08 23:26:57 +0800989path_cleanup(path_t *path)
990{
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +0300991#if !USE_UNICODE_WCHAR_CACHE
992 wchar_t *wide = (wchar_t *)path->wide;
993 path->wide = NULL;
994 PyMem_Free(wide);
995#endif /* USE_UNICODE_WCHAR_CACHE */
Xiang Zhang04316c42017-01-08 23:26:57 +0800996 Py_CLEAR(path->object);
997 Py_CLEAR(path->cleanup);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700998}
999
1000static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001001path_converter(PyObject *o, void *p)
1002{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001003 path_t *path = (path_t *)p;
Xiang Zhang04316c42017-01-08 23:26:57 +08001004 PyObject *bytes = NULL;
1005 Py_ssize_t length = 0;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001006 int is_index, is_buffer, is_bytes, is_unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03001007 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -07001008#ifdef MS_WINDOWS
Xiang Zhang04316c42017-01-08 23:26:57 +08001009 PyObject *wo = NULL;
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001010 wchar_t *wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001011#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07001012
1013#define FORMAT_EXCEPTION(exc, fmt) \
1014 PyErr_Format(exc, "%s%s" fmt, \
1015 path->function_name ? path->function_name : "", \
1016 path->function_name ? ": " : "", \
1017 path->argument_name ? path->argument_name : "path")
1018
1019 /* Py_CLEANUP_SUPPORTED support */
1020 if (o == NULL) {
1021 path_cleanup(path);
1022 return 1;
1023 }
1024
Brett Cannon3f9183b2016-08-26 14:44:48 -07001025 /* Ensure it's always safe to call path_cleanup(). */
Xiang Zhang04316c42017-01-08 23:26:57 +08001026 path->object = path->cleanup = NULL;
1027 /* path->object owns a reference to the original object */
1028 Py_INCREF(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001029
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001030 if ((o == Py_None) && path->nullable) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001031 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001032#ifdef MS_WINDOWS
1033 path->narrow = FALSE;
1034#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001035 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001036#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07001037 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001038 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001039 }
1040
Brett Cannon3f9183b2016-08-26 14:44:48 -07001041 /* Only call this here so that we don't treat the return value of
1042 os.fspath() as an fd or buffer. */
1043 is_index = path->allow_fd && PyIndex_Check(o);
1044 is_buffer = PyObject_CheckBuffer(o);
1045 is_bytes = PyBytes_Check(o);
1046 is_unicode = PyUnicode_Check(o);
1047
1048 if (!is_index && !is_buffer && !is_unicode && !is_bytes) {
1049 /* Inline PyOS_FSPath() for better error messages. */
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001050 PyObject *func, *res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001051
1052 func = _PyObject_LookupSpecial(o, &PyId___fspath__);
1053 if (NULL == func) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001054 goto error_format;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001055 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001056 res = _PyObject_CallNoArg(func);
Brett Cannon3f9183b2016-08-26 14:44:48 -07001057 Py_DECREF(func);
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001058 if (NULL == res) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001059 goto error_exit;
1060 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001061 else if (PyUnicode_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001062 is_unicode = 1;
1063 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001064 else if (PyBytes_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001065 is_bytes = 1;
1066 }
1067 else {
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001068 PyErr_Format(PyExc_TypeError,
1069 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -08001070 "not %.200s", _PyType_Name(Py_TYPE(o)),
1071 _PyType_Name(Py_TYPE(res)));
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001072 Py_DECREF(res);
1073 goto error_exit;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001074 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001075
1076 /* still owns a reference to the original object */
1077 Py_DECREF(o);
1078 o = res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001079 }
1080
1081 if (is_unicode) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001082#ifdef MS_WINDOWS
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001083#if USE_UNICODE_WCHAR_CACHE
1084_Py_COMP_DIAG_PUSH
1085_Py_COMP_DIAG_IGNORE_DEPR_DECLS
Victor Stinner26c03bd2016-09-19 11:55:44 +02001086 wide = PyUnicode_AsUnicodeAndSize(o, &length);
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001087_Py_COMP_DIAG_POP
1088#else /* USE_UNICODE_WCHAR_CACHE */
1089 wide = PyUnicode_AsWideCharString(o, &length);
1090#endif /* USE_UNICODE_WCHAR_CACHE */
Victor Stinner59799a82013-11-13 14:17:30 +01001091 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001092 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001093 }
Victor Stinner59799a82013-11-13 14:17:30 +01001094 if (length > 32767) {
1095 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001096 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001097 }
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001098 if (wcslen(wide) != length) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001099 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001100 goto error_exit;
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001101 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001102
1103 path->wide = wide;
Xiang Zhang04316c42017-01-08 23:26:57 +08001104 path->narrow = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001105 path->fd = -1;
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001106#if !USE_UNICODE_WCHAR_CACHE
1107 wide = NULL;
1108#endif /* USE_UNICODE_WCHAR_CACHE */
Xiang Zhang04316c42017-01-08 23:26:57 +08001109 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001110#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001111 if (!PyUnicode_FSConverter(o, &bytes)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001112 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001113 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001114#endif
1115 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001116 else if (is_bytes) {
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001117 bytes = o;
1118 Py_INCREF(bytes);
1119 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001120 else if (is_buffer) {
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03001121 /* XXX Replace PyObject_CheckBuffer with PyBytes_Check in other code
Ville Skyttä49b27342017-08-03 09:00:59 +03001122 after removing support of non-bytes buffer objects. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001123 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1124 "%s%s%s should be %s, not %.200s",
1125 path->function_name ? path->function_name : "",
1126 path->function_name ? ": " : "",
1127 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001128 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1129 "integer or None" :
1130 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1131 path->nullable ? "string, bytes, os.PathLike or None" :
1132 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001133 _PyType_Name(Py_TYPE(o)))) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001134 goto error_exit;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001135 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001136 bytes = PyBytes_FromObject(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001137 if (!bytes) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001138 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001139 }
1140 }
Steve Dowercc16be82016-09-08 10:35:16 -07001141 else if (is_index) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001142 if (!_fd_converter(o, &path->fd)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001143 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001144 }
1145 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001146#ifdef MS_WINDOWS
1147 path->narrow = FALSE;
1148#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001149 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001150#endif
Xiang Zhang04316c42017-01-08 23:26:57 +08001151 goto success_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001152 }
1153 else {
Xiang Zhang04316c42017-01-08 23:26:57 +08001154 error_format:
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001155 PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
1156 path->function_name ? path->function_name : "",
1157 path->function_name ? ": " : "",
1158 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001159 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1160 "integer or None" :
1161 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1162 path->nullable ? "string, bytes, os.PathLike or None" :
1163 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001164 _PyType_Name(Py_TYPE(o)));
Xiang Zhang04316c42017-01-08 23:26:57 +08001165 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001166 }
1167
Larry Hastings9cf065c2012-06-22 16:30:09 -07001168 length = PyBytes_GET_SIZE(bytes);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001169 narrow = PyBytes_AS_STRING(bytes);
Victor Stinner706768c2014-08-16 01:03:39 +02001170 if ((size_t)length != strlen(narrow)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03001171 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001172 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001173 }
1174
Steve Dowercc16be82016-09-08 10:35:16 -07001175#ifdef MS_WINDOWS
1176 wo = PyUnicode_DecodeFSDefaultAndSize(
1177 narrow,
1178 length
1179 );
1180 if (!wo) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001181 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001182 }
1183
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001184#if USE_UNICODE_WCHAR_CACHE
1185_Py_COMP_DIAG_PUSH
1186_Py_COMP_DIAG_IGNORE_DEPR_DECLS
Xiang Zhang04316c42017-01-08 23:26:57 +08001187 wide = PyUnicode_AsUnicodeAndSize(wo, &length);
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001188_Py_COMP_DIAG_POP
1189#else /* USE_UNICODE_WCHAR_CACHE */
1190 wide = PyUnicode_AsWideCharString(wo, &length);
1191 Py_DECREF(wo);
1192#endif /* USE_UNICODE_WCHAR_CACHE */
Steve Dowercc16be82016-09-08 10:35:16 -07001193 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001194 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001195 }
1196 if (length > 32767) {
1197 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001198 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001199 }
1200 if (wcslen(wide) != length) {
1201 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001202 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001203 }
1204 path->wide = wide;
1205 path->narrow = TRUE;
Xiang Zhang04316c42017-01-08 23:26:57 +08001206 Py_DECREF(bytes);
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001207#if USE_UNICODE_WCHAR_CACHE
1208 path->cleanup = wo;
1209#else /* USE_UNICODE_WCHAR_CACHE */
1210 wide = NULL;
1211#endif /* USE_UNICODE_WCHAR_CACHE */
Steve Dowercc16be82016-09-08 10:35:16 -07001212#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001213 path->wide = NULL;
1214 path->narrow = narrow;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001215 if (bytes == o) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001216 /* Still a reference owned by path->object, don't have to
1217 worry about path->narrow is used after free. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001218 Py_DECREF(bytes);
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001219 }
1220 else {
1221 path->cleanup = bytes;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001222 }
Xiang Zhang04316c42017-01-08 23:26:57 +08001223#endif
1224 path->fd = -1;
1225
1226 success_exit:
1227 path->length = length;
1228 path->object = o;
1229 return Py_CLEANUP_SUPPORTED;
1230
1231 error_exit:
1232 Py_XDECREF(o);
1233 Py_XDECREF(bytes);
1234#ifdef MS_WINDOWS
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001235#if USE_UNICODE_WCHAR_CACHE
Xiang Zhang04316c42017-01-08 23:26:57 +08001236 Py_XDECREF(wo);
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001237#else /* USE_UNICODE_WCHAR_CACHE */
1238 PyMem_Free(wide);
1239#endif /* USE_UNICODE_WCHAR_CACHE */
Xiang Zhang04316c42017-01-08 23:26:57 +08001240#endif
1241 return 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001242}
1243
1244static void
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001245argument_unavailable_error(const char *function_name, const char *argument_name)
1246{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001247 PyErr_Format(PyExc_NotImplementedError,
1248 "%s%s%s unavailable on this platform",
1249 (function_name != NULL) ? function_name : "",
1250 (function_name != NULL) ? ": ": "",
1251 argument_name);
1252}
1253
1254static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001255dir_fd_unavailable(PyObject *o, void *p)
1256{
1257 int dir_fd;
1258 if (!dir_fd_converter(o, &dir_fd))
Larry Hastings9cf065c2012-06-22 16:30:09 -07001259 return 0;
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001260 if (dir_fd != DEFAULT_DIR_FD) {
1261 argument_unavailable_error(NULL, "dir_fd");
1262 return 0;
1263 }
1264 *(int *)p = dir_fd;
1265 return 1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001266}
1267
1268static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001269fd_specified(const char *function_name, int fd)
1270{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001271 if (fd == -1)
1272 return 0;
1273
1274 argument_unavailable_error(function_name, "fd");
1275 return 1;
1276}
1277
1278static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001279follow_symlinks_specified(const char *function_name, int follow_symlinks)
1280{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001281 if (follow_symlinks)
1282 return 0;
1283
1284 argument_unavailable_error(function_name, "follow_symlinks");
1285 return 1;
1286}
1287
1288static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001289path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
1290{
Steve Dowercc16be82016-09-08 10:35:16 -07001291 if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
1292#ifndef MS_WINDOWS
1293 && !path->narrow
1294#endif
1295 ) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001296 PyErr_Format(PyExc_ValueError,
1297 "%s: can't specify dir_fd without matching path",
1298 function_name);
1299 return 1;
1300 }
1301 return 0;
1302}
1303
1304static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001305dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
1306{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001307 if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
1308 PyErr_Format(PyExc_ValueError,
1309 "%s: can't specify both dir_fd and fd",
1310 function_name);
1311 return 1;
1312 }
1313 return 0;
1314}
1315
1316static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001317fd_and_follow_symlinks_invalid(const char *function_name, int fd,
1318 int follow_symlinks)
1319{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001320 if ((fd > 0) && (!follow_symlinks)) {
1321 PyErr_Format(PyExc_ValueError,
1322 "%s: cannot use fd and follow_symlinks together",
1323 function_name);
1324 return 1;
1325 }
1326 return 0;
1327}
1328
1329static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001330dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
1331 int follow_symlinks)
1332{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001333 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
1334 PyErr_Format(PyExc_ValueError,
1335 "%s: cannot use dir_fd and follow_symlinks together",
1336 function_name);
1337 return 1;
1338 }
1339 return 0;
1340}
1341
Larry Hastings2f936352014-08-05 14:04:04 +10001342#ifdef MS_WINDOWS
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001343 typedef long long Py_off_t;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001344#else
Larry Hastings2f936352014-08-05 14:04:04 +10001345 typedef off_t Py_off_t;
1346#endif
1347
1348static int
1349Py_off_t_converter(PyObject *arg, void *addr)
1350{
1351#ifdef HAVE_LARGEFILE_SUPPORT
1352 *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
1353#else
1354 *((Py_off_t *)addr) = PyLong_AsLong(arg);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001355#endif
1356 if (PyErr_Occurred())
1357 return 0;
1358 return 1;
1359}
Larry Hastings2f936352014-08-05 14:04:04 +10001360
1361static PyObject *
1362PyLong_FromPy_off_t(Py_off_t offset)
1363{
1364#ifdef HAVE_LARGEFILE_SUPPORT
1365 return PyLong_FromLongLong(offset);
1366#else
1367 return PyLong_FromLong(offset);
Ross Lagerwallb1e5d592011-09-19 08:30:43 +02001368#endif
Larry Hastings2f936352014-08-05 14:04:04 +10001369}
1370
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001371#ifdef HAVE_SIGSET_T
1372/* Convert an iterable of integers to a sigset.
1373 Return 1 on success, return 0 and raise an exception on error. */
1374int
1375_Py_Sigset_Converter(PyObject *obj, void *addr)
1376{
1377 sigset_t *mask = (sigset_t *)addr;
1378 PyObject *iterator, *item;
1379 long signum;
1380 int overflow;
1381
Rémi Lapeyref0900192019-05-04 01:30:53 +02001382 // The extra parens suppress the unreachable-code warning with clang on MacOS
1383 if (sigemptyset(mask) < (0)) {
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001384 /* Probably only if mask == NULL. */
1385 PyErr_SetFromErrno(PyExc_OSError);
1386 return 0;
1387 }
1388
1389 iterator = PyObject_GetIter(obj);
1390 if (iterator == NULL) {
1391 return 0;
1392 }
1393
1394 while ((item = PyIter_Next(iterator)) != NULL) {
1395 signum = PyLong_AsLongAndOverflow(item, &overflow);
1396 Py_DECREF(item);
1397 if (signum <= 0 || signum >= NSIG) {
1398 if (overflow || signum != -1 || !PyErr_Occurred()) {
1399 PyErr_Format(PyExc_ValueError,
1400 "signal number %ld out of range", signum);
1401 }
1402 goto error;
1403 }
1404 if (sigaddset(mask, (int)signum)) {
1405 if (errno != EINVAL) {
1406 /* Probably impossible */
1407 PyErr_SetFromErrno(PyExc_OSError);
1408 goto error;
1409 }
1410 /* For backwards compatibility, allow idioms such as
1411 * `range(1, NSIG)` but warn about invalid signal numbers
1412 */
1413 const char msg[] =
1414 "invalid signal number %ld, please use valid_signals()";
1415 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
1416 goto error;
1417 }
1418 }
1419 }
1420 if (!PyErr_Occurred()) {
1421 Py_DECREF(iterator);
1422 return 1;
1423 }
1424
1425error:
1426 Py_DECREF(iterator);
1427 return 0;
1428}
1429#endif /* HAVE_SIGSET_T */
1430
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001431#ifdef MS_WINDOWS
Brian Curtinf5e76d02010-11-24 13:14:05 +00001432
1433static int
Brian Curtind25aef52011-06-13 15:16:04 -05001434win32_get_reparse_tag(HANDLE reparse_point_handle, ULONG *reparse_tag)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001435{
Martin Panter70214ad2016-08-04 02:38:59 +00001436 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1437 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001438 DWORD n_bytes_returned;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001439
1440 if (0 == DeviceIoControl(
1441 reparse_point_handle,
1442 FSCTL_GET_REPARSE_POINT,
1443 NULL, 0, /* in buffer */
1444 target_buffer, sizeof(target_buffer),
1445 &n_bytes_returned,
1446 NULL)) /* we're not using OVERLAPPED_IO */
Brian Curtind25aef52011-06-13 15:16:04 -05001447 return FALSE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001448
1449 if (reparse_tag)
1450 *reparse_tag = rdb->ReparseTag;
1451
Brian Curtind25aef52011-06-13 15:16:04 -05001452 return TRUE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001453}
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001454
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001455#endif /* MS_WINDOWS */
Brian Curtinf5e76d02010-11-24 13:14:05 +00001456
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001457/* Return a dictionary corresponding to the POSIX environment table */
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001458#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Jack Jansenea0c3822002-08-01 21:57:49 +00001459/* On Darwin/MacOSX a shared library or framework has no access to
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001460** environ directly, we must obtain it with _NSGetEnviron(). See also
1461** man environ(7).
Jack Jansenea0c3822002-08-01 21:57:49 +00001462*/
1463#include <crt_externs.h>
pxinwrf2d7ac72019-05-21 18:46:37 +08001464#elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001465extern char **environ;
Guido van Rossuma4916fa1996-05-23 22:58:55 +00001466#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001467
Barry Warsaw53699e91996-12-10 23:23:01 +00001468static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001469convertenviron(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001470{
Victor Stinner8c62be82010-05-06 00:08:46 +00001471 PyObject *d;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001472#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00001473 wchar_t **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001474#else
Victor Stinner8c62be82010-05-06 00:08:46 +00001475 char **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001476#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +00001477
Victor Stinner8c62be82010-05-06 00:08:46 +00001478 d = PyDict_New();
1479 if (d == NULL)
1480 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001481#ifdef MS_WINDOWS
1482 /* _wenviron must be initialized in this way if the program is started
1483 through main() instead of wmain(). */
1484 _wgetenv(L"");
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001485 e = _wenviron;
Benoit Hudson723f71a2019-12-06 14:15:03 -05001486#elif defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
1487 /* environ is not accessible as an extern in a shared object on OSX; use
1488 _NSGetEnviron to resolve it. The value changes if you add environment
1489 variables between calls to Py_Initialize, so don't cache the value. */
1490 e = *_NSGetEnviron();
Victor Stinner8c62be82010-05-06 00:08:46 +00001491#else
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001492 e = environ;
1493#endif
1494 if (e == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +00001495 return d;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001496 for (; *e != NULL; e++) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001497 PyObject *k;
1498 PyObject *v;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001499#ifdef MS_WINDOWS
1500 const wchar_t *p = wcschr(*e, L'=');
1501#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03001502 const char *p = strchr(*e, '=');
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001503#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001504 if (p == NULL)
1505 continue;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001506#ifdef MS_WINDOWS
1507 k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
1508#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001509 k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001510#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001511 if (k == NULL) {
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001512 Py_DECREF(d);
1513 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001514 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001515#ifdef MS_WINDOWS
1516 v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
1517#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001518 v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001519#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001520 if (v == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001521 Py_DECREF(k);
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001522 Py_DECREF(d);
1523 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001524 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001525 if (PyDict_GetItemWithError(d, k) == NULL) {
1526 if (PyErr_Occurred() || PyDict_SetItem(d, k, v) != 0) {
1527 Py_DECREF(v);
1528 Py_DECREF(k);
1529 Py_DECREF(d);
1530 return NULL;
1531 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001532 }
1533 Py_DECREF(k);
1534 Py_DECREF(v);
Guido van Rossumd48f2521997-12-05 22:19:34 +00001535 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001536 return d;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001537}
1538
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001539/* Set a POSIX-specific error from errno, and return NULL */
1540
Barry Warsawd58d7641998-07-23 16:14:40 +00001541static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001542posix_error(void)
Guido van Rossumad0ee831995-03-01 10:34:45 +00001543{
Victor Stinner8c62be82010-05-06 00:08:46 +00001544 return PyErr_SetFromErrno(PyExc_OSError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001545}
Mark Hammondef8b6542001-05-13 08:04:26 +00001546
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001547#ifdef MS_WINDOWS
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001548static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001549win32_error(const char* function, const char* filename)
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001550{
Victor Stinner8c62be82010-05-06 00:08:46 +00001551 /* XXX We should pass the function name along in the future.
1552 (winreg.c also wants to pass the function name.)
1553 This would however require an additional param to the
1554 Windows error object, which is non-trivial.
1555 */
1556 errno = GetLastError();
1557 if (filename)
1558 return PyErr_SetFromWindowsErrWithFilename(errno, filename);
1559 else
1560 return PyErr_SetFromWindowsErr(errno);
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001561}
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001562
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001563static PyObject *
Steve Dower2438cdf2019-03-29 16:37:16 -07001564win32_error_object_err(const char* function, PyObject* filename, DWORD err)
Victor Stinnereb5657a2011-09-30 01:44:27 +02001565{
1566 /* XXX - see win32_error for comments on 'function' */
Victor Stinnereb5657a2011-09-30 01:44:27 +02001567 if (filename)
1568 return PyErr_SetExcFromWindowsErrWithFilenameObject(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001569 PyExc_OSError,
Steve Dower2438cdf2019-03-29 16:37:16 -07001570 err,
Victor Stinnereb5657a2011-09-30 01:44:27 +02001571 filename);
1572 else
Steve Dower2438cdf2019-03-29 16:37:16 -07001573 return PyErr_SetFromWindowsErr(err);
1574}
1575
1576static PyObject *
1577win32_error_object(const char* function, PyObject* filename)
1578{
1579 errno = GetLastError();
1580 return win32_error_object_err(function, filename, errno);
Victor Stinnereb5657a2011-09-30 01:44:27 +02001581}
1582
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001583#endif /* MS_WINDOWS */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001584
Larry Hastings9cf065c2012-06-22 16:30:09 -07001585static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001586posix_path_object_error(PyObject *path)
1587{
1588 return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
1589}
1590
1591static PyObject *
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001592path_object_error(PyObject *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001593{
1594#ifdef MS_WINDOWS
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001595 return PyErr_SetExcFromWindowsErrWithFilenameObject(
1596 PyExc_OSError, 0, path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001597#else
Alexey Izbyshev83460312018-10-20 03:28:22 +03001598 return posix_path_object_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001599#endif
1600}
1601
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001602static PyObject *
1603path_object_error2(PyObject *path, PyObject *path2)
1604{
1605#ifdef MS_WINDOWS
1606 return PyErr_SetExcFromWindowsErrWithFilenameObjects(
1607 PyExc_OSError, 0, path, path2);
1608#else
1609 return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
1610#endif
1611}
1612
1613static PyObject *
1614path_error(path_t *path)
1615{
1616 return path_object_error(path->object);
1617}
Larry Hastings31826802013-10-19 00:09:25 -07001618
Larry Hastingsb0827312014-02-09 22:05:19 -08001619static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001620posix_path_error(path_t *path)
1621{
1622 return posix_path_object_error(path->object);
1623}
1624
1625static PyObject *
Larry Hastingsb0827312014-02-09 22:05:19 -08001626path_error2(path_t *path, path_t *path2)
1627{
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001628 return path_object_error2(path->object, path2->object);
Larry Hastingsb0827312014-02-09 22:05:19 -08001629}
1630
1631
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001632/* POSIX generic methods */
1633
Larry Hastings2f936352014-08-05 14:04:04 +10001634static int
1635fildes_converter(PyObject *o, void *p)
Fred Drake4d1e64b2002-04-15 19:40:07 +00001636{
Victor Stinner8c62be82010-05-06 00:08:46 +00001637 int fd;
Larry Hastings2f936352014-08-05 14:04:04 +10001638 int *pointer = (int *)p;
1639 fd = PyObject_AsFileDescriptor(o);
Victor Stinner8c62be82010-05-06 00:08:46 +00001640 if (fd < 0)
Larry Hastings2f936352014-08-05 14:04:04 +10001641 return 0;
Larry Hastings2f936352014-08-05 14:04:04 +10001642 *pointer = fd;
1643 return 1;
1644}
1645
1646static PyObject *
1647posix_fildes_fd(int fd, int (*func)(int))
1648{
1649 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001650 int async_err = 0;
1651
1652 do {
1653 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001654 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001655 res = (*func)(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001656 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001657 Py_END_ALLOW_THREADS
1658 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1659 if (res != 0)
1660 return (!async_err) ? posix_error() : NULL;
1661 Py_RETURN_NONE;
Fred Drake4d1e64b2002-04-15 19:40:07 +00001662}
Guido van Rossum21142a01999-01-08 21:05:37 +00001663
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001664
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001665#ifdef MS_WINDOWS
Thomas Wouters477c8d52006-05-27 19:21:47 +00001666/* This is a reimplementation of the C library's chdir function,
1667 but one that produces Win32 errors instead of DOS error codes.
1668 chdir is essentially a wrapper around SetCurrentDirectory; however,
1669 it also needs to set "magic" environment variables indicating
1670 the per-drive current directory, which are of the form =<drive>: */
Benjamin Peterson206e3072008-10-19 14:07:49 +00001671static BOOL __stdcall
Thomas Wouters477c8d52006-05-27 19:21:47 +00001672win32_wchdir(LPCWSTR path)
1673{
Victor Stinnered537822015-12-13 21:40:26 +01001674 wchar_t path_buf[MAX_PATH], *new_path = path_buf;
Victor Stinner8c62be82010-05-06 00:08:46 +00001675 int result;
1676 wchar_t env[4] = L"=x:";
Thomas Wouters477c8d52006-05-27 19:21:47 +00001677
Victor Stinner8c62be82010-05-06 00:08:46 +00001678 if(!SetCurrentDirectoryW(path))
1679 return FALSE;
Victor Stinnered537822015-12-13 21:40:26 +01001680 result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001681 if (!result)
1682 return FALSE;
Victor Stinnere847d712015-12-14 00:21:50 +01001683 if (result > Py_ARRAY_LENGTH(path_buf)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001684 new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00001685 if (!new_path) {
1686 SetLastError(ERROR_OUTOFMEMORY);
1687 return FALSE;
1688 }
1689 result = GetCurrentDirectoryW(result, new_path);
1690 if (!result) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001691 PyMem_RawFree(new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001692 return FALSE;
1693 }
1694 }
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001695 int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
1696 wcsncmp(new_path, L"//", 2) == 0);
1697 if (!is_unc_like_path) {
1698 env[1] = new_path[0];
1699 result = SetEnvironmentVariableW(env, new_path);
1700 }
Victor Stinnered537822015-12-13 21:40:26 +01001701 if (new_path != path_buf)
Victor Stinnerb6404912013-07-07 16:21:41 +02001702 PyMem_RawFree(new_path);
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001703 return result ? TRUE : FALSE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001704}
1705#endif
1706
Martin v. Löwis14694662006-02-03 12:54:16 +00001707#ifdef MS_WINDOWS
1708/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
1709 - time stamps are restricted to second resolution
1710 - file modification times suffer from forth-and-back conversions between
1711 UTC and local time
1712 Therefore, we implement our own stat, based on the Win32 API directly.
1713*/
Victor Stinner8c62be82010-05-06 00:08:46 +00001714#define HAVE_STAT_NSEC 1
Zachary Ware63f277b2014-06-19 09:46:37 -05001715#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001716#define HAVE_STRUCT_STAT_ST_REPARSE_TAG 1
Martin v. Löwis14694662006-02-03 12:54:16 +00001717
Victor Stinner6036e442015-03-08 01:58:04 +01001718static void
Steve Dowercc16be82016-09-08 10:35:16 -07001719find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
1720 BY_HANDLE_FILE_INFORMATION *info,
1721 ULONG *reparse_tag)
Victor Stinner6036e442015-03-08 01:58:04 +01001722{
1723 memset(info, 0, sizeof(*info));
1724 info->dwFileAttributes = pFileData->dwFileAttributes;
1725 info->ftCreationTime = pFileData->ftCreationTime;
1726 info->ftLastAccessTime = pFileData->ftLastAccessTime;
1727 info->ftLastWriteTime = pFileData->ftLastWriteTime;
1728 info->nFileSizeHigh = pFileData->nFileSizeHigh;
1729 info->nFileSizeLow = pFileData->nFileSizeLow;
1730/* info->nNumberOfLinks = 1; */
1731 if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
1732 *reparse_tag = pFileData->dwReserved0;
1733 else
1734 *reparse_tag = 0;
1735}
1736
Guido van Rossumd8faa362007-04-27 19:54:29 +00001737static BOOL
Steve Dowercc16be82016-09-08 10:35:16 -07001738attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001739{
Victor Stinner8c62be82010-05-06 00:08:46 +00001740 HANDLE hFindFile;
1741 WIN32_FIND_DATAW FileData;
1742 hFindFile = FindFirstFileW(pszFile, &FileData);
1743 if (hFindFile == INVALID_HANDLE_VALUE)
1744 return FALSE;
1745 FindClose(hFindFile);
Steve Dowercc16be82016-09-08 10:35:16 -07001746 find_data_to_file_info(&FileData, info, reparse_tag);
Victor Stinner8c62be82010-05-06 00:08:46 +00001747 return TRUE;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001748}
1749
Brian Curtind25aef52011-06-13 15:16:04 -05001750static int
Steve Dowercc16be82016-09-08 10:35:16 -07001751win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
Brian Curtind25aef52011-06-13 15:16:04 -05001752 BOOL traverse)
1753{
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001754 HANDLE hFile;
1755 BY_HANDLE_FILE_INFORMATION fileInfo;
1756 FILE_ATTRIBUTE_TAG_INFO tagInfo = { 0 };
1757 DWORD fileType, error;
1758 BOOL isUnhandledTag = FALSE;
1759 int retval = 0;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001760
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001761 DWORD access = FILE_READ_ATTRIBUTES;
1762 DWORD flags = FILE_FLAG_BACKUP_SEMANTICS; /* Allow opening directories. */
1763 if (!traverse) {
1764 flags |= FILE_FLAG_OPEN_REPARSE_POINT;
1765 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001766
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001767 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING, flags, NULL);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001768 if (hFile == INVALID_HANDLE_VALUE) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001769 /* Either the path doesn't exist, or the caller lacks access. */
1770 error = GetLastError();
1771 switch (error) {
1772 case ERROR_ACCESS_DENIED: /* Cannot sync or read attributes. */
1773 case ERROR_SHARING_VIOLATION: /* It's a paging file. */
1774 /* Try reading the parent directory. */
1775 if (!attributes_from_dir(path, &fileInfo, &tagInfo.ReparseTag)) {
1776 /* Cannot read the parent directory. */
1777 SetLastError(error);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001778 return -1;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001779 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001780 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1781 if (traverse ||
1782 !IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1783 /* The stat call has to traverse but cannot, so fail. */
1784 SetLastError(error);
Brian Curtind25aef52011-06-13 15:16:04 -05001785 return -1;
Mark Becwarb82bfac2019-02-02 16:08:23 -05001786 }
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001787 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001788 break;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001789
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001790 case ERROR_INVALID_PARAMETER:
1791 /* \\.\con requires read or write access. */
1792 hFile = CreateFileW(path, access | GENERIC_READ,
1793 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1794 OPEN_EXISTING, flags, NULL);
1795 if (hFile == INVALID_HANDLE_VALUE) {
1796 SetLastError(error);
1797 return -1;
1798 }
1799 break;
1800
1801 case ERROR_CANT_ACCESS_FILE:
1802 /* bpo37834: open unhandled reparse points if traverse fails. */
1803 if (traverse) {
1804 traverse = FALSE;
1805 isUnhandledTag = TRUE;
1806 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING,
1807 flags | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
1808 }
1809 if (hFile == INVALID_HANDLE_VALUE) {
1810 SetLastError(error);
1811 return -1;
1812 }
1813 break;
1814
1815 default:
1816 return -1;
1817 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001818 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001819
1820 if (hFile != INVALID_HANDLE_VALUE) {
1821 /* Handle types other than files on disk. */
1822 fileType = GetFileType(hFile);
1823 if (fileType != FILE_TYPE_DISK) {
1824 if (fileType == FILE_TYPE_UNKNOWN && GetLastError() != 0) {
1825 retval = -1;
1826 goto cleanup;
1827 }
1828 DWORD fileAttributes = GetFileAttributesW(path);
1829 memset(result, 0, sizeof(*result));
1830 if (fileAttributes != INVALID_FILE_ATTRIBUTES &&
1831 fileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1832 /* \\.\pipe\ or \\.\mailslot\ */
1833 result->st_mode = _S_IFDIR;
1834 } else if (fileType == FILE_TYPE_CHAR) {
1835 /* \\.\nul */
1836 result->st_mode = _S_IFCHR;
1837 } else if (fileType == FILE_TYPE_PIPE) {
1838 /* \\.\pipe\spam */
1839 result->st_mode = _S_IFIFO;
1840 }
1841 /* FILE_TYPE_UNKNOWN, e.g. \\.\mailslot\waitfor.exe\spam */
1842 goto cleanup;
1843 }
1844
1845 /* Query the reparse tag, and traverse a non-link. */
1846 if (!traverse) {
1847 if (!GetFileInformationByHandleEx(hFile, FileAttributeTagInfo,
1848 &tagInfo, sizeof(tagInfo))) {
1849 /* Allow devices that do not support FileAttributeTagInfo. */
1850 switch (GetLastError()) {
1851 case ERROR_INVALID_PARAMETER:
1852 case ERROR_INVALID_FUNCTION:
1853 case ERROR_NOT_SUPPORTED:
1854 tagInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1855 tagInfo.ReparseTag = 0;
1856 break;
1857 default:
1858 retval = -1;
1859 goto cleanup;
1860 }
1861 } else if (tagInfo.FileAttributes &
1862 FILE_ATTRIBUTE_REPARSE_POINT) {
1863 if (IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1864 if (isUnhandledTag) {
1865 /* Traversing previously failed for either this link
1866 or its target. */
1867 SetLastError(ERROR_CANT_ACCESS_FILE);
1868 retval = -1;
1869 goto cleanup;
1870 }
1871 /* Traverse a non-link, but not if traversing already failed
1872 for an unhandled tag. */
1873 } else if (!isUnhandledTag) {
1874 CloseHandle(hFile);
1875 return win32_xstat_impl(path, result, TRUE);
1876 }
1877 }
1878 }
1879
1880 if (!GetFileInformationByHandle(hFile, &fileInfo)) {
1881 switch (GetLastError()) {
1882 case ERROR_INVALID_PARAMETER:
1883 case ERROR_INVALID_FUNCTION:
1884 case ERROR_NOT_SUPPORTED:
Steve Dower772ec0f2019-09-04 14:42:54 -07001885 /* Volumes and physical disks are block devices, e.g.
1886 \\.\C: and \\.\PhysicalDrive0. */
1887 memset(result, 0, sizeof(*result));
1888 result->st_mode = 0x6000; /* S_IFBLK */
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001889 goto cleanup;
1890 }
Steve Dower772ec0f2019-09-04 14:42:54 -07001891 retval = -1;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001892 goto cleanup;
1893 }
1894 }
1895
1896 _Py_attribute_data_to_stat(&fileInfo, tagInfo.ReparseTag, result);
1897
1898 if (!(fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
1899 /* Fix the file execute permissions. This hack sets S_IEXEC if
1900 the filename has an extension that is commonly used by files
1901 that CreateProcessW can execute. A real implementation calls
1902 GetSecurityInfo, OpenThreadToken/OpenProcessToken, and
1903 AccessCheck to check for generic read, write, and execute
1904 access. */
1905 const wchar_t *fileExtension = wcsrchr(path, '.');
1906 if (fileExtension) {
1907 if (_wcsicmp(fileExtension, L".exe") == 0 ||
1908 _wcsicmp(fileExtension, L".bat") == 0 ||
1909 _wcsicmp(fileExtension, L".cmd") == 0 ||
1910 _wcsicmp(fileExtension, L".com") == 0) {
1911 result->st_mode |= 0111;
1912 }
1913 }
1914 }
1915
1916cleanup:
1917 if (hFile != INVALID_HANDLE_VALUE) {
Steve Dower772ec0f2019-09-04 14:42:54 -07001918 /* Preserve last error if we are failing */
1919 error = retval ? GetLastError() : 0;
1920 if (!CloseHandle(hFile)) {
1921 retval = -1;
1922 } else if (retval) {
1923 /* Restore last error */
1924 SetLastError(error);
1925 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001926 }
1927
1928 return retval;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001929}
1930
1931static int
Steve Dowercc16be82016-09-08 10:35:16 -07001932win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001933{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001934 /* Protocol violation: we explicitly clear errno, instead of
1935 setting it to a POSIX error. Callers should use GetLastError. */
Brian Curtind25aef52011-06-13 15:16:04 -05001936 int code = win32_xstat_impl(path, result, traverse);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001937 errno = 0;
1938 return code;
1939}
Brian Curtind25aef52011-06-13 15:16:04 -05001940/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
Brian Curtind40e6f72010-07-08 21:39:08 +00001941
1942 In Posix, stat automatically traverses symlinks and returns the stat
1943 structure for the target. In Windows, the equivalent GetFileAttributes by
1944 default does not traverse symlinks and instead returns attributes for
1945 the symlink.
1946
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001947 Instead, we will open the file (which *does* traverse symlinks by default)
1948 and GetFileInformationByHandle(). */
Brian Curtind40e6f72010-07-08 21:39:08 +00001949
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001950static int
Steve Dowercc16be82016-09-08 10:35:16 -07001951win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
Martin v. Löwis14694662006-02-03 12:54:16 +00001952{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001953 return win32_xstat(path, result, FALSE);
Martin v. Löwis14694662006-02-03 12:54:16 +00001954}
1955
Victor Stinner8c62be82010-05-06 00:08:46 +00001956static int
Steve Dowercc16be82016-09-08 10:35:16 -07001957win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
Brian Curtind40e6f72010-07-08 21:39:08 +00001958{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001959 return win32_xstat(path, result, TRUE);
Brian Curtind40e6f72010-07-08 21:39:08 +00001960}
1961
Martin v. Löwis14694662006-02-03 12:54:16 +00001962#endif /* MS_WINDOWS */
1963
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001964PyDoc_STRVAR(stat_result__doc__,
Larry Hastings9cf065c2012-06-22 16:30:09 -07001965"stat_result: Result from stat, fstat, or lstat.\n\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001966This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001967 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001968or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1969\n\
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001970Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1971or st_flags, they are available as attributes only.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001972\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001973See os.stat for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001974
1975static PyStructSequence_Field stat_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001976 {"st_mode", "protection bits"},
1977 {"st_ino", "inode"},
1978 {"st_dev", "device"},
1979 {"st_nlink", "number of hard links"},
1980 {"st_uid", "user ID of owner"},
1981 {"st_gid", "group ID of owner"},
1982 {"st_size", "total size, in bytes"},
1983 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1984 {NULL, "integer time of last access"},
1985 {NULL, "integer time of last modification"},
1986 {NULL, "integer time of last change"},
1987 {"st_atime", "time of last access"},
1988 {"st_mtime", "time of last modification"},
1989 {"st_ctime", "time of last change"},
Larry Hastings6fe20b32012-04-19 15:07:49 -07001990 {"st_atime_ns", "time of last access in nanoseconds"},
1991 {"st_mtime_ns", "time of last modification in nanoseconds"},
1992 {"st_ctime_ns", "time of last change in nanoseconds"},
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001993#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00001994 {"st_blksize", "blocksize for filesystem I/O"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001995#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001996#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00001997 {"st_blocks", "number of blocks allocated"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001998#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001999#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00002000 {"st_rdev", "device type (if inode device)"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002001#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002002#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00002003 {"st_flags", "user defined flags for file"},
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002004#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002005#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00002006 {"st_gen", "generation number"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002007#endif
2008#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00002009 {"st_birthtime", "time of creation"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002010#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05002011#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2012 {"st_file_attributes", "Windows file attribute bits"},
2013#endif
jcea6c51d512018-01-28 14:00:08 +01002014#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2015 {"st_fstype", "Type of filesystem"},
2016#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002017#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2018 {"st_reparse_tag", "Windows reparse tag"},
2019#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002020 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002021};
2022
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002023#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Larry Hastings6fe20b32012-04-19 15:07:49 -07002024#define ST_BLKSIZE_IDX 16
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002025#else
Larry Hastings6fe20b32012-04-19 15:07:49 -07002026#define ST_BLKSIZE_IDX 15
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002027#endif
2028
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002029#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002030#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
2031#else
2032#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
2033#endif
2034
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002035#ifdef HAVE_STRUCT_STAT_ST_RDEV
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002036#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
2037#else
2038#define ST_RDEV_IDX ST_BLOCKS_IDX
2039#endif
2040
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002041#ifdef HAVE_STRUCT_STAT_ST_FLAGS
2042#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
2043#else
2044#define ST_FLAGS_IDX ST_RDEV_IDX
2045#endif
2046
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002047#ifdef HAVE_STRUCT_STAT_ST_GEN
Martin v. Löwisf09582e2005-08-14 21:42:34 +00002048#define ST_GEN_IDX (ST_FLAGS_IDX+1)
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002049#else
Martin v. Löwisf09582e2005-08-14 21:42:34 +00002050#define ST_GEN_IDX ST_FLAGS_IDX
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002051#endif
2052
2053#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
2054#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
2055#else
2056#define ST_BIRTHTIME_IDX ST_GEN_IDX
2057#endif
2058
Zachary Ware63f277b2014-06-19 09:46:37 -05002059#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2060#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_IDX+1)
2061#else
2062#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_IDX
2063#endif
2064
jcea6c51d512018-01-28 14:00:08 +01002065#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2066#define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
2067#else
2068#define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
2069#endif
2070
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002071#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2072#define ST_REPARSE_TAG_IDX (ST_FSTYPE_IDX+1)
2073#else
2074#define ST_REPARSE_TAG_IDX ST_FSTYPE_IDX
2075#endif
2076
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002077static PyStructSequence_Desc stat_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002078 "stat_result", /* name */
2079 stat_result__doc__, /* doc */
2080 stat_result_fields,
2081 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002082};
2083
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002084PyDoc_STRVAR(statvfs_result__doc__,
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002085"statvfs_result: Result from statvfs or fstatvfs.\n\n\
2086This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00002087 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
Guido van Rossuma4dc73e2001-10-18 20:53:15 +00002088or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002089\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002090See os.statvfs for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002091
2092static PyStructSequence_Field statvfs_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002093 {"f_bsize", },
2094 {"f_frsize", },
2095 {"f_blocks", },
2096 {"f_bfree", },
2097 {"f_bavail", },
2098 {"f_files", },
2099 {"f_ffree", },
2100 {"f_favail", },
2101 {"f_flag", },
2102 {"f_namemax",},
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +01002103 {"f_fsid", },
Victor Stinner8c62be82010-05-06 00:08:46 +00002104 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002105};
2106
2107static PyStructSequence_Desc statvfs_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002108 "statvfs_result", /* name */
2109 statvfs_result__doc__, /* doc */
2110 statvfs_result_fields,
2111 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002112};
2113
Ross Lagerwall7807c352011-03-17 20:20:30 +02002114#if defined(HAVE_WAITID) && !defined(__APPLE__)
2115PyDoc_STRVAR(waitid_result__doc__,
2116"waitid_result: Result from waitid.\n\n\
2117This object may be accessed either as a tuple of\n\
2118 (si_pid, si_uid, si_signo, si_status, si_code),\n\
2119or via the attributes si_pid, si_uid, and so on.\n\
2120\n\
2121See os.waitid for more information.");
2122
2123static PyStructSequence_Field waitid_result_fields[] = {
2124 {"si_pid", },
2125 {"si_uid", },
2126 {"si_signo", },
2127 {"si_status", },
2128 {"si_code", },
2129 {0}
2130};
2131
2132static PyStructSequence_Desc waitid_result_desc = {
2133 "waitid_result", /* name */
2134 waitid_result__doc__, /* doc */
2135 waitid_result_fields,
2136 5
2137};
Benjamin Petersonbad9c2f2011-08-02 18:42:14 -05002138#endif
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002139static newfunc structseq_new;
2140
2141static PyObject *
2142statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2143{
Victor Stinner8c62be82010-05-06 00:08:46 +00002144 PyStructSequence *result;
2145 int i;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002146
Victor Stinner8c62be82010-05-06 00:08:46 +00002147 result = (PyStructSequence*)structseq_new(type, args, kwds);
2148 if (!result)
2149 return NULL;
2150 /* If we have been initialized from a tuple,
2151 st_?time might be set to None. Initialize it
2152 from the int slots. */
2153 for (i = 7; i <= 9; i++) {
2154 if (result->ob_item[i+3] == Py_None) {
2155 Py_DECREF(Py_None);
2156 Py_INCREF(result->ob_item[i]);
2157 result->ob_item[i+3] = result->ob_item[i];
2158 }
2159 }
2160 return (PyObject*)result;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002161}
2162
Eddie Elizondob3966632019-11-05 07:16:14 -08002163static int
2164_posix_clear(PyObject *module)
2165{
Victor Stinner97f33c32020-05-14 18:05:58 +02002166 _posixstate *state = get_posix_state(module);
2167 Py_CLEAR(state->billion);
2168 Py_CLEAR(state->DirEntryType);
2169 Py_CLEAR(state->ScandirIteratorType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002170#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Victor Stinner97f33c32020-05-14 18:05:58 +02002171 Py_CLEAR(state->SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002172#endif
Victor Stinner97f33c32020-05-14 18:05:58 +02002173 Py_CLEAR(state->StatResultType);
2174 Py_CLEAR(state->StatVFSResultType);
2175 Py_CLEAR(state->TerminalSizeType);
2176 Py_CLEAR(state->TimesResultType);
2177 Py_CLEAR(state->UnameResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002178#if defined(HAVE_WAITID) && !defined(__APPLE__)
Victor Stinner97f33c32020-05-14 18:05:58 +02002179 Py_CLEAR(state->WaitidResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002180#endif
2181#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
Victor Stinner97f33c32020-05-14 18:05:58 +02002182 Py_CLEAR(state->struct_rusage);
Eddie Elizondob3966632019-11-05 07:16:14 -08002183#endif
Victor Stinner97f33c32020-05-14 18:05:58 +02002184 Py_CLEAR(state->st_mode);
Eddie Elizondob3966632019-11-05 07:16:14 -08002185 return 0;
2186}
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002187
Eddie Elizondob3966632019-11-05 07:16:14 -08002188static int
2189_posix_traverse(PyObject *module, visitproc visit, void *arg)
2190{
Victor Stinner97f33c32020-05-14 18:05:58 +02002191 _posixstate *state = get_posix_state(module);
2192 Py_VISIT(state->billion);
2193 Py_VISIT(state->DirEntryType);
2194 Py_VISIT(state->ScandirIteratorType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002195#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Victor Stinner97f33c32020-05-14 18:05:58 +02002196 Py_VISIT(state->SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002197#endif
Victor Stinner97f33c32020-05-14 18:05:58 +02002198 Py_VISIT(state->StatResultType);
2199 Py_VISIT(state->StatVFSResultType);
2200 Py_VISIT(state->TerminalSizeType);
2201 Py_VISIT(state->TimesResultType);
2202 Py_VISIT(state->UnameResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002203#if defined(HAVE_WAITID) && !defined(__APPLE__)
Victor Stinner97f33c32020-05-14 18:05:58 +02002204 Py_VISIT(state->WaitidResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002205#endif
2206#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
Victor Stinner97f33c32020-05-14 18:05:58 +02002207 Py_VISIT(state->struct_rusage);
Eddie Elizondob3966632019-11-05 07:16:14 -08002208#endif
Victor Stinner97f33c32020-05-14 18:05:58 +02002209 Py_VISIT(state->st_mode);
Eddie Elizondob3966632019-11-05 07:16:14 -08002210 return 0;
2211}
2212
2213static void
2214_posix_free(void *module)
2215{
2216 _posix_clear((PyObject *)module);
2217}
Larry Hastings6fe20b32012-04-19 15:07:49 -07002218
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002219static void
Victor Stinner1c2fa782020-05-10 11:05:29 +02002220fill_time(PyObject *module, PyObject *v, int index, time_t sec, unsigned long nsec)
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002221{
Larry Hastings6fe20b32012-04-19 15:07:49 -07002222 PyObject *s = _PyLong_FromTime_t(sec);
2223 PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
2224 PyObject *s_in_ns = NULL;
2225 PyObject *ns_total = NULL;
2226 PyObject *float_s = NULL;
2227
2228 if (!(s && ns_fractional))
2229 goto exit;
2230
Victor Stinner1c2fa782020-05-10 11:05:29 +02002231 s_in_ns = PyNumber_Multiply(s, get_posix_state(module)->billion);
Larry Hastings6fe20b32012-04-19 15:07:49 -07002232 if (!s_in_ns)
2233 goto exit;
2234
2235 ns_total = PyNumber_Add(s_in_ns, ns_fractional);
2236 if (!ns_total)
2237 goto exit;
2238
Victor Stinner01b5aab2017-10-24 02:02:00 -07002239 float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
2240 if (!float_s) {
2241 goto exit;
Larry Hastings6fe20b32012-04-19 15:07:49 -07002242 }
2243
2244 PyStructSequence_SET_ITEM(v, index, s);
2245 PyStructSequence_SET_ITEM(v, index+3, float_s);
2246 PyStructSequence_SET_ITEM(v, index+6, ns_total);
2247 s = NULL;
2248 float_s = NULL;
2249 ns_total = NULL;
2250exit:
2251 Py_XDECREF(s);
2252 Py_XDECREF(ns_fractional);
2253 Py_XDECREF(s_in_ns);
2254 Py_XDECREF(ns_total);
2255 Py_XDECREF(float_s);
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002256}
2257
Tim Peters5aa91602002-01-30 05:46:57 +00002258/* pack a system stat C structure into the Python stat tuple
Fred Drake699f3522000-06-29 21:12:41 +00002259 (used by posix_stat() and posix_fstat()) */
2260static PyObject*
Victor Stinner1c2fa782020-05-10 11:05:29 +02002261_pystat_fromstructstat(PyObject *module, STRUCT_STAT *st)
Fred Drake699f3522000-06-29 21:12:41 +00002262{
Victor Stinner8c62be82010-05-06 00:08:46 +00002263 unsigned long ansec, mnsec, cnsec;
Victor Stinner1c2fa782020-05-10 11:05:29 +02002264 PyObject *StatResultType = get_posix_state(module)->StatResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -08002265 PyObject *v = PyStructSequence_New((PyTypeObject *)StatResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +00002266 if (v == NULL)
2267 return NULL;
Fred Drake699f3522000-06-29 21:12:41 +00002268
Victor Stinner8c62be82010-05-06 00:08:46 +00002269 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode));
Victor Stinner0f6d7332017-03-09 17:34:28 +01002270 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(st->st_ino));
xdegaye50e86032017-05-22 11:15:08 +02002271 PyStructSequence_SET_ITEM(v, 1, PyLong_FromUnsignedLongLong(st->st_ino));
Serhiy Storchaka404fa922013-01-02 18:22:23 +02002272#ifdef MS_WINDOWS
2273 PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002274#else
Serhiy Storchakab2653b32015-01-18 11:12:11 +02002275 PyStructSequence_SET_ITEM(v, 2, _PyLong_FromDev(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002276#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002277 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02002278#if defined(MS_WINDOWS)
2279 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong(0));
2280 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong(0));
2281#else
2282 PyStructSequence_SET_ITEM(v, 4, _PyLong_FromUid(st->st_uid));
2283 PyStructSequence_SET_ITEM(v, 5, _PyLong_FromGid(st->st_gid));
2284#endif
xdegaye50e86032017-05-22 11:15:08 +02002285 Py_BUILD_ASSERT(sizeof(long long) >= sizeof(st->st_size));
2286 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLongLong(st->st_size));
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002287
Martin v. Löwis14694662006-02-03 12:54:16 +00002288#if defined(HAVE_STAT_TV_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002289 ansec = st->st_atim.tv_nsec;
2290 mnsec = st->st_mtim.tv_nsec;
2291 cnsec = st->st_ctim.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002292#elif defined(HAVE_STAT_TV_NSEC2)
Victor Stinner8c62be82010-05-06 00:08:46 +00002293 ansec = st->st_atimespec.tv_nsec;
2294 mnsec = st->st_mtimespec.tv_nsec;
2295 cnsec = st->st_ctimespec.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002296#elif defined(HAVE_STAT_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002297 ansec = st->st_atime_nsec;
2298 mnsec = st->st_mtime_nsec;
2299 cnsec = st->st_ctime_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002300#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002301 ansec = mnsec = cnsec = 0;
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002302#endif
Victor Stinner1c2fa782020-05-10 11:05:29 +02002303 fill_time(module, v, 7, st->st_atime, ansec);
2304 fill_time(module, v, 8, st->st_mtime, mnsec);
2305 fill_time(module, v, 9, st->st_ctime, cnsec);
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002306
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002307#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00002308 PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
2309 PyLong_FromLong((long)st->st_blksize));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002310#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002311#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00002312 PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
2313 PyLong_FromLong((long)st->st_blocks));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002314#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002315#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00002316 PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
2317 PyLong_FromLong((long)st->st_rdev));
Fred Drake699f3522000-06-29 21:12:41 +00002318#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002319#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00002320 PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
2321 PyLong_FromLong((long)st->st_gen));
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002322#endif
2323#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00002324 {
Victor Stinner4195b5c2012-02-08 23:03:19 +01002325 PyObject *val;
2326 unsigned long bsec,bnsec;
2327 bsec = (long)st->st_birthtime;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002328#ifdef HAVE_STAT_TV_NSEC2
Victor Stinner4195b5c2012-02-08 23:03:19 +01002329 bnsec = st->st_birthtimespec.tv_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002330#else
Victor Stinner4195b5c2012-02-08 23:03:19 +01002331 bnsec = 0;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002332#endif
Victor Stinner01b5aab2017-10-24 02:02:00 -07002333 val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
Victor Stinner4195b5c2012-02-08 23:03:19 +01002334 PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
2335 val);
Victor Stinner8c62be82010-05-06 00:08:46 +00002336 }
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002337#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002338#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00002339 PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
2340 PyLong_FromLong((long)st->st_flags));
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002341#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05002342#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2343 PyStructSequence_SET_ITEM(v, ST_FILE_ATTRIBUTES_IDX,
2344 PyLong_FromUnsignedLong(st->st_file_attributes));
2345#endif
jcea6c51d512018-01-28 14:00:08 +01002346#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2347 PyStructSequence_SET_ITEM(v, ST_FSTYPE_IDX,
2348 PyUnicode_FromString(st->st_fstype));
2349#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002350#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2351 PyStructSequence_SET_ITEM(v, ST_REPARSE_TAG_IDX,
2352 PyLong_FromUnsignedLong(st->st_reparse_tag));
2353#endif
Fred Drake699f3522000-06-29 21:12:41 +00002354
Victor Stinner8c62be82010-05-06 00:08:46 +00002355 if (PyErr_Occurred()) {
2356 Py_DECREF(v);
2357 return NULL;
2358 }
Fred Drake699f3522000-06-29 21:12:41 +00002359
Victor Stinner8c62be82010-05-06 00:08:46 +00002360 return v;
Fred Drake699f3522000-06-29 21:12:41 +00002361}
2362
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002363/* POSIX methods */
2364
Guido van Rossum94f6f721999-01-06 18:42:14 +00002365
2366static PyObject *
Victor Stinner1c2fa782020-05-10 11:05:29 +02002367posix_do_stat(PyObject *module, const char *function_name, path_t *path,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002368 int dir_fd, int follow_symlinks)
Guido van Rossum94f6f721999-01-06 18:42:14 +00002369{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002370 STRUCT_STAT st;
2371 int result;
2372
2373#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
2374 if (follow_symlinks_specified(function_name, follow_symlinks))
2375 return NULL;
2376#endif
2377
2378 if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
2379 dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
2380 fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
2381 return NULL;
2382
2383 Py_BEGIN_ALLOW_THREADS
2384 if (path->fd != -1)
2385 result = FSTAT(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002386#ifdef MS_WINDOWS
Steve Dower513d7472016-09-08 10:41:50 -07002387 else if (follow_symlinks)
Steve Dowercc16be82016-09-08 10:35:16 -07002388 result = win32_stat(path->wide, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002389 else
Steve Dowercc16be82016-09-08 10:35:16 -07002390 result = win32_lstat(path->wide, &st);
2391#else
2392 else
2393#if defined(HAVE_LSTAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002394 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
2395 result = LSTAT(path->narrow, &st);
2396 else
Steve Dowercc16be82016-09-08 10:35:16 -07002397#endif /* HAVE_LSTAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002398#ifdef HAVE_FSTATAT
2399 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks)
2400 result = fstatat(dir_fd, path->narrow, &st,
2401 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2402 else
Steve Dowercc16be82016-09-08 10:35:16 -07002403#endif /* HAVE_FSTATAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002404 result = STAT(path->narrow, &st);
Steve Dowercc16be82016-09-08 10:35:16 -07002405#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002406 Py_END_ALLOW_THREADS
2407
Victor Stinner292c8352012-10-30 02:17:38 +01002408 if (result != 0) {
2409 return path_error(path);
2410 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07002411
Victor Stinner1c2fa782020-05-10 11:05:29 +02002412 return _pystat_fromstructstat(module, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002413}
2414
Larry Hastings2f936352014-08-05 14:04:04 +10002415/*[python input]
2416
2417for s in """
2418
2419FACCESSAT
2420FCHMODAT
2421FCHOWNAT
2422FSTATAT
2423LINKAT
2424MKDIRAT
2425MKFIFOAT
2426MKNODAT
2427OPENAT
2428READLINKAT
2429SYMLINKAT
2430UNLINKAT
2431
2432""".strip().split():
2433 s = s.strip()
2434 print("""
2435#ifdef HAVE_{s}
2436 #define {s}_DIR_FD_CONVERTER dir_fd_converter
Larry Hastings31826802013-10-19 00:09:25 -07002437#else
Larry Hastings2f936352014-08-05 14:04:04 +10002438 #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings31826802013-10-19 00:09:25 -07002439#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002440""".rstrip().format(s=s))
2441
2442for s in """
2443
2444FCHDIR
2445FCHMOD
2446FCHOWN
2447FDOPENDIR
2448FEXECVE
2449FPATHCONF
2450FSTATVFS
2451FTRUNCATE
2452
2453""".strip().split():
2454 s = s.strip()
2455 print("""
2456#ifdef HAVE_{s}
2457 #define PATH_HAVE_{s} 1
2458#else
2459 #define PATH_HAVE_{s} 0
2460#endif
2461
2462""".rstrip().format(s=s))
2463[python start generated code]*/
2464
2465#ifdef HAVE_FACCESSAT
2466 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
2467#else
2468 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
2469#endif
2470
2471#ifdef HAVE_FCHMODAT
2472 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
2473#else
2474 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
2475#endif
2476
2477#ifdef HAVE_FCHOWNAT
2478 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
2479#else
2480 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
2481#endif
2482
2483#ifdef HAVE_FSTATAT
2484 #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
2485#else
2486 #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
2487#endif
2488
2489#ifdef HAVE_LINKAT
2490 #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
2491#else
2492 #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2493#endif
2494
2495#ifdef HAVE_MKDIRAT
2496 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
2497#else
2498 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
2499#endif
2500
2501#ifdef HAVE_MKFIFOAT
2502 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
2503#else
2504 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
2505#endif
2506
2507#ifdef HAVE_MKNODAT
2508 #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
2509#else
2510 #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
2511#endif
2512
2513#ifdef HAVE_OPENAT
2514 #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
2515#else
2516 #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
2517#endif
2518
2519#ifdef HAVE_READLINKAT
2520 #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
2521#else
2522 #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2523#endif
2524
2525#ifdef HAVE_SYMLINKAT
2526 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
2527#else
2528 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2529#endif
2530
2531#ifdef HAVE_UNLINKAT
2532 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
2533#else
2534 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2535#endif
2536
2537#ifdef HAVE_FCHDIR
2538 #define PATH_HAVE_FCHDIR 1
2539#else
2540 #define PATH_HAVE_FCHDIR 0
2541#endif
2542
2543#ifdef HAVE_FCHMOD
2544 #define PATH_HAVE_FCHMOD 1
2545#else
2546 #define PATH_HAVE_FCHMOD 0
2547#endif
2548
2549#ifdef HAVE_FCHOWN
2550 #define PATH_HAVE_FCHOWN 1
2551#else
2552 #define PATH_HAVE_FCHOWN 0
2553#endif
2554
2555#ifdef HAVE_FDOPENDIR
2556 #define PATH_HAVE_FDOPENDIR 1
2557#else
2558 #define PATH_HAVE_FDOPENDIR 0
2559#endif
2560
2561#ifdef HAVE_FEXECVE
2562 #define PATH_HAVE_FEXECVE 1
2563#else
2564 #define PATH_HAVE_FEXECVE 0
2565#endif
2566
2567#ifdef HAVE_FPATHCONF
2568 #define PATH_HAVE_FPATHCONF 1
2569#else
2570 #define PATH_HAVE_FPATHCONF 0
2571#endif
2572
2573#ifdef HAVE_FSTATVFS
2574 #define PATH_HAVE_FSTATVFS 1
2575#else
2576 #define PATH_HAVE_FSTATVFS 0
2577#endif
2578
2579#ifdef HAVE_FTRUNCATE
2580 #define PATH_HAVE_FTRUNCATE 1
2581#else
2582 #define PATH_HAVE_FTRUNCATE 0
2583#endif
2584/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
Larry Hastings31826802013-10-19 00:09:25 -07002585
Steve Dowerfe0a41a2015-03-20 19:50:46 -07002586#ifdef MS_WINDOWS
2587 #undef PATH_HAVE_FTRUNCATE
2588 #define PATH_HAVE_FTRUNCATE 1
2589#endif
Larry Hastings31826802013-10-19 00:09:25 -07002590
Larry Hastings61272b72014-01-07 12:41:53 -08002591/*[python input]
Larry Hastings31826802013-10-19 00:09:25 -07002592
2593class path_t_converter(CConverter):
2594
2595 type = "path_t"
2596 impl_by_reference = True
2597 parse_by_reference = True
2598
2599 converter = 'path_converter'
2600
2601 def converter_init(self, *, allow_fd=False, nullable=False):
Larry Hastings31826802013-10-19 00:09:25 -07002602 # right now path_t doesn't support default values.
2603 # to support a default value, you'll need to override initialize().
Larry Hastings2f936352014-08-05 14:04:04 +10002604 if self.default not in (unspecified, None):
Larry Hastings7726ac92014-01-31 22:03:12 -08002605 fail("Can't specify a default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002606
Larry Hastings2f936352014-08-05 14:04:04 +10002607 if self.c_default not in (None, 'Py_None'):
2608 raise RuntimeError("Can't specify a c_default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002609
2610 self.nullable = nullable
2611 self.allow_fd = allow_fd
2612
Larry Hastings7726ac92014-01-31 22:03:12 -08002613 def pre_render(self):
2614 def strify(value):
Larry Hastings2f936352014-08-05 14:04:04 +10002615 if isinstance(value, str):
2616 return value
Larry Hastings7726ac92014-01-31 22:03:12 -08002617 return str(int(bool(value)))
2618
2619 # add self.py_name here when merging with posixmodule conversion
Larry Hastings2f936352014-08-05 14:04:04 +10002620 self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
Larry Hastings31826802013-10-19 00:09:25 -07002621 self.function.name,
Larry Hastings2f936352014-08-05 14:04:04 +10002622 self.name,
Larry Hastings7726ac92014-01-31 22:03:12 -08002623 strify(self.nullable),
2624 strify(self.allow_fd),
Larry Hastings31826802013-10-19 00:09:25 -07002625 )
2626
2627 def cleanup(self):
2628 return "path_cleanup(&" + self.name + ");\n"
2629
2630
2631class dir_fd_converter(CConverter):
2632 type = 'int'
Larry Hastings31826802013-10-19 00:09:25 -07002633
Larry Hastings2f936352014-08-05 14:04:04 +10002634 def converter_init(self, requires=None):
Larry Hastings31826802013-10-19 00:09:25 -07002635 if self.default in (unspecified, None):
2636 self.c_default = 'DEFAULT_DIR_FD'
Larry Hastings2f936352014-08-05 14:04:04 +10002637 if isinstance(requires, str):
2638 self.converter = requires.upper() + '_DIR_FD_CONVERTER'
2639 else:
2640 self.converter = 'dir_fd_converter'
Larry Hastings31826802013-10-19 00:09:25 -07002641
Larry Hastings2f936352014-08-05 14:04:04 +10002642class fildes_converter(CConverter):
2643 type = 'int'
2644 converter = 'fildes_converter'
2645
2646class uid_t_converter(CConverter):
2647 type = "uid_t"
2648 converter = '_Py_Uid_Converter'
2649
2650class gid_t_converter(CConverter):
2651 type = "gid_t"
2652 converter = '_Py_Gid_Converter'
2653
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02002654class dev_t_converter(CConverter):
2655 type = 'dev_t'
2656 converter = '_Py_Dev_Converter'
2657
2658class dev_t_return_converter(unsigned_long_return_converter):
2659 type = 'dev_t'
2660 conversion_fn = '_PyLong_FromDev'
2661 unsigned_cast = '(dev_t)'
2662
Larry Hastings2f936352014-08-05 14:04:04 +10002663class FSConverter_converter(CConverter):
2664 type = 'PyObject *'
2665 converter = 'PyUnicode_FSConverter'
2666 def converter_init(self):
2667 if self.default is not unspecified:
2668 fail("FSConverter_converter does not support default values")
2669 self.c_default = 'NULL'
2670
2671 def cleanup(self):
2672 return "Py_XDECREF(" + self.name + ");\n"
2673
2674class pid_t_converter(CConverter):
2675 type = 'pid_t'
2676 format_unit = '" _Py_PARSE_PID "'
2677
2678class idtype_t_converter(int_converter):
2679 type = 'idtype_t'
2680
2681class id_t_converter(CConverter):
2682 type = 'id_t'
2683 format_unit = '" _Py_PARSE_PID "'
2684
Benjamin Petersonca470632016-09-06 13:47:26 -07002685class intptr_t_converter(CConverter):
2686 type = 'intptr_t'
Larry Hastings2f936352014-08-05 14:04:04 +10002687 format_unit = '" _Py_PARSE_INTPTR "'
2688
2689class Py_off_t_converter(CConverter):
2690 type = 'Py_off_t'
2691 converter = 'Py_off_t_converter'
2692
2693class Py_off_t_return_converter(long_return_converter):
2694 type = 'Py_off_t'
2695 conversion_fn = 'PyLong_FromPy_off_t'
2696
2697class path_confname_converter(CConverter):
2698 type="int"
2699 converter="conv_path_confname"
2700
2701class confstr_confname_converter(path_confname_converter):
2702 converter='conv_confstr_confname'
2703
2704class sysconf_confname_converter(path_confname_converter):
2705 converter="conv_sysconf_confname"
2706
Larry Hastings61272b72014-01-07 12:41:53 -08002707[python start generated code]*/
Victor Stinner1c2fa782020-05-10 11:05:29 +02002708/*[python end generated code: output=da39a3ee5e6b4b0d input=f1c8ae8d744f6c8b]*/
Larry Hastings31826802013-10-19 00:09:25 -07002709
Larry Hastings61272b72014-01-07 12:41:53 -08002710/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002711
Larry Hastings2a727912014-01-16 11:32:01 -08002712os.stat
Larry Hastings31826802013-10-19 00:09:25 -07002713
2714 path : path_t(allow_fd=True)
BNMetricsb9427072018-11-02 15:20:19 +00002715 Path to be examined; can be string, bytes, a path-like object or
Xiang Zhang4459e002017-01-22 13:04:17 +08002716 open-file-descriptor int.
Larry Hastings31826802013-10-19 00:09:25 -07002717
2718 *
2719
Larry Hastings2f936352014-08-05 14:04:04 +10002720 dir_fd : dir_fd(requires='fstatat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002721 If not None, it should be a file descriptor open to a directory,
2722 and path should be a relative string; path will then be relative to
2723 that directory.
2724
2725 follow_symlinks: bool = True
2726 If False, and the last element of the path is a symbolic link,
2727 stat will examine the symbolic link itself instead of the file
2728 the link points to.
2729
2730Perform a stat system call on the given path.
2731
2732dir_fd and follow_symlinks may not be implemented
2733 on your platform. If they are unavailable, using them will raise a
2734 NotImplementedError.
2735
2736It's an error to use dir_fd or follow_symlinks when specifying path as
2737 an open file descriptor.
2738
Larry Hastings61272b72014-01-07 12:41:53 -08002739[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002740
Larry Hastings31826802013-10-19 00:09:25 -07002741static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002742os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002743/*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
Larry Hastings31826802013-10-19 00:09:25 -07002744{
Victor Stinner1c2fa782020-05-10 11:05:29 +02002745 return posix_do_stat(module, "stat", path, dir_fd, follow_symlinks);
Larry Hastings31826802013-10-19 00:09:25 -07002746}
2747
Larry Hastings2f936352014-08-05 14:04:04 +10002748
2749/*[clinic input]
2750os.lstat
2751
2752 path : path_t
2753
2754 *
2755
2756 dir_fd : dir_fd(requires='fstatat') = None
2757
2758Perform a stat system call on the given path, without following symbolic links.
2759
2760Like stat(), but do not follow symbolic links.
2761Equivalent to stat(path, follow_symlinks=False).
2762[clinic start generated code]*/
2763
Larry Hastings2f936352014-08-05 14:04:04 +10002764static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002765os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
2766/*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002767{
2768 int follow_symlinks = 0;
Victor Stinner1c2fa782020-05-10 11:05:29 +02002769 return posix_do_stat(module, "lstat", path, dir_fd, follow_symlinks);
Larry Hastings2f936352014-08-05 14:04:04 +10002770}
Larry Hastings31826802013-10-19 00:09:25 -07002771
Larry Hastings2f936352014-08-05 14:04:04 +10002772
Larry Hastings61272b72014-01-07 12:41:53 -08002773/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10002774os.access -> bool
Larry Hastings31826802013-10-19 00:09:25 -07002775
Benjamin Peterson768f3b42016-09-05 15:29:33 -07002776 path: path_t
BNMetricsb9427072018-11-02 15:20:19 +00002777 Path to be tested; can be string, bytes, or a path-like object.
Larry Hastings31826802013-10-19 00:09:25 -07002778
2779 mode: int
2780 Operating-system mode bitfield. Can be F_OK to test existence,
2781 or the inclusive-OR of R_OK, W_OK, and X_OK.
2782
2783 *
2784
Larry Hastings2f936352014-08-05 14:04:04 +10002785 dir_fd : dir_fd(requires='faccessat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002786 If not None, it should be a file descriptor open to a directory,
2787 and path should be relative; path will then be relative to that
2788 directory.
2789
2790 effective_ids: bool = False
2791 If True, access will use the effective uid/gid instead of
2792 the real uid/gid.
2793
2794 follow_symlinks: bool = True
2795 If False, and the last element of the path is a symbolic link,
2796 access will examine the symbolic link itself instead of the file
2797 the link points to.
2798
2799Use the real uid/gid to test for access to a path.
2800
2801{parameters}
2802dir_fd, effective_ids, and follow_symlinks may not be implemented
2803 on your platform. If they are unavailable, using them will raise a
2804 NotImplementedError.
2805
2806Note that most operations will use the effective uid/gid, therefore this
2807 routine can be used in a suid/sgid environment to test if the invoking user
2808 has the specified access to the path.
2809
Larry Hastings61272b72014-01-07 12:41:53 -08002810[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002811
Larry Hastings2f936352014-08-05 14:04:04 +10002812static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002813os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002814 int effective_ids, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002815/*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
Larry Hastings31826802013-10-19 00:09:25 -07002816{
Larry Hastings2f936352014-08-05 14:04:04 +10002817 int return_value;
Victor Stinner8c62be82010-05-06 00:08:46 +00002818
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002819#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002820 DWORD attr;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002821#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07002822 int result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002823#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07002824
Larry Hastings9cf065c2012-06-22 16:30:09 -07002825#ifndef HAVE_FACCESSAT
2826 if (follow_symlinks_specified("access", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002827 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002828
2829 if (effective_ids) {
2830 argument_unavailable_error("access", "effective_ids");
Larry Hastings2f936352014-08-05 14:04:04 +10002831 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002832 }
2833#endif
2834
2835#ifdef MS_WINDOWS
2836 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002837 attr = GetFileAttributesW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002838 Py_END_ALLOW_THREADS
2839
2840 /*
Georg Brandlf7875592012-06-24 13:58:31 +02002841 * Access is possible if
Larry Hastings9cf065c2012-06-22 16:30:09 -07002842 * * we didn't get a -1, and
2843 * * write access wasn't requested,
2844 * * or the file isn't read-only,
2845 * * or it's a directory.
2846 * (Directories cannot be read-only on Windows.)
2847 */
Larry Hastings2f936352014-08-05 14:04:04 +10002848 return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
Georg Brandl5bb7aa92012-06-23 12:48:40 +02002849 (!(mode & 2) ||
Larry Hastings9cf065c2012-06-22 16:30:09 -07002850 !(attr & FILE_ATTRIBUTE_READONLY) ||
Larry Hastings2f936352014-08-05 14:04:04 +10002851 (attr & FILE_ATTRIBUTE_DIRECTORY));
Larry Hastings9cf065c2012-06-22 16:30:09 -07002852#else
2853
2854 Py_BEGIN_ALLOW_THREADS
2855#ifdef HAVE_FACCESSAT
2856 if ((dir_fd != DEFAULT_DIR_FD) ||
2857 effective_ids ||
2858 !follow_symlinks) {
2859 int flags = 0;
2860 if (!follow_symlinks)
2861 flags |= AT_SYMLINK_NOFOLLOW;
2862 if (effective_ids)
2863 flags |= AT_EACCESS;
Larry Hastings31826802013-10-19 00:09:25 -07002864 result = faccessat(dir_fd, path->narrow, mode, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002865 }
2866 else
2867#endif
Larry Hastings31826802013-10-19 00:09:25 -07002868 result = access(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002869 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10002870 return_value = !result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002871#endif
2872
Larry Hastings9cf065c2012-06-22 16:30:09 -07002873 return return_value;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002874}
2875
Guido van Rossumd371ff11999-01-25 16:12:23 +00002876#ifndef F_OK
2877#define F_OK 0
2878#endif
2879#ifndef R_OK
2880#define R_OK 4
2881#endif
2882#ifndef W_OK
2883#define W_OK 2
2884#endif
2885#ifndef X_OK
2886#define X_OK 1
2887#endif
2888
Larry Hastings31826802013-10-19 00:09:25 -07002889
Guido van Rossumd371ff11999-01-25 16:12:23 +00002890#ifdef HAVE_TTYNAME
Larry Hastings61272b72014-01-07 12:41:53 -08002891/*[clinic input]
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002892os.ttyname
Larry Hastings31826802013-10-19 00:09:25 -07002893
2894 fd: int
2895 Integer file descriptor handle.
2896
2897 /
2898
2899Return the name of the terminal device connected to 'fd'.
Larry Hastings61272b72014-01-07 12:41:53 -08002900[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002901
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002902static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002903os_ttyname_impl(PyObject *module, int fd)
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002904/*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
Larry Hastings31826802013-10-19 00:09:25 -07002905{
Guido van Rossum94f6f721999-01-06 18:42:14 +00002906
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002907 long size = sysconf(_SC_TTY_NAME_MAX);
2908 if (size == -1) {
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002909 return posix_error();
2910 }
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002911 char *buffer = (char *)PyMem_RawMalloc(size);
2912 if (buffer == NULL) {
2913 return PyErr_NoMemory();
2914 }
2915 int ret = ttyname_r(fd, buffer, size);
2916 if (ret != 0) {
2917 PyMem_RawFree(buffer);
2918 errno = ret;
2919 return posix_error();
2920 }
2921 PyObject *res = PyUnicode_DecodeFSDefault(buffer);
2922 PyMem_RawFree(buffer);
2923 return res;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002924}
Guido van Rossumd371ff11999-01-25 16:12:23 +00002925#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +00002926
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002927#ifdef HAVE_CTERMID
Larry Hastings2f936352014-08-05 14:04:04 +10002928/*[clinic input]
2929os.ctermid
2930
2931Return the name of the controlling terminal for this process.
2932[clinic start generated code]*/
2933
Larry Hastings2f936352014-08-05 14:04:04 +10002934static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002935os_ctermid_impl(PyObject *module)
2936/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002937{
Victor Stinner8c62be82010-05-06 00:08:46 +00002938 char *ret;
2939 char buffer[L_ctermid];
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002940
Greg Wardb48bc172000-03-01 21:51:56 +00002941#ifdef USE_CTERMID_R
Victor Stinner8c62be82010-05-06 00:08:46 +00002942 ret = ctermid_r(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002943#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002944 ret = ctermid(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002945#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002946 if (ret == NULL)
2947 return posix_error();
Victor Stinner5fe6de82010-08-15 09:12:51 +00002948 return PyUnicode_DecodeFSDefault(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002949}
Larry Hastings2f936352014-08-05 14:04:04 +10002950#endif /* HAVE_CTERMID */
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002951
Larry Hastings2f936352014-08-05 14:04:04 +10002952
2953/*[clinic input]
2954os.chdir
2955
2956 path: path_t(allow_fd='PATH_HAVE_FCHDIR')
2957
2958Change the current working directory to the specified path.
2959
2960path may always be specified as a string.
2961On some platforms, path may also be specified as an open file descriptor.
2962 If this functionality is unavailable, using it raises an exception.
2963[clinic start generated code]*/
2964
Larry Hastings2f936352014-08-05 14:04:04 +10002965static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002966os_chdir_impl(PyObject *module, path_t *path)
2967/*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002968{
2969 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002970
Saiyang Gou7514f4f2020-02-12 23:47:42 -08002971 if (PySys_Audit("os.chdir", "(O)", path->object) < 0) {
2972 return NULL;
2973 }
2974
Larry Hastings9cf065c2012-06-22 16:30:09 -07002975 Py_BEGIN_ALLOW_THREADS
2976#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07002977 /* on unix, success = 0, on windows, success = !0 */
2978 result = !win32_wchdir(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002979#else
2980#ifdef HAVE_FCHDIR
Larry Hastings2f936352014-08-05 14:04:04 +10002981 if (path->fd != -1)
2982 result = fchdir(path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002983 else
2984#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002985 result = chdir(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002986#endif
2987 Py_END_ALLOW_THREADS
2988
2989 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002990 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002991 }
2992
Larry Hastings2f936352014-08-05 14:04:04 +10002993 Py_RETURN_NONE;
2994}
2995
2996
2997#ifdef HAVE_FCHDIR
2998/*[clinic input]
2999os.fchdir
3000
3001 fd: fildes
3002
3003Change to the directory of the given file descriptor.
3004
3005fd must be opened on a directory, not a file.
3006Equivalent to os.chdir(fd).
3007
3008[clinic start generated code]*/
3009
Fred Drake4d1e64b2002-04-15 19:40:07 +00003010static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003011os_fchdir_impl(PyObject *module, int fd)
3012/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
Fred Drake4d1e64b2002-04-15 19:40:07 +00003013{
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003014 if (PySys_Audit("os.chdir", "(i)", fd) < 0) {
3015 return NULL;
3016 }
Larry Hastings2f936352014-08-05 14:04:04 +10003017 return posix_fildes_fd(fd, fchdir);
Fred Drake4d1e64b2002-04-15 19:40:07 +00003018}
3019#endif /* HAVE_FCHDIR */
3020
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003021
Larry Hastings2f936352014-08-05 14:04:04 +10003022/*[clinic input]
3023os.chmod
3024
3025 path: path_t(allow_fd='PATH_HAVE_FCHMOD')
BNMetricsb9427072018-11-02 15:20:19 +00003026 Path to be modified. May always be specified as a str, bytes, or a path-like object.
Larry Hastings2f936352014-08-05 14:04:04 +10003027 On some platforms, path may also be specified as an open file descriptor.
3028 If this functionality is unavailable, using it raises an exception.
3029
3030 mode: int
3031 Operating-system mode bitfield.
3032
3033 *
3034
3035 dir_fd : dir_fd(requires='fchmodat') = None
3036 If not None, it should be a file descriptor open to a directory,
3037 and path should be relative; path will then be relative to that
3038 directory.
3039
3040 follow_symlinks: bool = True
3041 If False, and the last element of the path is a symbolic link,
3042 chmod will modify the symbolic link itself instead of the file
3043 the link points to.
3044
3045Change the access permissions of a file.
3046
3047It is an error to use dir_fd or follow_symlinks when specifying path as
3048 an open file descriptor.
3049dir_fd and follow_symlinks may not be implemented on your platform.
3050 If they are unavailable, using them will raise a NotImplementedError.
3051
3052[clinic start generated code]*/
3053
Larry Hastings2f936352014-08-05 14:04:04 +10003054static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003055os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003056 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003057/*[clinic end generated code: output=5cf6a94915cc7bff input=989081551c00293b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003058{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003059 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003060
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003061#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003062 DWORD attr;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003063#endif
Hirokazu Yamamoto892a37a2009-06-28 11:07:03 +00003064
Larry Hastings9cf065c2012-06-22 16:30:09 -07003065#ifdef HAVE_FCHMODAT
3066 int fchmodat_nofollow_unsupported = 0;
3067#endif
3068
Larry Hastings9cf065c2012-06-22 16:30:09 -07003069#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
3070 if (follow_symlinks_specified("chmod", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003071 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003072#endif
3073
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003074 if (PySys_Audit("os.chmod", "Oii", path->object, mode,
3075 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
3076 return NULL;
3077 }
3078
Larry Hastings9cf065c2012-06-22 16:30:09 -07003079#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003080 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003081 attr = GetFileAttributesW(path->wide);
Tim Golden23005082013-10-25 11:22:37 +01003082 if (attr == INVALID_FILE_ATTRIBUTES)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003083 result = 0;
3084 else {
3085 if (mode & _S_IWRITE)
Victor Stinner8c62be82010-05-06 00:08:46 +00003086 attr &= ~FILE_ATTRIBUTE_READONLY;
3087 else
3088 attr |= FILE_ATTRIBUTE_READONLY;
Steve Dowercc16be82016-09-08 10:35:16 -07003089 result = SetFileAttributesW(path->wide, attr);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003090 }
3091 Py_END_ALLOW_THREADS
3092
3093 if (!result) {
Larry Hastings2f936352014-08-05 14:04:04 +10003094 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003095 }
3096#else /* MS_WINDOWS */
3097 Py_BEGIN_ALLOW_THREADS
3098#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003099 if (path->fd != -1)
3100 result = fchmod(path->fd, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003101 else
3102#endif
3103#ifdef HAVE_LCHMOD
3104 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003105 result = lchmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003106 else
3107#endif
3108#ifdef HAVE_FCHMODAT
3109 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
3110 /*
3111 * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
3112 * The documentation specifically shows how to use it,
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003113 * and then says it isn't implemented yet.
3114 * (true on linux with glibc 2.15, and openindiana 3.x)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003115 *
3116 * Once it is supported, os.chmod will automatically
3117 * support dir_fd and follow_symlinks=False. (Hopefully.)
3118 * Until then, we need to be careful what exception we raise.
3119 */
Larry Hastings2f936352014-08-05 14:04:04 +10003120 result = fchmodat(dir_fd, path->narrow, mode,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003121 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3122 /*
3123 * But wait! We can't throw the exception without allowing threads,
3124 * and we can't do that in this nested scope. (Macro trickery, sigh.)
3125 */
3126 fchmodat_nofollow_unsupported =
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003127 result &&
3128 ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
3129 !follow_symlinks;
Victor Stinner8c62be82010-05-06 00:08:46 +00003130 }
3131 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00003132#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003133 result = chmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003134 Py_END_ALLOW_THREADS
3135
3136 if (result) {
3137#ifdef HAVE_FCHMODAT
3138 if (fchmodat_nofollow_unsupported) {
3139 if (dir_fd != DEFAULT_DIR_FD)
3140 dir_fd_and_follow_symlinks_invalid("chmod",
3141 dir_fd, follow_symlinks);
3142 else
3143 follow_symlinks_specified("chmod", follow_symlinks);
Anthony Sottile233ef242017-12-14 08:57:55 -08003144 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003145 }
3146 else
3147#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003148 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003149 }
3150#endif
3151
Larry Hastings2f936352014-08-05 14:04:04 +10003152 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003153}
3154
Larry Hastings9cf065c2012-06-22 16:30:09 -07003155
Christian Heimes4e30a842007-11-30 22:12:06 +00003156#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003157/*[clinic input]
3158os.fchmod
3159
3160 fd: int
3161 mode: int
3162
3163Change the access permissions of the file given by file descriptor fd.
3164
3165Equivalent to os.chmod(fd, mode).
3166[clinic start generated code]*/
3167
Larry Hastings2f936352014-08-05 14:04:04 +10003168static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003169os_fchmod_impl(PyObject *module, int fd, int mode)
3170/*[clinic end generated code: output=afd9bc05b4e426b3 input=8ab11975ca01ee5b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003171{
3172 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003173 int async_err = 0;
3174
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003175 if (PySys_Audit("os.chmod", "iii", fd, mode, -1) < 0) {
3176 return NULL;
3177 }
3178
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003179 do {
3180 Py_BEGIN_ALLOW_THREADS
3181 res = fchmod(fd, mode);
3182 Py_END_ALLOW_THREADS
3183 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3184 if (res != 0)
3185 return (!async_err) ? posix_error() : NULL;
3186
Victor Stinner8c62be82010-05-06 00:08:46 +00003187 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003188}
3189#endif /* HAVE_FCHMOD */
3190
Larry Hastings2f936352014-08-05 14:04:04 +10003191
Christian Heimes4e30a842007-11-30 22:12:06 +00003192#ifdef HAVE_LCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003193/*[clinic input]
3194os.lchmod
3195
3196 path: path_t
3197 mode: int
3198
3199Change the access permissions of a file, without following symbolic links.
3200
3201If path is a symlink, this affects the link itself rather than the target.
3202Equivalent to chmod(path, mode, follow_symlinks=False)."
3203[clinic start generated code]*/
3204
Larry Hastings2f936352014-08-05 14:04:04 +10003205static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003206os_lchmod_impl(PyObject *module, path_t *path, int mode)
3207/*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003208{
Victor Stinner8c62be82010-05-06 00:08:46 +00003209 int res;
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003210 if (PySys_Audit("os.chmod", "Oii", path->object, mode, -1) < 0) {
3211 return NULL;
3212 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003213 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003214 res = lchmod(path->narrow, mode);
Victor Stinner8c62be82010-05-06 00:08:46 +00003215 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003216 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003217 path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003218 return NULL;
3219 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003220 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003221}
3222#endif /* HAVE_LCHMOD */
3223
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003224
Thomas Wouterscf297e42007-02-23 15:07:44 +00003225#ifdef HAVE_CHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003226/*[clinic input]
3227os.chflags
3228
3229 path: path_t
3230 flags: unsigned_long(bitwise=True)
3231 follow_symlinks: bool=True
3232
3233Set file flags.
3234
3235If follow_symlinks is False, and the last element of the path is a symbolic
3236 link, chflags will change flags on the symbolic link itself instead of the
3237 file the link points to.
3238follow_symlinks may not be implemented on your platform. If it is
3239unavailable, using it will raise a NotImplementedError.
3240
3241[clinic start generated code]*/
3242
Larry Hastings2f936352014-08-05 14:04:04 +10003243static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003244os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
Larry Hastings89964c42015-04-14 18:07:59 -04003245 int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003246/*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003247{
3248 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003249
3250#ifndef HAVE_LCHFLAGS
3251 if (follow_symlinks_specified("chflags", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003252 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003253#endif
3254
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003255 if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
3256 return NULL;
3257 }
3258
Victor Stinner8c62be82010-05-06 00:08:46 +00003259 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003260#ifdef HAVE_LCHFLAGS
3261 if (!follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +10003262 result = lchflags(path->narrow, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003263 else
3264#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003265 result = chflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003266 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003267
Larry Hastings2f936352014-08-05 14:04:04 +10003268 if (result)
3269 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003270
Larry Hastings2f936352014-08-05 14:04:04 +10003271 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003272}
3273#endif /* HAVE_CHFLAGS */
3274
Larry Hastings2f936352014-08-05 14:04:04 +10003275
Thomas Wouterscf297e42007-02-23 15:07:44 +00003276#ifdef HAVE_LCHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003277/*[clinic input]
3278os.lchflags
3279
3280 path: path_t
3281 flags: unsigned_long(bitwise=True)
3282
3283Set file flags.
3284
3285This function will not follow symbolic links.
3286Equivalent to chflags(path, flags, follow_symlinks=False).
3287[clinic start generated code]*/
3288
Larry Hastings2f936352014-08-05 14:04:04 +10003289static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003290os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
3291/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003292{
Victor Stinner8c62be82010-05-06 00:08:46 +00003293 int res;
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003294 if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
3295 return NULL;
3296 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003297 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003298 res = lchflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003299 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003300 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003301 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003302 }
Victor Stinner292c8352012-10-30 02:17:38 +01003303 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003304}
3305#endif /* HAVE_LCHFLAGS */
3306
Larry Hastings2f936352014-08-05 14:04:04 +10003307
Martin v. Löwis244edc82001-10-04 22:44:26 +00003308#ifdef HAVE_CHROOT
Larry Hastings2f936352014-08-05 14:04:04 +10003309/*[clinic input]
3310os.chroot
3311 path: path_t
3312
3313Change root directory to path.
3314
3315[clinic start generated code]*/
3316
Larry Hastings2f936352014-08-05 14:04:04 +10003317static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003318os_chroot_impl(PyObject *module, path_t *path)
3319/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003320{
3321 int res;
3322 Py_BEGIN_ALLOW_THREADS
3323 res = chroot(path->narrow);
3324 Py_END_ALLOW_THREADS
3325 if (res < 0)
3326 return path_error(path);
3327 Py_RETURN_NONE;
3328}
3329#endif /* HAVE_CHROOT */
3330
Martin v. Löwis244edc82001-10-04 22:44:26 +00003331
Guido van Rossum21142a01999-01-08 21:05:37 +00003332#ifdef HAVE_FSYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003333/*[clinic input]
3334os.fsync
3335
3336 fd: fildes
3337
3338Force write of fd to disk.
3339[clinic start generated code]*/
3340
Larry Hastings2f936352014-08-05 14:04:04 +10003341static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003342os_fsync_impl(PyObject *module, int fd)
3343/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003344{
3345 return posix_fildes_fd(fd, fsync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003346}
3347#endif /* HAVE_FSYNC */
3348
Larry Hastings2f936352014-08-05 14:04:04 +10003349
Ross Lagerwall7807c352011-03-17 20:20:30 +02003350#ifdef HAVE_SYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003351/*[clinic input]
3352os.sync
3353
3354Force write of everything to disk.
3355[clinic start generated code]*/
3356
Larry Hastings2f936352014-08-05 14:04:04 +10003357static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003358os_sync_impl(PyObject *module)
3359/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
Ross Lagerwall7807c352011-03-17 20:20:30 +02003360{
3361 Py_BEGIN_ALLOW_THREADS
3362 sync();
3363 Py_END_ALLOW_THREADS
3364 Py_RETURN_NONE;
3365}
Larry Hastings2f936352014-08-05 14:04:04 +10003366#endif /* HAVE_SYNC */
3367
Ross Lagerwall7807c352011-03-17 20:20:30 +02003368
Guido van Rossum21142a01999-01-08 21:05:37 +00003369#ifdef HAVE_FDATASYNC
Guido van Rossum7f58e2e2000-09-22 17:26:14 +00003370#ifdef __hpux
Guido van Rossumecc23b02000-09-22 16:01:05 +00003371extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
3372#endif
3373
Larry Hastings2f936352014-08-05 14:04:04 +10003374/*[clinic input]
3375os.fdatasync
3376
3377 fd: fildes
3378
3379Force write of fd to disk without forcing update of metadata.
3380[clinic start generated code]*/
3381
Larry Hastings2f936352014-08-05 14:04:04 +10003382static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003383os_fdatasync_impl(PyObject *module, int fd)
3384/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003385{
3386 return posix_fildes_fd(fd, fdatasync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003387}
3388#endif /* HAVE_FDATASYNC */
3389
3390
Fredrik Lundh10723342000-07-10 16:38:09 +00003391#ifdef HAVE_CHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003392/*[clinic input]
3393os.chown
3394
3395 path : path_t(allow_fd='PATH_HAVE_FCHOWN')
BNMetricsb9427072018-11-02 15:20:19 +00003396 Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
Larry Hastings2f936352014-08-05 14:04:04 +10003397
3398 uid: uid_t
3399
3400 gid: gid_t
3401
3402 *
3403
3404 dir_fd : dir_fd(requires='fchownat') = None
3405 If not None, it should be a file descriptor open to a directory,
3406 and path should be relative; path will then be relative to that
3407 directory.
3408
3409 follow_symlinks: bool = True
3410 If False, and the last element of the path is a symbolic link,
3411 stat will examine the symbolic link itself instead of the file
3412 the link points to.
3413
3414Change the owner and group id of path to the numeric uid and gid.\
3415
3416path may always be specified as a string.
3417On some platforms, path may also be specified as an open file descriptor.
3418 If this functionality is unavailable, using it raises an exception.
3419If dir_fd is not None, it should be a file descriptor open to a directory,
3420 and path should be relative; path will then be relative to that directory.
3421If follow_symlinks is False, and the last element of the path is a symbolic
3422 link, chown will modify the symbolic link itself instead of the file the
3423 link points to.
3424It is an error to use dir_fd or follow_symlinks when specifying path as
3425 an open file descriptor.
3426dir_fd and follow_symlinks may not be implemented on your platform.
3427 If they are unavailable, using them will raise a NotImplementedError.
3428
3429[clinic start generated code]*/
3430
Larry Hastings2f936352014-08-05 14:04:04 +10003431static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003432os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
Larry Hastings89964c42015-04-14 18:07:59 -04003433 int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003434/*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003435{
3436 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003437
3438#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
3439 if (follow_symlinks_specified("chown", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003440 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003441#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003442 if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
3443 fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
3444 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003445
3446#ifdef __APPLE__
3447 /*
3448 * This is for Mac OS X 10.3, which doesn't have lchown.
3449 * (But we still have an lchown symbol because of weak-linking.)
3450 * It doesn't have fchownat either. So there's no possibility
3451 * of a graceful failover.
Georg Brandlf7875592012-06-24 13:58:31 +02003452 */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003453 if ((!follow_symlinks) && (lchown == NULL)) {
3454 follow_symlinks_specified("chown", follow_symlinks);
Larry Hastings2f936352014-08-05 14:04:04 +10003455 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003456 }
3457#endif
3458
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003459 if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid,
3460 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
3461 return NULL;
3462 }
3463
Victor Stinner8c62be82010-05-06 00:08:46 +00003464 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003465#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003466 if (path->fd != -1)
3467 result = fchown(path->fd, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003468 else
3469#endif
3470#ifdef HAVE_LCHOWN
3471 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003472 result = lchown(path->narrow, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003473 else
3474#endif
3475#ifdef HAVE_FCHOWNAT
3476 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003477 result = fchownat(dir_fd, path->narrow, uid, gid,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003478 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3479 else
3480#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003481 result = chown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003482 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003483
Larry Hastings2f936352014-08-05 14:04:04 +10003484 if (result)
3485 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003486
Larry Hastings2f936352014-08-05 14:04:04 +10003487 Py_RETURN_NONE;
Guido van Rossumb6775db1994-08-01 11:34:53 +00003488}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003489#endif /* HAVE_CHOWN */
Guido van Rossumb6775db1994-08-01 11:34:53 +00003490
Larry Hastings2f936352014-08-05 14:04:04 +10003491
Christian Heimes4e30a842007-11-30 22:12:06 +00003492#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003493/*[clinic input]
3494os.fchown
3495
3496 fd: int
3497 uid: uid_t
3498 gid: gid_t
3499
3500Change the owner and group id of the file specified by file descriptor.
3501
3502Equivalent to os.chown(fd, uid, gid).
3503
3504[clinic start generated code]*/
3505
Larry Hastings2f936352014-08-05 14:04:04 +10003506static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003507os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
3508/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003509{
Victor Stinner8c62be82010-05-06 00:08:46 +00003510 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003511 int async_err = 0;
3512
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003513 if (PySys_Audit("os.chown", "iIIi", fd, uid, gid, -1) < 0) {
3514 return NULL;
3515 }
3516
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003517 do {
3518 Py_BEGIN_ALLOW_THREADS
3519 res = fchown(fd, uid, gid);
3520 Py_END_ALLOW_THREADS
3521 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3522 if (res != 0)
3523 return (!async_err) ? posix_error() : NULL;
3524
Victor Stinner8c62be82010-05-06 00:08:46 +00003525 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003526}
3527#endif /* HAVE_FCHOWN */
3528
Larry Hastings2f936352014-08-05 14:04:04 +10003529
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003530#ifdef HAVE_LCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003531/*[clinic input]
3532os.lchown
3533
3534 path : path_t
3535 uid: uid_t
3536 gid: gid_t
3537
3538Change the owner and group id of path to the numeric uid and gid.
3539
3540This function will not follow symbolic links.
3541Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
3542[clinic start generated code]*/
3543
Larry Hastings2f936352014-08-05 14:04:04 +10003544static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003545os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
3546/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003547{
Victor Stinner8c62be82010-05-06 00:08:46 +00003548 int res;
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003549 if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid, -1) < 0) {
3550 return NULL;
3551 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003552 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10003553 res = lchown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003554 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003555 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003556 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003557 }
Larry Hastings2f936352014-08-05 14:04:04 +10003558 Py_RETURN_NONE;
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003559}
3560#endif /* HAVE_LCHOWN */
3561
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003562
Barry Warsaw53699e91996-12-10 23:23:01 +00003563static PyObject *
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003564posix_getcwd(int use_bytes)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003565{
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003566#ifdef MS_WINDOWS
Victor Stinner689830e2019-06-26 17:31:12 +02003567 wchar_t wbuf[MAXPATHLEN];
3568 wchar_t *wbuf2 = wbuf;
3569 DWORD len;
3570
3571 Py_BEGIN_ALLOW_THREADS
3572 len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
3573 /* If the buffer is large enough, len does not include the
3574 terminating \0. If the buffer is too small, len includes
3575 the space needed for the terminator. */
3576 if (len >= Py_ARRAY_LENGTH(wbuf)) {
Victor Stinnerec3e20a2019-06-28 18:01:59 +02003577 if (len <= PY_SSIZE_T_MAX / sizeof(wchar_t)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02003578 wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00003579 }
Victor Stinner689830e2019-06-26 17:31:12 +02003580 else {
3581 wbuf2 = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003582 }
Victor Stinner689830e2019-06-26 17:31:12 +02003583 if (wbuf2) {
3584 len = GetCurrentDirectoryW(len, wbuf2);
Victor Stinner8c62be82010-05-06 00:08:46 +00003585 }
Victor Stinner689830e2019-06-26 17:31:12 +02003586 }
3587 Py_END_ALLOW_THREADS
3588
3589 if (!wbuf2) {
3590 PyErr_NoMemory();
3591 return NULL;
3592 }
3593 if (!len) {
Victor Stinnerb024e842012-10-31 22:24:06 +01003594 if (wbuf2 != wbuf)
Victor Stinnerb6404912013-07-07 16:21:41 +02003595 PyMem_RawFree(wbuf2);
Victor Stinner689830e2019-06-26 17:31:12 +02003596 return PyErr_SetFromWindowsErr(0);
Victor Stinner8c62be82010-05-06 00:08:46 +00003597 }
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01003598
Victor Stinner689830e2019-06-26 17:31:12 +02003599 PyObject *resobj = PyUnicode_FromWideChar(wbuf2, len);
3600 if (wbuf2 != wbuf) {
3601 PyMem_RawFree(wbuf2);
3602 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003603
Victor Stinner689830e2019-06-26 17:31:12 +02003604 if (use_bytes) {
3605 if (resobj == NULL) {
3606 return NULL;
3607 }
3608 Py_SETREF(resobj, PyUnicode_EncodeFSDefault(resobj));
3609 }
3610
3611 return resobj;
3612#else
3613 const size_t chunk = 1024;
3614
3615 char *buf = NULL;
3616 char *cwd = NULL;
3617 size_t buflen = 0;
3618
Victor Stinner8c62be82010-05-06 00:08:46 +00003619 Py_BEGIN_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003620 do {
Victor Stinner689830e2019-06-26 17:31:12 +02003621 char *newbuf;
3622 if (buflen <= PY_SSIZE_T_MAX - chunk) {
3623 buflen += chunk;
3624 newbuf = PyMem_RawRealloc(buf, buflen);
3625 }
3626 else {
3627 newbuf = NULL;
3628 }
3629 if (newbuf == NULL) {
3630 PyMem_RawFree(buf);
3631 buf = NULL;
Victor Stinnerc44f7072016-03-14 18:07:53 +01003632 break;
3633 }
Victor Stinner689830e2019-06-26 17:31:12 +02003634 buf = newbuf;
Victor Stinner4403d7d2015-04-25 00:16:10 +02003635
Victor Stinner4403d7d2015-04-25 00:16:10 +02003636 cwd = getcwd(buf, buflen);
3637 } while (cwd == NULL && errno == ERANGE);
Victor Stinner8c62be82010-05-06 00:08:46 +00003638 Py_END_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003639
Victor Stinner689830e2019-06-26 17:31:12 +02003640 if (buf == NULL) {
3641 return PyErr_NoMemory();
3642 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003643 if (cwd == NULL) {
3644 PyMem_RawFree(buf);
Victor Stinner8c62be82010-05-06 00:08:46 +00003645 return posix_error();
Victor Stinner4403d7d2015-04-25 00:16:10 +02003646 }
3647
Victor Stinner689830e2019-06-26 17:31:12 +02003648 PyObject *obj;
3649 if (use_bytes) {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003650 obj = PyBytes_FromStringAndSize(buf, strlen(buf));
Victor Stinner689830e2019-06-26 17:31:12 +02003651 }
3652 else {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003653 obj = PyUnicode_DecodeFSDefault(buf);
Victor Stinner689830e2019-06-26 17:31:12 +02003654 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003655 PyMem_RawFree(buf);
3656
3657 return obj;
Victor Stinner689830e2019-06-26 17:31:12 +02003658#endif /* !MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003659}
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003660
Larry Hastings2f936352014-08-05 14:04:04 +10003661
3662/*[clinic input]
3663os.getcwd
3664
3665Return a unicode string representing the current working directory.
3666[clinic start generated code]*/
3667
Larry Hastings2f936352014-08-05 14:04:04 +10003668static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003669os_getcwd_impl(PyObject *module)
3670/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003671{
3672 return posix_getcwd(0);
3673}
3674
Larry Hastings2f936352014-08-05 14:04:04 +10003675
3676/*[clinic input]
3677os.getcwdb
3678
3679Return a bytes string representing the current working directory.
3680[clinic start generated code]*/
3681
Larry Hastings2f936352014-08-05 14:04:04 +10003682static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003683os_getcwdb_impl(PyObject *module)
3684/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003685{
3686 return posix_getcwd(1);
3687}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003688
Larry Hastings2f936352014-08-05 14:04:04 +10003689
Larry Hastings9cf065c2012-06-22 16:30:09 -07003690#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
3691#define HAVE_LINK 1
3692#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003693
Guido van Rossumb6775db1994-08-01 11:34:53 +00003694#ifdef HAVE_LINK
Larry Hastings2f936352014-08-05 14:04:04 +10003695/*[clinic input]
3696
3697os.link
3698
3699 src : path_t
3700 dst : path_t
3701 *
3702 src_dir_fd : dir_fd = None
3703 dst_dir_fd : dir_fd = None
3704 follow_symlinks: bool = True
3705
3706Create a hard link to a file.
3707
3708If either src_dir_fd or dst_dir_fd is not None, it should be a file
3709 descriptor open to a directory, and the respective path string (src or dst)
3710 should be relative; the path will then be relative to that directory.
3711If follow_symlinks is False, and the last element of src is a symbolic
3712 link, link will create a link to the symbolic link itself instead of the
3713 file the link points to.
3714src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
3715 platform. If they are unavailable, using them will raise a
3716 NotImplementedError.
3717[clinic start generated code]*/
3718
Larry Hastings2f936352014-08-05 14:04:04 +10003719static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003720os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003721 int dst_dir_fd, int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003722/*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003723{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003724#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07003725 BOOL result = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003726#else
3727 int result;
3728#endif
3729
Larry Hastings9cf065c2012-06-22 16:30:09 -07003730#ifndef HAVE_LINKAT
3731 if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
3732 argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10003733 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003734 }
3735#endif
3736
Steve Dowercc16be82016-09-08 10:35:16 -07003737#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10003738 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003739 PyErr_SetString(PyExc_NotImplementedError,
3740 "link: src and dst must be the same type");
Larry Hastings2f936352014-08-05 14:04:04 +10003741 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003742 }
Steve Dowercc16be82016-09-08 10:35:16 -07003743#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003744
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003745 if (PySys_Audit("os.link", "OOii", src->object, dst->object,
3746 src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
3747 dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
3748 return NULL;
3749 }
3750
Brian Curtin1b9df392010-11-24 20:24:31 +00003751#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003752 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08003753 result = CreateHardLinkW(dst->wide, src->wide, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003754 Py_END_ALLOW_THREADS
Brian Curtin1b9df392010-11-24 20:24:31 +00003755
Larry Hastings2f936352014-08-05 14:04:04 +10003756 if (!result)
3757 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003758#else
3759 Py_BEGIN_ALLOW_THREADS
Larry Hastings67cbf7b2012-06-22 17:06:48 -07003760#ifdef HAVE_LINKAT
Larry Hastings9cf065c2012-06-22 16:30:09 -07003761 if ((src_dir_fd != DEFAULT_DIR_FD) ||
3762 (dst_dir_fd != DEFAULT_DIR_FD) ||
3763 (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003764 result = linkat(src_dir_fd, src->narrow,
3765 dst_dir_fd, dst->narrow,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003766 follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
3767 else
Steve Dowercc16be82016-09-08 10:35:16 -07003768#endif /* HAVE_LINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10003769 result = link(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003770 Py_END_ALLOW_THREADS
Brian Curtinfc889c42010-11-28 23:59:46 +00003771
Larry Hastings2f936352014-08-05 14:04:04 +10003772 if (result)
3773 return path_error2(src, dst);
Steve Dowercc16be82016-09-08 10:35:16 -07003774#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003775
Larry Hastings2f936352014-08-05 14:04:04 +10003776 Py_RETURN_NONE;
Brian Curtin1b9df392010-11-24 20:24:31 +00003777}
Larry Hastings9cf065c2012-06-22 16:30:09 -07003778#endif
3779
Brian Curtin1b9df392010-11-24 20:24:31 +00003780
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003781#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
Barry Warsaw53699e91996-12-10 23:23:01 +00003782static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003783_listdir_windows_no_opendir(path_t *path, PyObject *list)
Guido van Rossumb6775db1994-08-01 11:34:53 +00003784{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003785 PyObject *v;
3786 HANDLE hFindFile = INVALID_HANDLE_VALUE;
3787 BOOL result;
Steve Dowercc16be82016-09-08 10:35:16 -07003788 wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003789 /* only claim to have space for MAX_PATH */
Victor Stinner75875072013-11-24 19:23:25 +01003790 Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003791 wchar_t *wnamebuf = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003792
Steve Dowercc16be82016-09-08 10:35:16 -07003793 WIN32_FIND_DATAW wFileData;
3794 const wchar_t *po_wchars;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003795
Steve Dowercc16be82016-09-08 10:35:16 -07003796 if (!path->wide) { /* Default arg: "." */
3797 po_wchars = L".";
3798 len = 1;
3799 } else {
3800 po_wchars = path->wide;
3801 len = wcslen(path->wide);
3802 }
3803 /* The +5 is so we can append "\\*.*\0" */
3804 wnamebuf = PyMem_New(wchar_t, len + 5);
3805 if (!wnamebuf) {
3806 PyErr_NoMemory();
Larry Hastings9cf065c2012-06-22 16:30:09 -07003807 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003808 }
Steve Dowercc16be82016-09-08 10:35:16 -07003809 wcscpy(wnamebuf, po_wchars);
Victor Stinner8c62be82010-05-06 00:08:46 +00003810 if (len > 0) {
Steve Dowercc16be82016-09-08 10:35:16 -07003811 wchar_t wch = wnamebuf[len-1];
3812 if (wch != SEP && wch != ALTSEP && wch != L':')
3813 wnamebuf[len++] = SEP;
3814 wcscpy(wnamebuf + len, L"*.*");
Victor Stinner8c62be82010-05-06 00:08:46 +00003815 }
Steve Dowercc16be82016-09-08 10:35:16 -07003816 if ((list = PyList_New(0)) == NULL) {
3817 goto exit;
3818 }
Antoine Pitroub73caab2010-08-09 23:39:31 +00003819 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003820 hFindFile = FindFirstFileW(wnamebuf, &wFileData);
Antoine Pitroub73caab2010-08-09 23:39:31 +00003821 Py_END_ALLOW_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +00003822 if (hFindFile == INVALID_HANDLE_VALUE) {
3823 int error = GetLastError();
3824 if (error == ERROR_FILE_NOT_FOUND)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003825 goto exit;
3826 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003827 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003828 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003829 }
3830 do {
3831 /* Skip over . and .. */
Steve Dowercc16be82016-09-08 10:35:16 -07003832 if (wcscmp(wFileData.cFileName, L".") != 0 &&
3833 wcscmp(wFileData.cFileName, L"..") != 0) {
3834 v = PyUnicode_FromWideChar(wFileData.cFileName,
3835 wcslen(wFileData.cFileName));
3836 if (path->narrow && v) {
3837 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3838 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003839 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003840 Py_DECREF(list);
3841 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003842 break;
3843 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003844 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003845 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003846 Py_DECREF(list);
3847 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003848 break;
3849 }
3850 Py_DECREF(v);
3851 }
3852 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003853 result = FindNextFileW(hFindFile, &wFileData);
Victor Stinner8c62be82010-05-06 00:08:46 +00003854 Py_END_ALLOW_THREADS
3855 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
3856 it got to the end of the directory. */
3857 if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003858 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003859 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003860 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003861 }
3862 } while (result == TRUE);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003863
Larry Hastings9cf065c2012-06-22 16:30:09 -07003864exit:
3865 if (hFindFile != INVALID_HANDLE_VALUE) {
3866 if (FindClose(hFindFile) == FALSE) {
3867 if (list != NULL) {
3868 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003869 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003870 }
3871 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003872 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003873 PyMem_Free(wnamebuf);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003874
Larry Hastings9cf065c2012-06-22 16:30:09 -07003875 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003876} /* end of _listdir_windows_no_opendir */
3877
3878#else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
3879
3880static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003881_posix_listdir(path_t *path, PyObject *list)
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003882{
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003883 PyObject *v;
3884 DIR *dirp = NULL;
3885 struct dirent *ep;
3886 int return_str; /* if false, return bytes */
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003887#ifdef HAVE_FDOPENDIR
3888 int fd = -1;
3889#endif
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003890
Victor Stinner8c62be82010-05-06 00:08:46 +00003891 errno = 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003892#ifdef HAVE_FDOPENDIR
Gregory P. Smith40a21602013-03-20 20:52:50 -07003893 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003894 /* closedir() closes the FD, so we duplicate it */
Victor Stinnerdaf45552013-08-28 00:53:59 +02003895 fd = _Py_dup(path->fd);
Victor Stinnerf3266652013-12-19 13:24:49 +01003896 if (fd == -1)
3897 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003898
Larry Hastingsfdaea062012-06-25 04:42:23 -07003899 return_str = 1;
3900
Larry Hastings9cf065c2012-06-22 16:30:09 -07003901 Py_BEGIN_ALLOW_THREADS
3902 dirp = fdopendir(fd);
3903 Py_END_ALLOW_THREADS
3904 }
3905 else
3906#endif
3907 {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003908 const char *name;
Gregory P. Smith40a21602013-03-20 20:52:50 -07003909 if (path->narrow) {
3910 name = path->narrow;
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03003911 /* only return bytes if they specified a bytes-like object */
3912 return_str = !PyObject_CheckBuffer(path->object);
Larry Hastingsfdaea062012-06-25 04:42:23 -07003913 }
3914 else {
3915 name = ".";
3916 return_str = 1;
3917 }
3918
Larry Hastings9cf065c2012-06-22 16:30:09 -07003919 Py_BEGIN_ALLOW_THREADS
3920 dirp = opendir(name);
3921 Py_END_ALLOW_THREADS
3922 }
3923
3924 if (dirp == NULL) {
Gregory P. Smith40a21602013-03-20 20:52:50 -07003925 list = path_error(path);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003926#ifdef HAVE_FDOPENDIR
3927 if (fd != -1) {
3928 Py_BEGIN_ALLOW_THREADS
3929 close(fd);
3930 Py_END_ALLOW_THREADS
3931 }
3932#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003933 goto exit;
3934 }
3935 if ((list = PyList_New(0)) == NULL) {
3936 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003937 }
3938 for (;;) {
3939 errno = 0;
3940 Py_BEGIN_ALLOW_THREADS
3941 ep = readdir(dirp);
3942 Py_END_ALLOW_THREADS
3943 if (ep == NULL) {
3944 if (errno == 0) {
3945 break;
3946 } else {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003947 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003948 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003949 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003950 }
3951 }
3952 if (ep->d_name[0] == '.' &&
3953 (NAMLEN(ep) == 1 ||
3954 (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
3955 continue;
Larry Hastingsfdaea062012-06-25 04:42:23 -07003956 if (return_str)
Victor Stinnera45598a2010-05-14 16:35:39 +00003957 v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
3958 else
3959 v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
Victor Stinner8c62be82010-05-06 00:08:46 +00003960 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003961 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003962 break;
3963 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003964 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003965 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003966 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003967 break;
3968 }
3969 Py_DECREF(v);
3970 }
Guido van Rossum0ee42cd1991-04-08 21:01:03 +00003971
Larry Hastings9cf065c2012-06-22 16:30:09 -07003972exit:
3973 if (dirp != NULL) {
3974 Py_BEGIN_ALLOW_THREADS
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003975#ifdef HAVE_FDOPENDIR
Larry Hastings9cf065c2012-06-22 16:30:09 -07003976 if (fd > -1)
3977 rewinddir(dirp);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003978#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003979 closedir(dirp);
3980 Py_END_ALLOW_THREADS
3981 }
3982
Larry Hastings9cf065c2012-06-22 16:30:09 -07003983 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003984} /* end of _posix_listdir */
3985#endif /* which OS */
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003986
Larry Hastings2f936352014-08-05 14:04:04 +10003987
3988/*[clinic input]
3989os.listdir
3990
3991 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
3992
3993Return a list containing the names of the files in the directory.
3994
BNMetricsb9427072018-11-02 15:20:19 +00003995path can be specified as either str, bytes, or a path-like object. If path is bytes,
Larry Hastings2f936352014-08-05 14:04:04 +10003996 the filenames returned will also be bytes; in all other circumstances
3997 the filenames returned will be str.
3998If path is None, uses the path='.'.
3999On some platforms, path may also be specified as an open file descriptor;\
4000 the file descriptor must refer to a directory.
4001 If this functionality is unavailable, using it raises NotImplementedError.
4002
4003The list is in arbitrary order. It does not include the special
4004entries '.' and '..' even if they are present in the directory.
4005
4006
4007[clinic start generated code]*/
4008
Larry Hastings2f936352014-08-05 14:04:04 +10004009static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004010os_listdir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +00004011/*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004012{
Steve Dower60419a72019-06-24 08:42:54 -07004013 if (PySys_Audit("os.listdir", "O",
4014 path->object ? path->object : Py_None) < 0) {
4015 return NULL;
4016 }
Larry Hastings2f936352014-08-05 14:04:04 +10004017#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
4018 return _listdir_windows_no_opendir(path, NULL);
4019#else
4020 return _posix_listdir(path, NULL);
4021#endif
4022}
4023
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004024#ifdef MS_WINDOWS
Mark Hammondef8b6542001-05-13 08:04:26 +00004025/* A helper function for abspath on win32 */
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03004026/*[clinic input]
4027os._getfullpathname
Victor Stinnereb5657a2011-09-30 01:44:27 +02004028
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03004029 path: path_t
4030 /
4031
4032[clinic start generated code]*/
4033
4034static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004035os__getfullpathname_impl(PyObject *module, path_t *path)
4036/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03004037{
Victor Stinner3939c322019-06-25 15:02:43 +02004038 wchar_t *abspath;
Victor Stinnereb5657a2011-09-30 01:44:27 +02004039
Victor Stinner3939c322019-06-25 15:02:43 +02004040 /* _Py_abspath() is implemented with GetFullPathNameW() on Windows */
4041 if (_Py_abspath(path->wide, &abspath) < 0) {
4042 return win32_error_object("GetFullPathNameW", path->object);
Victor Stinner8c62be82010-05-06 00:08:46 +00004043 }
Victor Stinner3939c322019-06-25 15:02:43 +02004044 if (abspath == NULL) {
4045 return PyErr_NoMemory();
4046 }
4047
4048 PyObject *str = PyUnicode_FromWideChar(abspath, wcslen(abspath));
4049 PyMem_RawFree(abspath);
4050 if (str == NULL) {
4051 return NULL;
4052 }
4053 if (path->narrow) {
4054 Py_SETREF(str, PyUnicode_EncodeFSDefault(str));
4055 }
4056 return str;
Larry Hastings2f936352014-08-05 14:04:04 +10004057}
Brian Curtind40e6f72010-07-08 21:39:08 +00004058
Brian Curtind25aef52011-06-13 15:16:04 -05004059
Larry Hastings2f936352014-08-05 14:04:04 +10004060/*[clinic input]
4061os._getfinalpathname
Brian Curtinf5e76d02010-11-24 13:14:05 +00004062
Steve Dower23ad6d02018-02-22 10:39:10 -08004063 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10004064 /
4065
4066A helper function for samepath on windows.
4067[clinic start generated code]*/
4068
Larry Hastings2f936352014-08-05 14:04:04 +10004069static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08004070os__getfinalpathname_impl(PyObject *module, path_t *path)
4071/*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
Brian Curtind40e6f72010-07-08 21:39:08 +00004072{
4073 HANDLE hFile;
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004074 wchar_t buf[MAXPATHLEN], *target_path = buf;
4075 int buf_size = Py_ARRAY_LENGTH(buf);
Brian Curtind40e6f72010-07-08 21:39:08 +00004076 int result_length;
Larry Hastings2f936352014-08-05 14:04:04 +10004077 PyObject *result;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004078
Steve Dower23ad6d02018-02-22 10:39:10 -08004079 Py_BEGIN_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00004080 hFile = CreateFileW(
Steve Dower23ad6d02018-02-22 10:39:10 -08004081 path->wide,
Brian Curtind40e6f72010-07-08 21:39:08 +00004082 0, /* desired access */
4083 0, /* share mode */
4084 NULL, /* security attributes */
4085 OPEN_EXISTING,
4086 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
4087 FILE_FLAG_BACKUP_SEMANTICS,
4088 NULL);
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004089 Py_END_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004090
Steve Dower23ad6d02018-02-22 10:39:10 -08004091 if (hFile == INVALID_HANDLE_VALUE) {
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004092 return win32_error_object("CreateFileW", path->object);
Steve Dower23ad6d02018-02-22 10:39:10 -08004093 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004094
4095 /* We have a good handle to the target, use it to determine the
4096 target path name. */
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004097 while (1) {
4098 Py_BEGIN_ALLOW_THREADS
4099 result_length = GetFinalPathNameByHandleW(hFile, target_path,
4100 buf_size, VOLUME_NAME_DOS);
4101 Py_END_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00004102
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004103 if (!result_length) {
4104 result = win32_error_object("GetFinalPathNameByHandleW",
4105 path->object);
4106 goto cleanup;
4107 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004108
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004109 if (result_length < buf_size) {
4110 break;
4111 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004112
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004113 wchar_t *tmp;
4114 tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
4115 result_length * sizeof(*tmp));
4116 if (!tmp) {
4117 result = PyErr_NoMemory();
4118 goto cleanup;
4119 }
4120
4121 buf_size = result_length;
4122 target_path = tmp;
Steve Dower23ad6d02018-02-22 10:39:10 -08004123 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004124
Victor Stinner9d3b93b2011-11-22 02:27:30 +01004125 result = PyUnicode_FromWideChar(target_path, result_length);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004126 if (result && path->narrow) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004127 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004128 }
Steve Dower23ad6d02018-02-22 10:39:10 -08004129
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004130cleanup:
4131 if (target_path != buf) {
4132 PyMem_Free(target_path);
4133 }
4134 CloseHandle(hFile);
4135 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10004136}
Brian Curtin62857742010-09-06 17:07:27 +00004137
Tim Golden6b528062013-08-01 12:44:00 +01004138
Larry Hastings2f936352014-08-05 14:04:04 +10004139/*[clinic input]
4140os._getvolumepathname
4141
Steve Dower23ad6d02018-02-22 10:39:10 -08004142 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10004143
4144A helper function for ismount on Win32.
4145[clinic start generated code]*/
4146
Larry Hastings2f936352014-08-05 14:04:04 +10004147static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08004148os__getvolumepathname_impl(PyObject *module, path_t *path)
4149/*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004150{
4151 PyObject *result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004152 wchar_t *mountpath=NULL;
Victor Stinner6edddfa2013-11-24 19:22:57 +01004153 size_t buflen;
Tim Golden6b528062013-08-01 12:44:00 +01004154 BOOL ret;
4155
Tim Golden6b528062013-08-01 12:44:00 +01004156 /* Volume path should be shorter than entire path */
Steve Dower23ad6d02018-02-22 10:39:10 -08004157 buflen = Py_MAX(path->length, MAX_PATH);
Victor Stinner6edddfa2013-11-24 19:22:57 +01004158
Victor Stinner850a18e2017-10-24 16:53:32 -07004159 if (buflen > PY_DWORD_MAX) {
Victor Stinner6edddfa2013-11-24 19:22:57 +01004160 PyErr_SetString(PyExc_OverflowError, "path too long");
4161 return NULL;
4162 }
4163
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004164 mountpath = PyMem_New(wchar_t, buflen);
Tim Golden6b528062013-08-01 12:44:00 +01004165 if (mountpath == NULL)
4166 return PyErr_NoMemory();
4167
4168 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -08004169 ret = GetVolumePathNameW(path->wide, mountpath,
Victor Stinner6edddfa2013-11-24 19:22:57 +01004170 Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
Tim Golden6b528062013-08-01 12:44:00 +01004171 Py_END_ALLOW_THREADS
4172
4173 if (!ret) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004174 result = win32_error_object("_getvolumepathname", path->object);
Tim Golden6b528062013-08-01 12:44:00 +01004175 goto exit;
4176 }
4177 result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
Steve Dower23ad6d02018-02-22 10:39:10 -08004178 if (path->narrow)
4179 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Tim Golden6b528062013-08-01 12:44:00 +01004180
4181exit:
4182 PyMem_Free(mountpath);
4183 return result;
4184}
Tim Golden6b528062013-08-01 12:44:00 +01004185
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004186#endif /* MS_WINDOWS */
Mark Hammondef8b6542001-05-13 08:04:26 +00004187
Larry Hastings2f936352014-08-05 14:04:04 +10004188
4189/*[clinic input]
4190os.mkdir
4191
4192 path : path_t
4193
4194 mode: int = 0o777
4195
4196 *
4197
4198 dir_fd : dir_fd(requires='mkdirat') = None
4199
4200# "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
4201
4202Create a directory.
4203
4204If dir_fd is not None, it should be a file descriptor open to a directory,
4205 and path should be relative; path will then be relative to that directory.
4206dir_fd may not be implemented on your platform.
4207 If it is unavailable, using it will raise a NotImplementedError.
4208
4209The mode argument is ignored on Windows.
4210[clinic start generated code]*/
4211
Larry Hastings2f936352014-08-05 14:04:04 +10004212static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004213os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
4214/*[clinic end generated code: output=a70446903abe821f input=e965f68377e9b1ce]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004215{
4216 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004217
Saiyang Gou7514f4f2020-02-12 23:47:42 -08004218 if (PySys_Audit("os.mkdir", "Oii", path->object, mode,
4219 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4220 return NULL;
4221 }
4222
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004223#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004224 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004225 result = CreateDirectoryW(path->wide, NULL);
Victor Stinner8c62be82010-05-06 00:08:46 +00004226 Py_END_ALLOW_THREADS
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004227
Larry Hastings2f936352014-08-05 14:04:04 +10004228 if (!result)
4229 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004230#else
Victor Stinner8c62be82010-05-06 00:08:46 +00004231 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004232#if HAVE_MKDIRAT
4233 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004234 result = mkdirat(dir_fd, path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004235 else
4236#endif
Erik Bray03eb11f2017-10-27 14:27:06 +02004237#if defined(__WATCOMC__) && !defined(__QNX__)
Larry Hastings2f936352014-08-05 14:04:04 +10004238 result = mkdir(path->narrow);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004239#else
Larry Hastings2f936352014-08-05 14:04:04 +10004240 result = mkdir(path->narrow, mode);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004241#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004242 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004243 if (result < 0)
4244 return path_error(path);
Steve Dowercc16be82016-09-08 10:35:16 -07004245#endif /* MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10004246 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004247}
4248
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004249
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004250/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
4251#if defined(HAVE_SYS_RESOURCE_H)
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004252#include <sys/resource.h>
4253#endif
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004254
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004255
4256#ifdef HAVE_NICE
Larry Hastings2f936352014-08-05 14:04:04 +10004257/*[clinic input]
4258os.nice
4259
4260 increment: int
4261 /
4262
4263Add increment to the priority of process and return the new priority.
4264[clinic start generated code]*/
4265
Larry Hastings2f936352014-08-05 14:04:04 +10004266static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004267os_nice_impl(PyObject *module, int increment)
4268/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004269{
4270 int value;
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004271
Victor Stinner8c62be82010-05-06 00:08:46 +00004272 /* There are two flavours of 'nice': one that returns the new
4273 priority (as required by almost all standards out there) and the
Benjamin Peterson288d1da2017-09-28 22:44:27 -07004274 Linux/FreeBSD one, which returns '0' on success and advices
Victor Stinner8c62be82010-05-06 00:08:46 +00004275 the use of getpriority() to get the new priority.
Tim Peters5aa91602002-01-30 05:46:57 +00004276
Victor Stinner8c62be82010-05-06 00:08:46 +00004277 If we are of the nice family that returns the new priority, we
4278 need to clear errno before the call, and check if errno is filled
4279 before calling posix_error() on a returnvalue of -1, because the
4280 -1 may be the actual new priority! */
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004281
Victor Stinner8c62be82010-05-06 00:08:46 +00004282 errno = 0;
4283 value = nice(increment);
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004284#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
Victor Stinner8c62be82010-05-06 00:08:46 +00004285 if (value == 0)
4286 value = getpriority(PRIO_PROCESS, 0);
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004287#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004288 if (value == -1 && errno != 0)
4289 /* either nice() or getpriority() returned an error */
4290 return posix_error();
4291 return PyLong_FromLong((long) value);
Guido van Rossum775f4da1993-01-09 17:18:52 +00004292}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004293#endif /* HAVE_NICE */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004294
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004295
4296#ifdef HAVE_GETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004297/*[clinic input]
4298os.getpriority
4299
4300 which: int
4301 who: int
4302
4303Return program scheduling priority.
4304[clinic start generated code]*/
4305
Larry Hastings2f936352014-08-05 14:04:04 +10004306static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004307os_getpriority_impl(PyObject *module, int which, int who)
4308/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004309{
4310 int retval;
4311
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004312 errno = 0;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004313 retval = getpriority(which, who);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004314 if (errno != 0)
4315 return posix_error();
4316 return PyLong_FromLong((long)retval);
4317}
4318#endif /* HAVE_GETPRIORITY */
4319
4320
4321#ifdef HAVE_SETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004322/*[clinic input]
4323os.setpriority
4324
4325 which: int
4326 who: int
4327 priority: int
4328
4329Set program scheduling priority.
4330[clinic start generated code]*/
4331
Larry Hastings2f936352014-08-05 14:04:04 +10004332static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004333os_setpriority_impl(PyObject *module, int which, int who, int priority)
4334/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004335{
4336 int retval;
4337
4338 retval = setpriority(which, who, priority);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004339 if (retval == -1)
4340 return posix_error();
4341 Py_RETURN_NONE;
4342}
4343#endif /* HAVE_SETPRIORITY */
4344
4345
Barry Warsaw53699e91996-12-10 23:23:01 +00004346static PyObject *
Larry Hastings2f936352014-08-05 14:04:04 +10004347internal_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 +00004348{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004349 const char *function_name = is_replace ? "replace" : "rename";
Larry Hastings9cf065c2012-06-22 16:30:09 -07004350 int dir_fd_specified;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004351
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004352#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004353 BOOL result;
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004354 int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004355#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004356 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004357#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004358
Larry Hastings9cf065c2012-06-22 16:30:09 -07004359 dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
4360 (dst_dir_fd != DEFAULT_DIR_FD);
4361#ifndef HAVE_RENAMEAT
4362 if (dir_fd_specified) {
4363 argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10004364 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004365 }
4366#endif
4367
Saiyang Gou7514f4f2020-02-12 23:47:42 -08004368 if (PySys_Audit("os.rename", "OOii", src->object, dst->object,
4369 src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
4370 dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
4371 return NULL;
4372 }
4373
Larry Hastings9cf065c2012-06-22 16:30:09 -07004374#ifdef MS_WINDOWS
4375 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004376 result = MoveFileExW(src->wide, dst->wide, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004377 Py_END_ALLOW_THREADS
4378
Larry Hastings2f936352014-08-05 14:04:04 +10004379 if (!result)
4380 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004381
4382#else
Steve Dowercc16be82016-09-08 10:35:16 -07004383 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
4384 PyErr_Format(PyExc_ValueError,
4385 "%s: src and dst must be the same type", function_name);
4386 return NULL;
4387 }
4388
Larry Hastings9cf065c2012-06-22 16:30:09 -07004389 Py_BEGIN_ALLOW_THREADS
4390#ifdef HAVE_RENAMEAT
4391 if (dir_fd_specified)
Larry Hastings2f936352014-08-05 14:04:04 +10004392 result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004393 else
4394#endif
Steve Dowercc16be82016-09-08 10:35:16 -07004395 result = rename(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004396 Py_END_ALLOW_THREADS
4397
Larry Hastings2f936352014-08-05 14:04:04 +10004398 if (result)
4399 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004400#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004401 Py_RETURN_NONE;
4402}
Larry Hastings9cf065c2012-06-22 16:30:09 -07004403
Larry Hastings2f936352014-08-05 14:04:04 +10004404
4405/*[clinic input]
4406os.rename
4407
4408 src : path_t
4409 dst : path_t
4410 *
4411 src_dir_fd : dir_fd = None
4412 dst_dir_fd : dir_fd = None
4413
4414Rename a file or directory.
4415
4416If either src_dir_fd or dst_dir_fd is not None, it should be a file
4417 descriptor open to a directory, and the respective path string (src or dst)
4418 should be relative; the path will then be relative to that directory.
4419src_dir_fd and dst_dir_fd, may not be implemented on your platform.
4420 If they are unavailable, using them will raise a NotImplementedError.
4421[clinic start generated code]*/
4422
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004423static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004424os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04004425 int dst_dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004426/*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004427{
Larry Hastings2f936352014-08-05 14:04:04 +10004428 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004429}
4430
Larry Hastings2f936352014-08-05 14:04:04 +10004431
4432/*[clinic input]
4433os.replace = os.rename
4434
4435Rename a file or directory, overwriting the destination.
4436
4437If either src_dir_fd or dst_dir_fd is not None, it should be a file
4438 descriptor open to a directory, and the respective path string (src or dst)
4439 should be relative; the path will then be relative to that directory.
4440src_dir_fd and dst_dir_fd, may not be implemented on your platform.
Anthony Sottile73d60022019-02-12 23:15:54 -05004441 If they are unavailable, using them will raise a NotImplementedError.
Larry Hastings2f936352014-08-05 14:04:04 +10004442[clinic start generated code]*/
4443
Larry Hastings2f936352014-08-05 14:04:04 +10004444static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004445os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
4446 int dst_dir_fd)
Anthony Sottile73d60022019-02-12 23:15:54 -05004447/*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004448{
4449 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
4450}
4451
4452
4453/*[clinic input]
4454os.rmdir
4455
4456 path: path_t
4457 *
4458 dir_fd: dir_fd(requires='unlinkat') = None
4459
4460Remove a directory.
4461
4462If dir_fd is not None, it should be a file descriptor open to a directory,
4463 and path should be relative; path will then be relative to that directory.
4464dir_fd may not be implemented on your platform.
4465 If it is unavailable, using it will raise a NotImplementedError.
4466[clinic start generated code]*/
4467
Larry Hastings2f936352014-08-05 14:04:04 +10004468static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004469os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
4470/*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004471{
4472 int result;
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004473
Saiyang Gou7514f4f2020-02-12 23:47:42 -08004474 if (PySys_Audit("os.rmdir", "Oi", path->object,
4475 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4476 return NULL;
4477 }
4478
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004479 Py_BEGIN_ALLOW_THREADS
4480#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004481 /* Windows, success=1, UNIX, success=0 */
4482 result = !RemoveDirectoryW(path->wide);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004483#else
4484#ifdef HAVE_UNLINKAT
4485 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004486 result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004487 else
4488#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004489 result = rmdir(path->narrow);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004490#endif
4491 Py_END_ALLOW_THREADS
4492
Larry Hastings2f936352014-08-05 14:04:04 +10004493 if (result)
4494 return path_error(path);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004495
Larry Hastings2f936352014-08-05 14:04:04 +10004496 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004497}
4498
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004499
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004500#ifdef HAVE_SYSTEM
Larry Hastings2f936352014-08-05 14:04:04 +10004501#ifdef MS_WINDOWS
4502/*[clinic input]
4503os.system -> long
4504
4505 command: Py_UNICODE
4506
4507Execute the command in a subshell.
4508[clinic start generated code]*/
4509
Larry Hastings2f936352014-08-05 14:04:04 +10004510static long
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02004511os_system_impl(PyObject *module, const Py_UNICODE *command)
4512/*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004513{
4514 long result;
Steve Dowerb82e17e2019-05-23 08:45:22 -07004515
Steve Dowerfbe3c762019-10-18 00:52:15 -07004516 if (PySys_Audit("os.system", "(u)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004517 return -1;
4518 }
4519
Victor Stinner8c62be82010-05-06 00:08:46 +00004520 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08004521 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10004522 result = _wsystem(command);
Steve Dowerc3630612016-11-19 18:41:16 -08004523 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00004524 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004525 return result;
4526}
4527#else /* MS_WINDOWS */
4528/*[clinic input]
4529os.system -> long
4530
4531 command: FSConverter
4532
4533Execute the command in a subshell.
4534[clinic start generated code]*/
4535
Larry Hastings2f936352014-08-05 14:04:04 +10004536static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004537os_system_impl(PyObject *module, PyObject *command)
4538/*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004539{
4540 long result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004541 const char *bytes = PyBytes_AsString(command);
Steve Dowerb82e17e2019-05-23 08:45:22 -07004542
Steve Dowerfbe3c762019-10-18 00:52:15 -07004543 if (PySys_Audit("os.system", "(O)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004544 return -1;
4545 }
4546
Larry Hastings2f936352014-08-05 14:04:04 +10004547 Py_BEGIN_ALLOW_THREADS
4548 result = system(bytes);
4549 Py_END_ALLOW_THREADS
4550 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004551}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004552#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004553#endif /* HAVE_SYSTEM */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004554
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004555
Larry Hastings2f936352014-08-05 14:04:04 +10004556/*[clinic input]
4557os.umask
4558
4559 mask: int
4560 /
4561
4562Set the current numeric umask and return the previous umask.
4563[clinic start generated code]*/
4564
Larry Hastings2f936352014-08-05 14:04:04 +10004565static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004566os_umask_impl(PyObject *module, int mask)
4567/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004568{
4569 int i = (int)umask(mask);
Victor Stinner8c62be82010-05-06 00:08:46 +00004570 if (i < 0)
4571 return posix_error();
4572 return PyLong_FromLong((long)i);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004573}
4574
Brian Curtind40e6f72010-07-08 21:39:08 +00004575#ifdef MS_WINDOWS
4576
4577/* override the default DeleteFileW behavior so that directory
4578symlinks can be removed with this function, the same as with
4579Unix symlinks */
4580BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
4581{
4582 WIN32_FILE_ATTRIBUTE_DATA info;
4583 WIN32_FIND_DATAW find_data;
4584 HANDLE find_data_handle;
4585 int is_directory = 0;
4586 int is_link = 0;
4587
4588 if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
4589 is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004590
Brian Curtind40e6f72010-07-08 21:39:08 +00004591 /* Get WIN32_FIND_DATA structure for the path to determine if
4592 it is a symlink */
4593 if(is_directory &&
4594 info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
4595 find_data_handle = FindFirstFileW(lpFileName, &find_data);
4596
4597 if(find_data_handle != INVALID_HANDLE_VALUE) {
Tim Golden0321cf22014-05-05 19:46:17 +01004598 /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
4599 IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
4600 is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
4601 find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
Brian Curtind40e6f72010-07-08 21:39:08 +00004602 FindClose(find_data_handle);
4603 }
4604 }
4605 }
4606
4607 if (is_directory && is_link)
4608 return RemoveDirectoryW(lpFileName);
4609
4610 return DeleteFileW(lpFileName);
4611}
4612#endif /* MS_WINDOWS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004613
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004614
Larry Hastings2f936352014-08-05 14:04:04 +10004615/*[clinic input]
4616os.unlink
4617
4618 path: path_t
4619 *
4620 dir_fd: dir_fd(requires='unlinkat')=None
4621
4622Remove a file (same as remove()).
4623
4624If dir_fd is not None, it should be a file descriptor open to a directory,
4625 and path should be relative; path will then be relative to that directory.
4626dir_fd may not be implemented on your platform.
4627 If it is unavailable, using it will raise a NotImplementedError.
4628
4629[clinic start generated code]*/
4630
Larry Hastings2f936352014-08-05 14:04:04 +10004631static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004632os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
4633/*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004634{
4635 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004636
Saiyang Gou7514f4f2020-02-12 23:47:42 -08004637 if (PySys_Audit("os.remove", "Oi", path->object,
4638 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4639 return NULL;
4640 }
4641
Larry Hastings9cf065c2012-06-22 16:30:09 -07004642 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04004643 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004644#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004645 /* Windows, success=1, UNIX, success=0 */
4646 result = !Py_DeleteFileW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004647#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004648#ifdef HAVE_UNLINKAT
4649 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004650 result = unlinkat(dir_fd, path->narrow, 0);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004651 else
4652#endif /* HAVE_UNLINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10004653 result = unlink(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004654#endif
Steve Dower8fc89802015-04-12 00:26:27 -04004655 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004656 Py_END_ALLOW_THREADS
4657
Larry Hastings2f936352014-08-05 14:04:04 +10004658 if (result)
4659 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004660
Larry Hastings2f936352014-08-05 14:04:04 +10004661 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004662}
4663
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004664
Larry Hastings2f936352014-08-05 14:04:04 +10004665/*[clinic input]
4666os.remove = os.unlink
4667
4668Remove a file (same as unlink()).
4669
4670If dir_fd is not None, it should be a file descriptor open to a directory,
4671 and path should be relative; path will then be relative to that directory.
4672dir_fd may not be implemented on your platform.
4673 If it is unavailable, using it will raise a NotImplementedError.
4674[clinic start generated code]*/
4675
Larry Hastings2f936352014-08-05 14:04:04 +10004676static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004677os_remove_impl(PyObject *module, path_t *path, int dir_fd)
4678/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004679{
4680 return os_unlink_impl(module, path, dir_fd);
4681}
4682
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004683
Larry Hastings605a62d2012-06-24 04:33:36 -07004684static PyStructSequence_Field uname_result_fields[] = {
4685 {"sysname", "operating system name"},
4686 {"nodename", "name of machine on network (implementation-defined)"},
4687 {"release", "operating system release"},
4688 {"version", "operating system version"},
4689 {"machine", "hardware identifier"},
4690 {NULL}
4691};
4692
4693PyDoc_STRVAR(uname_result__doc__,
4694"uname_result: Result from os.uname().\n\n\
4695This object may be accessed either as a tuple of\n\
4696 (sysname, nodename, release, version, machine),\n\
4697or via the attributes sysname, nodename, release, version, and machine.\n\
4698\n\
4699See os.uname for more information.");
4700
4701static PyStructSequence_Desc uname_result_desc = {
Eddie Elizondob3966632019-11-05 07:16:14 -08004702 MODNAME ".uname_result", /* name */
Larry Hastings605a62d2012-06-24 04:33:36 -07004703 uname_result__doc__, /* doc */
4704 uname_result_fields,
4705 5
4706};
4707
Larry Hastings605a62d2012-06-24 04:33:36 -07004708#ifdef HAVE_UNAME
Larry Hastings2f936352014-08-05 14:04:04 +10004709/*[clinic input]
4710os.uname
4711
4712Return an object identifying the current operating system.
4713
4714The object behaves like a named tuple with the following fields:
4715 (sysname, nodename, release, version, machine)
4716
4717[clinic start generated code]*/
4718
Larry Hastings2f936352014-08-05 14:04:04 +10004719static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004720os_uname_impl(PyObject *module)
4721/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004722{
Victor Stinner8c62be82010-05-06 00:08:46 +00004723 struct utsname u;
4724 int res;
Larry Hastings605a62d2012-06-24 04:33:36 -07004725 PyObject *value;
Neal Norwitze241ce82003-02-17 18:17:05 +00004726
Victor Stinner8c62be82010-05-06 00:08:46 +00004727 Py_BEGIN_ALLOW_THREADS
4728 res = uname(&u);
4729 Py_END_ALLOW_THREADS
4730 if (res < 0)
4731 return posix_error();
Larry Hastings605a62d2012-06-24 04:33:36 -07004732
Hai Shif707d942020-03-16 21:15:01 +08004733 PyObject *UnameResultType = get_posix_state(module)->UnameResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -08004734 value = PyStructSequence_New((PyTypeObject *)UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07004735 if (value == NULL)
4736 return NULL;
4737
4738#define SET(i, field) \
4739 { \
Victor Stinnera534fc42013-06-03 22:07:27 +02004740 PyObject *o = PyUnicode_DecodeFSDefault(field); \
Larry Hastings605a62d2012-06-24 04:33:36 -07004741 if (!o) { \
4742 Py_DECREF(value); \
4743 return NULL; \
4744 } \
4745 PyStructSequence_SET_ITEM(value, i, o); \
4746 } \
4747
4748 SET(0, u.sysname);
4749 SET(1, u.nodename);
4750 SET(2, u.release);
4751 SET(3, u.version);
4752 SET(4, u.machine);
4753
4754#undef SET
4755
4756 return value;
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004757}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004758#endif /* HAVE_UNAME */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004759
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004760
Larry Hastings9cf065c2012-06-22 16:30:09 -07004761
4762typedef struct {
4763 int now;
4764 time_t atime_s;
4765 long atime_ns;
4766 time_t mtime_s;
4767 long mtime_ns;
4768} utime_t;
4769
4770/*
Victor Stinner484df002014-10-09 13:52:31 +02004771 * these macros assume that "ut" is a pointer to a utime_t
Larry Hastings9cf065c2012-06-22 16:30:09 -07004772 * they also intentionally leak the declaration of a pointer named "time"
4773 */
4774#define UTIME_TO_TIMESPEC \
4775 struct timespec ts[2]; \
4776 struct timespec *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004777 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004778 time = NULL; \
4779 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004780 ts[0].tv_sec = ut->atime_s; \
4781 ts[0].tv_nsec = ut->atime_ns; \
4782 ts[1].tv_sec = ut->mtime_s; \
4783 ts[1].tv_nsec = ut->mtime_ns; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004784 time = ts; \
4785 } \
4786
4787#define UTIME_TO_TIMEVAL \
4788 struct timeval tv[2]; \
4789 struct timeval *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004790 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004791 time = NULL; \
4792 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004793 tv[0].tv_sec = ut->atime_s; \
4794 tv[0].tv_usec = ut->atime_ns / 1000; \
4795 tv[1].tv_sec = ut->mtime_s; \
4796 tv[1].tv_usec = ut->mtime_ns / 1000; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004797 time = tv; \
4798 } \
4799
4800#define UTIME_TO_UTIMBUF \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004801 struct utimbuf u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004802 struct utimbuf *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004803 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004804 time = NULL; \
4805 else { \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004806 u.actime = ut->atime_s; \
4807 u.modtime = ut->mtime_s; \
4808 time = &u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004809 }
4810
4811#define UTIME_TO_TIME_T \
4812 time_t timet[2]; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004813 time_t *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004814 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004815 time = NULL; \
4816 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004817 timet[0] = ut->atime_s; \
4818 timet[1] = ut->mtime_s; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004819 time = timet; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004820 } \
4821
4822
Victor Stinner528a9ab2015-09-03 21:30:26 +02004823#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004824
4825static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004826utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004827{
4828#ifdef HAVE_UTIMENSAT
4829 int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
4830 UTIME_TO_TIMESPEC;
4831 return utimensat(dir_fd, path, time, flags);
4832#elif defined(HAVE_FUTIMESAT)
4833 UTIME_TO_TIMEVAL;
4834 /*
4835 * follow_symlinks will never be false here;
4836 * we only allow !follow_symlinks and dir_fd together
4837 * if we have utimensat()
4838 */
4839 assert(follow_symlinks);
4840 return futimesat(dir_fd, path, time);
4841#endif
4842}
4843
Larry Hastings2f936352014-08-05 14:04:04 +10004844 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
4845#else
4846 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings9cf065c2012-06-22 16:30:09 -07004847#endif
4848
Victor Stinner528a9ab2015-09-03 21:30:26 +02004849#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004850
4851static int
Victor Stinner484df002014-10-09 13:52:31 +02004852utime_fd(utime_t *ut, int fd)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004853{
4854#ifdef HAVE_FUTIMENS
4855 UTIME_TO_TIMESPEC;
4856 return futimens(fd, time);
4857#else
4858 UTIME_TO_TIMEVAL;
4859 return futimes(fd, time);
4860#endif
4861}
4862
Larry Hastings2f936352014-08-05 14:04:04 +10004863 #define PATH_UTIME_HAVE_FD 1
4864#else
4865 #define PATH_UTIME_HAVE_FD 0
Larry Hastings9cf065c2012-06-22 16:30:09 -07004866#endif
4867
Victor Stinner5ebae872015-09-22 01:29:33 +02004868#if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
4869# define UTIME_HAVE_NOFOLLOW_SYMLINKS
4870#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004871
Victor Stinner4552ced2015-09-21 22:37:15 +02004872#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004873
4874static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004875utime_nofollow_symlinks(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004876{
4877#ifdef HAVE_UTIMENSAT
4878 UTIME_TO_TIMESPEC;
4879 return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
4880#else
4881 UTIME_TO_TIMEVAL;
4882 return lutimes(path, time);
4883#endif
4884}
4885
4886#endif
4887
4888#ifndef MS_WINDOWS
4889
4890static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004891utime_default(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004892{
4893#ifdef HAVE_UTIMENSAT
4894 UTIME_TO_TIMESPEC;
4895 return utimensat(DEFAULT_DIR_FD, path, time, 0);
4896#elif defined(HAVE_UTIMES)
4897 UTIME_TO_TIMEVAL;
4898 return utimes(path, time);
4899#elif defined(HAVE_UTIME_H)
4900 UTIME_TO_UTIMBUF;
4901 return utime(path, time);
4902#else
4903 UTIME_TO_TIME_T;
4904 return utime(path, time);
4905#endif
4906}
4907
4908#endif
4909
Larry Hastings76ad59b2012-05-03 00:30:07 -07004910static int
Victor Stinner1c2fa782020-05-10 11:05:29 +02004911split_py_long_to_s_and_ns(PyObject *module, PyObject *py_long, time_t *s, long *ns)
Larry Hastings76ad59b2012-05-03 00:30:07 -07004912{
4913 int result = 0;
Benjamin Petersonfbd85a02012-05-04 11:06:09 -04004914 PyObject *divmod;
Victor Stinner1c2fa782020-05-10 11:05:29 +02004915 divmod = PyNumber_Divmod(py_long, get_posix_state(module)->billion);
Larry Hastings76ad59b2012-05-03 00:30:07 -07004916 if (!divmod)
4917 goto exit;
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004918 if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
4919 PyErr_Format(PyExc_TypeError,
4920 "%.200s.__divmod__() must return a 2-tuple, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -08004921 _PyType_Name(Py_TYPE(py_long)), _PyType_Name(Py_TYPE(divmod)));
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004922 goto exit;
4923 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004924 *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
4925 if ((*s == -1) && PyErr_Occurred())
4926 goto exit;
4927 *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
Benjamin Peterson35a8f0d2012-05-04 01:10:59 -04004928 if ((*ns == -1) && PyErr_Occurred())
Larry Hastings76ad59b2012-05-03 00:30:07 -07004929 goto exit;
4930
4931 result = 1;
4932exit:
4933 Py_XDECREF(divmod);
4934 return result;
4935}
4936
Larry Hastings2f936352014-08-05 14:04:04 +10004937
4938/*[clinic input]
4939os.utime
4940
4941 path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004942 times: object = None
Larry Hastings2f936352014-08-05 14:04:04 +10004943 *
4944 ns: object = NULL
4945 dir_fd: dir_fd(requires='futimensat') = None
4946 follow_symlinks: bool=True
4947
Martin Panter0ff89092015-09-09 01:56:53 +00004948# "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
Larry Hastings2f936352014-08-05 14:04:04 +10004949
4950Set the access and modified time of path.
4951
4952path may always be specified as a string.
4953On some platforms, path may also be specified as an open file descriptor.
4954 If this functionality is unavailable, using it raises an exception.
4955
4956If times is not None, it must be a tuple (atime, mtime);
4957 atime and mtime should be expressed as float seconds since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004958If ns is specified, it must be a tuple (atime_ns, mtime_ns);
Larry Hastings2f936352014-08-05 14:04:04 +10004959 atime_ns and mtime_ns should be expressed as integer nanoseconds
4960 since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004961If times is None and ns is unspecified, utime uses the current time.
Larry Hastings2f936352014-08-05 14:04:04 +10004962Specifying tuples for both times and ns is an error.
4963
4964If dir_fd is not None, it should be a file descriptor open to a directory,
4965 and path should be relative; path will then be relative to that directory.
4966If follow_symlinks is False, and the last element of the path is a symbolic
4967 link, utime will modify the symbolic link itself instead of the file the
4968 link points to.
4969It is an error to use dir_fd or follow_symlinks when specifying path
4970 as an open file descriptor.
4971dir_fd and follow_symlinks may not be available on your platform.
4972 If they are unavailable, using them will raise a NotImplementedError.
4973
4974[clinic start generated code]*/
4975
Larry Hastings2f936352014-08-05 14:04:04 +10004976static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004977os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
4978 int dir_fd, int follow_symlinks)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004979/*[clinic end generated code: output=cfcac69d027b82cf input=2fbd62a2f228f8f4]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004980{
Larry Hastings9cf065c2012-06-22 16:30:09 -07004981#ifdef MS_WINDOWS
4982 HANDLE hFile;
4983 FILETIME atime, mtime;
4984#else
4985 int result;
4986#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004987
Larry Hastings2f936352014-08-05 14:04:04 +10004988 utime_t utime;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004989
Christian Heimesb3c87242013-08-01 00:08:16 +02004990 memset(&utime, 0, sizeof(utime_t));
Larry Hastings76ad59b2012-05-03 00:30:07 -07004991
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004992 if (times != Py_None && ns) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004993 PyErr_SetString(PyExc_ValueError,
4994 "utime: you may specify either 'times'"
4995 " or 'ns' but not both");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004996 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004997 }
4998
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004999 if (times != Py_None) {
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02005000 time_t a_sec, m_sec;
5001 long a_nsec, m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07005002 if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07005003 PyErr_SetString(PyExc_TypeError,
5004 "utime: 'times' must be either"
5005 " a tuple of two ints or None");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005006 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07005007 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07005008 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04005009 if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
Victor Stinnerdca028b2015-03-30 01:02:57 +02005010 &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04005011 _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
Victor Stinnerdca028b2015-03-30 01:02:57 +02005012 &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005013 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07005014 }
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02005015 utime.atime_s = a_sec;
5016 utime.atime_ns = a_nsec;
5017 utime.mtime_s = m_sec;
5018 utime.mtime_ns = m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07005019 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07005020 else if (ns) {
Larry Hastings76ad59b2012-05-03 00:30:07 -07005021 if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07005022 PyErr_SetString(PyExc_TypeError,
5023 "utime: 'ns' must be a tuple of two ints");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005024 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07005025 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07005026 utime.now = 0;
Victor Stinner1c2fa782020-05-10 11:05:29 +02005027 if (!split_py_long_to_s_and_ns(module, PyTuple_GET_ITEM(ns, 0),
Larry Hastings9cf065c2012-06-22 16:30:09 -07005028 &utime.atime_s, &utime.atime_ns) ||
Victor Stinner1c2fa782020-05-10 11:05:29 +02005029 !split_py_long_to_s_and_ns(module, PyTuple_GET_ITEM(ns, 1),
Larry Hastings9cf065c2012-06-22 16:30:09 -07005030 &utime.mtime_s, &utime.mtime_ns)) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005031 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07005032 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07005033 }
5034 else {
5035 /* times and ns are both None/unspecified. use "now". */
5036 utime.now = 1;
Larry Hastings76ad59b2012-05-03 00:30:07 -07005037 }
5038
Victor Stinner4552ced2015-09-21 22:37:15 +02005039#if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07005040 if (follow_symlinks_specified("utime", follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005041 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07005042#endif
Benjamin Petersonb399ab22012-05-04 01:31:13 -04005043
Larry Hastings2f936352014-08-05 14:04:04 +10005044 if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
5045 dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
5046 fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005047 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07005048
Larry Hastings9cf065c2012-06-22 16:30:09 -07005049#if !defined(HAVE_UTIMENSAT)
5050 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
Georg Brandl969288e2012-06-26 09:25:44 +02005051 PyErr_SetString(PyExc_ValueError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005052 "utime: cannot use dir_fd and follow_symlinks "
5053 "together on this platform");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005054 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07005055 }
5056#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07005057
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005058 if (PySys_Audit("os.utime", "OOOi", path->object, times, ns ? ns : Py_None,
5059 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
5060 return NULL;
5061 }
5062
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00005063#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07005064 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07005065 hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
5066 NULL, OPEN_EXISTING,
5067 FILE_FLAG_BACKUP_SEMANTICS, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005068 Py_END_ALLOW_THREADS
5069 if (hFile == INVALID_HANDLE_VALUE) {
Larry Hastings2f936352014-08-05 14:04:04 +10005070 path_error(path);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005071 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07005072 }
5073
Larry Hastings9cf065c2012-06-22 16:30:09 -07005074 if (utime.now) {
Antoine Pitrou91a7af32013-11-23 15:23:26 +01005075 GetSystemTimeAsFileTime(&mtime);
5076 atime = mtime;
Victor Stinner8c62be82010-05-06 00:08:46 +00005077 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005078 else {
Steve Dowerbf1f3762015-02-21 15:26:02 -08005079 _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
5080 _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
Victor Stinner8c62be82010-05-06 00:08:46 +00005081 }
5082 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
5083 /* Avoid putting the file name into the error here,
5084 as that may confuse the user into believing that
5085 something is wrong with the file, when it also
5086 could be the time stamp that gives a problem. */
Victor Stinnerb024e842012-10-31 22:24:06 +01005087 PyErr_SetFromWindowsErr(0);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005088 CloseHandle(hFile);
5089 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00005090 }
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005091 CloseHandle(hFile);
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00005092#else /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07005093 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00005094
Victor Stinner4552ced2015-09-21 22:37:15 +02005095#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07005096 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10005097 result = utime_nofollow_symlinks(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005098 else
Larry Hastings9e3e70b2011-09-08 19:29:07 -07005099#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07005100
Victor Stinner528a9ab2015-09-03 21:30:26 +02005101#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07005102 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10005103 result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005104 else
5105#endif
5106
Victor Stinner528a9ab2015-09-03 21:30:26 +02005107#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings2f936352014-08-05 14:04:04 +10005108 if (path->fd != -1)
5109 result = utime_fd(&utime, path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005110 else
5111#endif
5112
Larry Hastings2f936352014-08-05 14:04:04 +10005113 result = utime_default(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005114
5115 Py_END_ALLOW_THREADS
5116
5117 if (result < 0) {
5118 /* see previous comment about not putting filename in error here */
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005119 posix_error();
5120 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00005121 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07005122
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00005123#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07005124
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005125 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005126}
5127
Guido van Rossum3b066191991-06-04 19:40:25 +00005128/* Process operations */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005129
Larry Hastings2f936352014-08-05 14:04:04 +10005130
5131/*[clinic input]
5132os._exit
5133
5134 status: int
5135
5136Exit to the system with specified status, without normal exit processing.
5137[clinic start generated code]*/
5138
Larry Hastings2f936352014-08-05 14:04:04 +10005139static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005140os__exit_impl(PyObject *module, int status)
5141/*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005142{
5143 _exit(status);
Victor Stinner8c62be82010-05-06 00:08:46 +00005144 return NULL; /* Make gcc -Wall happy */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005145}
5146
Steve Dowercc16be82016-09-08 10:35:16 -07005147#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5148#define EXECV_CHAR wchar_t
5149#else
5150#define EXECV_CHAR char
5151#endif
5152
pxinwrf2d7ac72019-05-21 18:46:37 +08005153#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005154static void
Steve Dowercc16be82016-09-08 10:35:16 -07005155free_string_array(EXECV_CHAR **array, Py_ssize_t count)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005156{
Victor Stinner8c62be82010-05-06 00:08:46 +00005157 Py_ssize_t i;
5158 for (i = 0; i < count; i++)
5159 PyMem_Free(array[i]);
5160 PyMem_DEL(array);
Martin v. Löwis114619e2002-10-07 06:44:21 +00005161}
Martin v. Löwis011e8422009-05-05 04:43:17 +00005162
Berker Peksag81816462016-09-15 20:19:47 +03005163static int
5164fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
Martin v. Löwis011e8422009-05-05 04:43:17 +00005165{
Victor Stinner8c62be82010-05-06 00:08:46 +00005166 Py_ssize_t size;
Berker Peksag81816462016-09-15 20:19:47 +03005167 PyObject *ub;
5168 int result = 0;
Steve Dowercc16be82016-09-08 10:35:16 -07005169#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
Berker Peksag81816462016-09-15 20:19:47 +03005170 if (!PyUnicode_FSDecoder(o, &ub))
Steve Dowercc16be82016-09-08 10:35:16 -07005171 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005172 *out = PyUnicode_AsWideCharString(ub, &size);
5173 if (*out)
5174 result = 1;
Steve Dowercc16be82016-09-08 10:35:16 -07005175#else
Berker Peksag81816462016-09-15 20:19:47 +03005176 if (!PyUnicode_FSConverter(o, &ub))
Victor Stinner8c62be82010-05-06 00:08:46 +00005177 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005178 size = PyBytes_GET_SIZE(ub);
5179 *out = PyMem_Malloc(size + 1);
5180 if (*out) {
5181 memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
5182 result = 1;
5183 } else
Victor Stinner50abf222013-11-07 23:56:10 +01005184 PyErr_NoMemory();
Steve Dowercc16be82016-09-08 10:35:16 -07005185#endif
Berker Peksag81816462016-09-15 20:19:47 +03005186 Py_DECREF(ub);
5187 return result;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005188}
Martin v. Löwis114619e2002-10-07 06:44:21 +00005189#endif
5190
pxinwrf2d7ac72019-05-21 18:46:37 +08005191#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
Steve Dowercc16be82016-09-08 10:35:16 -07005192static EXECV_CHAR**
Victor Stinner13bb71c2010-04-23 21:41:56 +00005193parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
5194{
Victor Stinner8c62be82010-05-06 00:08:46 +00005195 Py_ssize_t i, pos, envc;
5196 PyObject *keys=NULL, *vals=NULL;
Berker Peksag81816462016-09-15 20:19:47 +03005197 PyObject *key, *val, *key2, *val2, *keyval;
Steve Dowercc16be82016-09-08 10:35:16 -07005198 EXECV_CHAR **envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005199
Victor Stinner8c62be82010-05-06 00:08:46 +00005200 i = PyMapping_Size(env);
5201 if (i < 0)
5202 return NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07005203 envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005204 if (envlist == NULL) {
5205 PyErr_NoMemory();
5206 return NULL;
5207 }
5208 envc = 0;
5209 keys = PyMapping_Keys(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005210 if (!keys)
5211 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00005212 vals = PyMapping_Values(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005213 if (!vals)
Victor Stinner8c62be82010-05-06 00:08:46 +00005214 goto error;
5215 if (!PyList_Check(keys) || !PyList_Check(vals)) {
5216 PyErr_Format(PyExc_TypeError,
5217 "env.keys() or env.values() is not a list");
5218 goto error;
5219 }
Victor Stinner13bb71c2010-04-23 21:41:56 +00005220
Victor Stinner8c62be82010-05-06 00:08:46 +00005221 for (pos = 0; pos < i; pos++) {
5222 key = PyList_GetItem(keys, pos);
5223 val = PyList_GetItem(vals, pos);
5224 if (!key || !val)
5225 goto error;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005226
Berker Peksag81816462016-09-15 20:19:47 +03005227#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5228 if (!PyUnicode_FSDecoder(key, &key2))
5229 goto error;
5230 if (!PyUnicode_FSDecoder(val, &val2)) {
5231 Py_DECREF(key2);
5232 goto error;
5233 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005234 /* Search from index 1 because on Windows starting '=' is allowed for
5235 defining hidden environment variables. */
5236 if (PyUnicode_GET_LENGTH(key2) == 0 ||
5237 PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
5238 {
5239 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005240 Py_DECREF(key2);
5241 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005242 goto error;
5243 }
Berker Peksag81816462016-09-15 20:19:47 +03005244 keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
5245#else
5246 if (!PyUnicode_FSConverter(key, &key2))
5247 goto error;
5248 if (!PyUnicode_FSConverter(val, &val2)) {
5249 Py_DECREF(key2);
5250 goto error;
5251 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005252 if (PyBytes_GET_SIZE(key2) == 0 ||
5253 strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
5254 {
5255 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005256 Py_DECREF(key2);
5257 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005258 goto error;
5259 }
Berker Peksag81816462016-09-15 20:19:47 +03005260 keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
5261 PyBytes_AS_STRING(val2));
5262#endif
5263 Py_DECREF(key2);
5264 Py_DECREF(val2);
Steve Dowercc16be82016-09-08 10:35:16 -07005265 if (!keyval)
Victor Stinner8c62be82010-05-06 00:08:46 +00005266 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -07005267
5268 if (!fsconvert_strdup(keyval, &envlist[envc++])) {
5269 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005270 goto error;
5271 }
Berker Peksag81816462016-09-15 20:19:47 +03005272
Steve Dowercc16be82016-09-08 10:35:16 -07005273 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005274 }
5275 Py_DECREF(vals);
5276 Py_DECREF(keys);
Victor Stinner13bb71c2010-04-23 21:41:56 +00005277
Victor Stinner8c62be82010-05-06 00:08:46 +00005278 envlist[envc] = 0;
5279 *envc_ptr = envc;
5280 return envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005281
5282error:
Victor Stinner8c62be82010-05-06 00:08:46 +00005283 Py_XDECREF(keys);
5284 Py_XDECREF(vals);
Steve Dowercc16be82016-09-08 10:35:16 -07005285 free_string_array(envlist, envc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005286 return NULL;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005287}
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005288
Steve Dowercc16be82016-09-08 10:35:16 -07005289static EXECV_CHAR**
Ross Lagerwall7807c352011-03-17 20:20:30 +02005290parse_arglist(PyObject* argv, Py_ssize_t *argc)
5291{
5292 int i;
Steve Dowercc16be82016-09-08 10:35:16 -07005293 EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005294 if (argvlist == NULL) {
5295 PyErr_NoMemory();
5296 return NULL;
5297 }
5298 for (i = 0; i < *argc; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005299 PyObject* item = PySequence_ITEM(argv, i);
5300 if (item == NULL)
5301 goto fail;
5302 if (!fsconvert_strdup(item, &argvlist[i])) {
5303 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005304 goto fail;
5305 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005306 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005307 }
5308 argvlist[*argc] = NULL;
5309 return argvlist;
5310fail:
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005311 *argc = i;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005312 free_string_array(argvlist, *argc);
5313 return NULL;
5314}
Steve Dowercc16be82016-09-08 10:35:16 -07005315
Ross Lagerwall7807c352011-03-17 20:20:30 +02005316#endif
5317
Larry Hastings2f936352014-08-05 14:04:04 +10005318
Ross Lagerwall7807c352011-03-17 20:20:30 +02005319#ifdef HAVE_EXECV
Larry Hastings2f936352014-08-05 14:04:04 +10005320/*[clinic input]
5321os.execv
5322
Steve Dowercc16be82016-09-08 10:35:16 -07005323 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005324 Path of executable file.
5325 argv: object
5326 Tuple or list of strings.
5327 /
5328
5329Execute an executable path with arguments, replacing current process.
5330[clinic start generated code]*/
5331
Larry Hastings2f936352014-08-05 14:04:04 +10005332static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005333os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
5334/*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005335{
Steve Dowercc16be82016-09-08 10:35:16 -07005336 EXECV_CHAR **argvlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005337 Py_ssize_t argc;
5338
5339 /* execv has two arguments: (path, argv), where
5340 argv is a list or tuple of strings. */
5341
Ross Lagerwall7807c352011-03-17 20:20:30 +02005342 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
5343 PyErr_SetString(PyExc_TypeError,
5344 "execv() arg 2 must be a tuple or list");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005345 return NULL;
5346 }
5347 argc = PySequence_Size(argv);
5348 if (argc < 1) {
5349 PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005350 return NULL;
5351 }
5352
5353 argvlist = parse_arglist(argv, &argc);
5354 if (argvlist == NULL) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02005355 return NULL;
5356 }
Steve Dowerbce26262016-11-19 19:17:26 -08005357 if (!argvlist[0][0]) {
5358 PyErr_SetString(PyExc_ValueError,
5359 "execv() arg 2 first element cannot be empty");
5360 free_string_array(argvlist, argc);
5361 return NULL;
5362 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005363
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005364 if (PySys_Audit("os.exec", "OOO", path->object, argv, Py_None) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -08005365 free_string_array(argvlist, argc);
5366 return NULL;
5367 }
5368
Steve Dowerbce26262016-11-19 19:17:26 -08005369 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005370#ifdef HAVE_WEXECV
5371 _wexecv(path->wide, argvlist);
5372#else
5373 execv(path->narrow, argvlist);
5374#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005375 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005376
5377 /* If we get here it's definitely an error */
5378
5379 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005380 return posix_error();
5381}
5382
Larry Hastings2f936352014-08-05 14:04:04 +10005383
5384/*[clinic input]
5385os.execve
5386
5387 path: path_t(allow_fd='PATH_HAVE_FEXECVE')
5388 Path of executable file.
5389 argv: object
5390 Tuple or list of strings.
5391 env: object
5392 Dictionary of strings mapping to strings.
5393
5394Execute an executable path with arguments, replacing current process.
5395[clinic start generated code]*/
5396
Larry Hastings2f936352014-08-05 14:04:04 +10005397static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005398os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
5399/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005400{
Steve Dowercc16be82016-09-08 10:35:16 -07005401 EXECV_CHAR **argvlist = NULL;
5402 EXECV_CHAR **envlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005403 Py_ssize_t argc, envc;
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005404
Victor Stinner8c62be82010-05-06 00:08:46 +00005405 /* execve has three arguments: (path, argv, env), where
5406 argv is a list or tuple of strings and env is a dictionary
5407 like posix.environ. */
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005408
Ross Lagerwall7807c352011-03-17 20:20:30 +02005409 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005410 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005411 "execve: argv must be a tuple or list");
Saiyang Gou95f60012020-02-04 16:15:00 -08005412 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005413 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005414 argc = PySequence_Size(argv);
Steve Dowerbce26262016-11-19 19:17:26 -08005415 if (argc < 1) {
5416 PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
5417 return NULL;
5418 }
5419
Victor Stinner8c62be82010-05-06 00:08:46 +00005420 if (!PyMapping_Check(env)) {
5421 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005422 "execve: environment must be a mapping object");
Saiyang Gou95f60012020-02-04 16:15:00 -08005423 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005424 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005425
Ross Lagerwall7807c352011-03-17 20:20:30 +02005426 argvlist = parse_arglist(argv, &argc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005427 if (argvlist == NULL) {
Saiyang Gou95f60012020-02-04 16:15:00 -08005428 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005429 }
Steve Dowerbce26262016-11-19 19:17:26 -08005430 if (!argvlist[0][0]) {
5431 PyErr_SetString(PyExc_ValueError,
5432 "execve: argv first element cannot be empty");
Saiyang Gou95f60012020-02-04 16:15:00 -08005433 goto fail_0;
Steve Dowerbce26262016-11-19 19:17:26 -08005434 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005435
Victor Stinner8c62be82010-05-06 00:08:46 +00005436 envlist = parse_envlist(env, &envc);
5437 if (envlist == NULL)
Saiyang Gou95f60012020-02-04 16:15:00 -08005438 goto fail_0;
5439
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005440 if (PySys_Audit("os.exec", "OOO", path->object, argv, env) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -08005441 goto fail_1;
5442 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005443
Steve Dowerbce26262016-11-19 19:17:26 -08005444 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07005445#ifdef HAVE_FEXECVE
Larry Hastings2f936352014-08-05 14:04:04 +10005446 if (path->fd > -1)
5447 fexecve(path->fd, argvlist, envlist);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005448 else
5449#endif
Steve Dowercc16be82016-09-08 10:35:16 -07005450#ifdef HAVE_WEXECV
5451 _wexecve(path->wide, argvlist, envlist);
5452#else
Larry Hastings2f936352014-08-05 14:04:04 +10005453 execve(path->narrow, argvlist, envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07005454#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005455 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005456
5457 /* If we get here it's definitely an error */
5458
Alexey Izbyshev83460312018-10-20 03:28:22 +03005459 posix_path_error(path);
Saiyang Gou95f60012020-02-04 16:15:00 -08005460 fail_1:
Steve Dowercc16be82016-09-08 10:35:16 -07005461 free_string_array(envlist, envc);
Saiyang Gou95f60012020-02-04 16:15:00 -08005462 fail_0:
Larry Hastings9cf065c2012-06-22 16:30:09 -07005463 if (argvlist)
5464 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005465 return NULL;
5466}
Steve Dowercc16be82016-09-08 10:35:16 -07005467
Larry Hastings9cf065c2012-06-22 16:30:09 -07005468#endif /* HAVE_EXECV */
5469
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005470#ifdef HAVE_POSIX_SPAWN
5471
5472enum posix_spawn_file_actions_identifier {
5473 POSIX_SPAWN_OPEN,
5474 POSIX_SPAWN_CLOSE,
5475 POSIX_SPAWN_DUP2
5476};
5477
William Orr81574b82018-10-01 22:19:56 -07005478#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005479static int
Victor Stinner1c2fa782020-05-10 11:05:29 +02005480convert_sched_param(PyObject *module, PyObject *param, struct sched_param *res);
William Orr81574b82018-10-01 22:19:56 -07005481#endif
Pablo Galindo254a4662018-09-07 16:44:24 +01005482
5483static int
Victor Stinner1c2fa782020-05-10 11:05:29 +02005484parse_posix_spawn_flags(PyObject *module, const char *func_name, PyObject *setpgroup,
Victor Stinner325e4ba2019-02-01 15:47:24 +01005485 int resetids, int setsid, PyObject *setsigmask,
Pablo Galindo254a4662018-09-07 16:44:24 +01005486 PyObject *setsigdef, PyObject *scheduler,
5487 posix_spawnattr_t *attrp)
5488{
5489 long all_flags = 0;
5490
5491 errno = posix_spawnattr_init(attrp);
5492 if (errno) {
5493 posix_error();
5494 return -1;
5495 }
5496
5497 if (setpgroup) {
5498 pid_t pgid = PyLong_AsPid(setpgroup);
5499 if (pgid == (pid_t)-1 && PyErr_Occurred()) {
5500 goto fail;
5501 }
5502 errno = posix_spawnattr_setpgroup(attrp, pgid);
5503 if (errno) {
5504 posix_error();
5505 goto fail;
5506 }
5507 all_flags |= POSIX_SPAWN_SETPGROUP;
5508 }
5509
5510 if (resetids) {
5511 all_flags |= POSIX_SPAWN_RESETIDS;
5512 }
5513
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005514 if (setsid) {
5515#ifdef POSIX_SPAWN_SETSID
5516 all_flags |= POSIX_SPAWN_SETSID;
5517#elif defined(POSIX_SPAWN_SETSID_NP)
5518 all_flags |= POSIX_SPAWN_SETSID_NP;
5519#else
5520 argument_unavailable_error(func_name, "setsid");
5521 return -1;
5522#endif
5523 }
5524
Pablo Galindo254a4662018-09-07 16:44:24 +01005525 if (setsigmask) {
5526 sigset_t set;
5527 if (!_Py_Sigset_Converter(setsigmask, &set)) {
5528 goto fail;
5529 }
5530 errno = posix_spawnattr_setsigmask(attrp, &set);
5531 if (errno) {
5532 posix_error();
5533 goto fail;
5534 }
5535 all_flags |= POSIX_SPAWN_SETSIGMASK;
5536 }
5537
5538 if (setsigdef) {
5539 sigset_t set;
5540 if (!_Py_Sigset_Converter(setsigdef, &set)) {
5541 goto fail;
5542 }
5543 errno = posix_spawnattr_setsigdefault(attrp, &set);
5544 if (errno) {
5545 posix_error();
5546 goto fail;
5547 }
5548 all_flags |= POSIX_SPAWN_SETSIGDEF;
5549 }
5550
5551 if (scheduler) {
5552#ifdef POSIX_SPAWN_SETSCHEDULER
5553 PyObject *py_schedpolicy;
Victor Stinner1c2fa782020-05-10 11:05:29 +02005554 PyObject *schedparam_obj;
Pablo Galindo254a4662018-09-07 16:44:24 +01005555 struct sched_param schedparam;
5556
Victor Stinner1c2fa782020-05-10 11:05:29 +02005557 if (!PyArg_ParseTuple(scheduler, "OO"
Pablo Galindo254a4662018-09-07 16:44:24 +01005558 ";A scheduler tuple must have two elements",
Victor Stinner1c2fa782020-05-10 11:05:29 +02005559 &py_schedpolicy, &schedparam_obj)) {
5560 goto fail;
5561 }
5562 if (!convert_sched_param(module, schedparam_obj, &schedparam)) {
Pablo Galindo254a4662018-09-07 16:44:24 +01005563 goto fail;
5564 }
5565 if (py_schedpolicy != Py_None) {
5566 int schedpolicy = _PyLong_AsInt(py_schedpolicy);
5567
5568 if (schedpolicy == -1 && PyErr_Occurred()) {
5569 goto fail;
5570 }
5571 errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
5572 if (errno) {
5573 posix_error();
5574 goto fail;
5575 }
5576 all_flags |= POSIX_SPAWN_SETSCHEDULER;
5577 }
5578 errno = posix_spawnattr_setschedparam(attrp, &schedparam);
5579 if (errno) {
5580 posix_error();
5581 goto fail;
5582 }
5583 all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
5584#else
5585 PyErr_SetString(PyExc_NotImplementedError,
5586 "The scheduler option is not supported in this system.");
5587 goto fail;
5588#endif
5589 }
5590
5591 errno = posix_spawnattr_setflags(attrp, all_flags);
5592 if (errno) {
5593 posix_error();
5594 goto fail;
5595 }
5596
5597 return 0;
5598
5599fail:
5600 (void)posix_spawnattr_destroy(attrp);
5601 return -1;
5602}
5603
5604static int
Serhiy Storchakaef347532018-05-01 16:45:04 +03005605parse_file_actions(PyObject *file_actions,
Pablo Galindocb970732018-06-19 09:19:50 +01005606 posix_spawn_file_actions_t *file_actionsp,
5607 PyObject *temp_buffer)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005608{
5609 PyObject *seq;
5610 PyObject *file_action = NULL;
5611 PyObject *tag_obj;
5612
5613 seq = PySequence_Fast(file_actions,
5614 "file_actions must be a sequence or None");
5615 if (seq == NULL) {
5616 return -1;
5617 }
5618
5619 errno = posix_spawn_file_actions_init(file_actionsp);
5620 if (errno) {
5621 posix_error();
5622 Py_DECREF(seq);
5623 return -1;
5624 }
5625
Zackery Spytzd52a83a2019-06-26 14:54:20 -06005626 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
Serhiy Storchakaef347532018-05-01 16:45:04 +03005627 file_action = PySequence_Fast_GET_ITEM(seq, i);
5628 Py_INCREF(file_action);
5629 if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
5630 PyErr_SetString(PyExc_TypeError,
5631 "Each file_actions element must be a non-empty tuple");
5632 goto fail;
5633 }
5634 long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
5635 if (tag == -1 && PyErr_Occurred()) {
5636 goto fail;
5637 }
5638
5639 /* Populate the file_actions object */
5640 switch (tag) {
5641 case POSIX_SPAWN_OPEN: {
5642 int fd, oflag;
5643 PyObject *path;
5644 unsigned long mode;
5645 if (!PyArg_ParseTuple(file_action, "OiO&ik"
5646 ";A open file_action tuple must have 5 elements",
5647 &tag_obj, &fd, PyUnicode_FSConverter, &path,
5648 &oflag, &mode))
5649 {
5650 goto fail;
5651 }
Pablo Galindocb970732018-06-19 09:19:50 +01005652 if (PyList_Append(temp_buffer, path)) {
5653 Py_DECREF(path);
5654 goto fail;
5655 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005656 errno = posix_spawn_file_actions_addopen(file_actionsp,
5657 fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
Pablo Galindocb970732018-06-19 09:19:50 +01005658 Py_DECREF(path);
Serhiy Storchakaef347532018-05-01 16:45:04 +03005659 if (errno) {
5660 posix_error();
5661 goto fail;
5662 }
5663 break;
5664 }
5665 case POSIX_SPAWN_CLOSE: {
5666 int fd;
5667 if (!PyArg_ParseTuple(file_action, "Oi"
5668 ";A close file_action tuple must have 2 elements",
5669 &tag_obj, &fd))
5670 {
5671 goto fail;
5672 }
5673 errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
5674 if (errno) {
5675 posix_error();
5676 goto fail;
5677 }
5678 break;
5679 }
5680 case POSIX_SPAWN_DUP2: {
5681 int fd1, fd2;
5682 if (!PyArg_ParseTuple(file_action, "Oii"
5683 ";A dup2 file_action tuple must have 3 elements",
5684 &tag_obj, &fd1, &fd2))
5685 {
5686 goto fail;
5687 }
5688 errno = posix_spawn_file_actions_adddup2(file_actionsp,
5689 fd1, fd2);
5690 if (errno) {
5691 posix_error();
5692 goto fail;
5693 }
5694 break;
5695 }
5696 default: {
5697 PyErr_SetString(PyExc_TypeError,
5698 "Unknown file_actions identifier");
5699 goto fail;
5700 }
5701 }
5702 Py_DECREF(file_action);
5703 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005704
Serhiy Storchakaef347532018-05-01 16:45:04 +03005705 Py_DECREF(seq);
5706 return 0;
5707
5708fail:
5709 Py_DECREF(seq);
5710 Py_DECREF(file_action);
5711 (void)posix_spawn_file_actions_destroy(file_actionsp);
5712 return -1;
5713}
5714
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005715
5716static PyObject *
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005717py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
5718 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005719 PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005720 PyObject *setsigdef, PyObject *scheduler)
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005721{
Victor Stinner325e4ba2019-02-01 15:47:24 +01005722 const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005723 EXECV_CHAR **argvlist = NULL;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005724 EXECV_CHAR **envlist = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005725 posix_spawn_file_actions_t file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005726 posix_spawn_file_actions_t *file_actionsp = NULL;
Pablo Galindo254a4662018-09-07 16:44:24 +01005727 posix_spawnattr_t attr;
5728 posix_spawnattr_t *attrp = NULL;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005729 Py_ssize_t argc, envc;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005730 PyObject *result = NULL;
Pablo Galindocb970732018-06-19 09:19:50 +01005731 PyObject *temp_buffer = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005732 pid_t pid;
5733 int err_code;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005734
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005735 /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
Serhiy Storchakaef347532018-05-01 16:45:04 +03005736 argv is a list or tuple of strings and env is a dictionary
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005737 like posix.environ. */
5738
Serhiy Storchakaef347532018-05-01 16:45:04 +03005739 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005740 PyErr_Format(PyExc_TypeError,
5741 "%s: argv must be a tuple or list", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005742 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005743 }
5744 argc = PySequence_Size(argv);
5745 if (argc < 1) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005746 PyErr_Format(PyExc_ValueError,
5747 "%s: argv must not be empty", func_name);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005748 return NULL;
5749 }
5750
5751 if (!PyMapping_Check(env)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005752 PyErr_Format(PyExc_TypeError,
5753 "%s: environment must be a mapping object", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005754 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005755 }
5756
5757 argvlist = parse_arglist(argv, &argc);
5758 if (argvlist == NULL) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005759 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005760 }
5761 if (!argvlist[0][0]) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005762 PyErr_Format(PyExc_ValueError,
5763 "%s: argv first element cannot be empty", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005764 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005765 }
5766
5767 envlist = parse_envlist(env, &envc);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005768 if (envlist == NULL) {
5769 goto exit;
5770 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005771
Anthony Shaw948ed8c2019-05-10 12:00:06 +10005772 if (file_actions != NULL && file_actions != Py_None) {
Pablo Galindocb970732018-06-19 09:19:50 +01005773 /* There is a bug in old versions of glibc that makes some of the
5774 * helper functions for manipulating file actions not copy the provided
5775 * buffers. The problem is that posix_spawn_file_actions_addopen does not
5776 * copy the value of path for some old versions of glibc (<2.20).
5777 * The use of temp_buffer here is a workaround that keeps the
5778 * python objects that own the buffers alive until posix_spawn gets called.
5779 * Check https://bugs.python.org/issue33630 and
5780 * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
5781 temp_buffer = PyList_New(0);
5782 if (!temp_buffer) {
5783 goto exit;
5784 }
5785 if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005786 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005787 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005788 file_actionsp = &file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005789 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005790
Victor Stinner1c2fa782020-05-10 11:05:29 +02005791 if (parse_posix_spawn_flags(module, func_name, setpgroup, resetids, setsid,
Victor Stinner325e4ba2019-02-01 15:47:24 +01005792 setsigmask, setsigdef, scheduler, &attr)) {
Pablo Galindo254a4662018-09-07 16:44:24 +01005793 goto exit;
5794 }
5795 attrp = &attr;
5796
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005797 if (PySys_Audit("os.posix_spawn", "OOO", path->object, argv, env) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -08005798 goto exit;
5799 }
5800
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005801 _Py_BEGIN_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005802#ifdef HAVE_POSIX_SPAWNP
5803 if (use_posix_spawnp) {
5804 err_code = posix_spawnp(&pid, path->narrow,
5805 file_actionsp, attrp, argvlist, envlist);
5806 }
5807 else
5808#endif /* HAVE_POSIX_SPAWNP */
5809 {
5810 err_code = posix_spawn(&pid, path->narrow,
5811 file_actionsp, attrp, argvlist, envlist);
5812 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005813 _Py_END_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005814
Serhiy Storchakaef347532018-05-01 16:45:04 +03005815 if (err_code) {
5816 errno = err_code;
5817 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005818 goto exit;
5819 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08005820#ifdef _Py_MEMORY_SANITIZER
5821 __msan_unpoison(&pid, sizeof(pid));
5822#endif
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005823 result = PyLong_FromPid(pid);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005824
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005825exit:
Serhiy Storchakaef347532018-05-01 16:45:04 +03005826 if (file_actionsp) {
5827 (void)posix_spawn_file_actions_destroy(file_actionsp);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005828 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005829 if (attrp) {
5830 (void)posix_spawnattr_destroy(attrp);
5831 }
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005832 if (envlist) {
5833 free_string_array(envlist, envc);
5834 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005835 if (argvlist) {
5836 free_string_array(argvlist, argc);
5837 }
Pablo Galindocb970732018-06-19 09:19:50 +01005838 Py_XDECREF(temp_buffer);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005839 return result;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005840}
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005841
5842
5843/*[clinic input]
5844
5845os.posix_spawn
5846 path: path_t
5847 Path of executable file.
5848 argv: object
5849 Tuple or list of strings.
5850 env: object
5851 Dictionary of strings mapping to strings.
5852 /
5853 *
5854 file_actions: object(c_default='NULL') = ()
5855 A sequence of file action tuples.
5856 setpgroup: object = NULL
5857 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5858 resetids: bool(accept={int}) = False
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005859 If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
5860 setsid: bool(accept={int}) = False
5861 If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005862 setsigmask: object(c_default='NULL') = ()
5863 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5864 setsigdef: object(c_default='NULL') = ()
5865 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5866 scheduler: object = NULL
5867 A tuple with the scheduler policy (optional) and parameters.
5868
5869Execute the program specified by path in a new process.
5870[clinic start generated code]*/
5871
5872static PyObject *
5873os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
5874 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005875 PyObject *setpgroup, int resetids, int setsid,
5876 PyObject *setsigmask, PyObject *setsigdef,
5877 PyObject *scheduler)
5878/*[clinic end generated code: output=14a1098c566bc675 input=8c6305619a00ad04]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005879{
5880 return py_posix_spawn(0, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005881 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005882 scheduler);
5883}
5884 #endif /* HAVE_POSIX_SPAWN */
5885
5886
5887
5888#ifdef HAVE_POSIX_SPAWNP
5889/*[clinic input]
5890
5891os.posix_spawnp
5892 path: path_t
5893 Path of executable file.
5894 argv: object
5895 Tuple or list of strings.
5896 env: object
5897 Dictionary of strings mapping to strings.
5898 /
5899 *
5900 file_actions: object(c_default='NULL') = ()
5901 A sequence of file action tuples.
5902 setpgroup: object = NULL
5903 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5904 resetids: bool(accept={int}) = False
5905 If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005906 setsid: bool(accept={int}) = False
5907 If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005908 setsigmask: object(c_default='NULL') = ()
5909 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5910 setsigdef: object(c_default='NULL') = ()
5911 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5912 scheduler: object = NULL
5913 A tuple with the scheduler policy (optional) and parameters.
5914
5915Execute the program specified by path in a new process.
5916[clinic start generated code]*/
5917
5918static PyObject *
5919os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
5920 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005921 PyObject *setpgroup, int resetids, int setsid,
5922 PyObject *setsigmask, PyObject *setsigdef,
5923 PyObject *scheduler)
5924/*[clinic end generated code: output=7b9aaefe3031238d input=c1911043a22028da]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005925{
5926 return py_posix_spawn(1, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005927 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005928 scheduler);
5929}
5930#endif /* HAVE_POSIX_SPAWNP */
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005931
pxinwrf2d7ac72019-05-21 18:46:37 +08005932#ifdef HAVE_RTPSPAWN
5933static intptr_t
5934_rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
5935 const char *envp[])
5936{
5937 RTP_ID rtpid;
5938 int status;
5939 pid_t res;
5940 int async_err = 0;
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005941
pxinwrf2d7ac72019-05-21 18:46:37 +08005942 /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
5943 uStackSize=0 cannot be used, the default stack size is too small for
5944 Python. */
5945 if (envp) {
5946 rtpid = rtpSpawn(rtpFileName, argv, envp,
5947 100, 0x1000000, 0, VX_FP_TASK);
5948 }
5949 else {
5950 rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
5951 100, 0x1000000, 0, VX_FP_TASK);
5952 }
5953 if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
5954 do {
5955 res = waitpid((pid_t)rtpid, &status, 0);
5956 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
5957
5958 if (res < 0)
5959 return RTP_ID_ERROR;
5960 return ((intptr_t)status);
5961 }
5962 return ((intptr_t)rtpid);
5963}
5964#endif
5965
5966#if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
Larry Hastings2f936352014-08-05 14:04:04 +10005967/*[clinic input]
5968os.spawnv
5969
5970 mode: int
5971 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005972 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005973 Path of executable file.
5974 argv: object
5975 Tuple or list of strings.
5976 /
5977
5978Execute the program specified by path in a new process.
5979[clinic start generated code]*/
5980
Larry Hastings2f936352014-08-05 14:04:04 +10005981static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005982os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
5983/*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005984{
Steve Dowercc16be82016-09-08 10:35:16 -07005985 EXECV_CHAR **argvlist;
Larry Hastings2f936352014-08-05 14:04:04 +10005986 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00005987 Py_ssize_t argc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005988 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005989 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Guido van Rossuma1065681999-01-25 23:20:23 +00005990
Victor Stinner8c62be82010-05-06 00:08:46 +00005991 /* spawnv has three arguments: (mode, path, argv), where
5992 argv is a list or tuple of strings. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005993
Victor Stinner8c62be82010-05-06 00:08:46 +00005994 if (PyList_Check(argv)) {
5995 argc = PyList_Size(argv);
5996 getitem = PyList_GetItem;
5997 }
5998 else if (PyTuple_Check(argv)) {
5999 argc = PyTuple_Size(argv);
6000 getitem = PyTuple_GetItem;
6001 }
6002 else {
6003 PyErr_SetString(PyExc_TypeError,
6004 "spawnv() arg 2 must be a tuple or list");
Victor Stinner8c62be82010-05-06 00:08:46 +00006005 return NULL;
6006 }
Steve Dower859fd7b2016-11-19 18:53:19 -08006007 if (argc == 0) {
6008 PyErr_SetString(PyExc_ValueError,
6009 "spawnv() arg 2 cannot be empty");
6010 return NULL;
6011 }
Guido van Rossuma1065681999-01-25 23:20:23 +00006012
Steve Dowercc16be82016-09-08 10:35:16 -07006013 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00006014 if (argvlist == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00006015 return PyErr_NoMemory();
6016 }
6017 for (i = 0; i < argc; i++) {
6018 if (!fsconvert_strdup((*getitem)(argv, i),
6019 &argvlist[i])) {
6020 free_string_array(argvlist, i);
6021 PyErr_SetString(
6022 PyExc_TypeError,
6023 "spawnv() arg 2 must contain only strings");
Victor Stinner8c62be82010-05-06 00:08:46 +00006024 return NULL;
6025 }
Steve Dower93ff8722016-11-19 19:03:54 -08006026 if (i == 0 && !argvlist[0][0]) {
Victor Stinner8acb4cf2017-06-15 15:30:40 +02006027 free_string_array(argvlist, i + 1);
Steve Dower93ff8722016-11-19 19:03:54 -08006028 PyErr_SetString(
6029 PyExc_ValueError,
6030 "spawnv() arg 2 first element cannot be empty");
6031 return NULL;
6032 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006033 }
6034 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00006035
pxinwrf2d7ac72019-05-21 18:46:37 +08006036#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00006037 if (mode == _OLD_P_OVERLAY)
6038 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08006039#endif
Tim Peters5aa91602002-01-30 05:46:57 +00006040
Saiyang Gou7514f4f2020-02-12 23:47:42 -08006041 if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv,
Saiyang Gou95f60012020-02-04 16:15:00 -08006042 Py_None) < 0) {
6043 free_string_array(argvlist, argc);
6044 return NULL;
6045 }
6046
Victor Stinner8c62be82010-05-06 00:08:46 +00006047 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07006048 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07006049#ifdef HAVE_WSPAWNV
6050 spawnval = _wspawnv(mode, path->wide, argvlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08006051#elif defined(HAVE_RTPSPAWN)
6052 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
Steve Dowercc16be82016-09-08 10:35:16 -07006053#else
6054 spawnval = _spawnv(mode, path->narrow, argvlist);
6055#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07006056 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00006057 Py_END_ALLOW_THREADS
Tim Peters5aa91602002-01-30 05:46:57 +00006058
Victor Stinner8c62be82010-05-06 00:08:46 +00006059 free_string_array(argvlist, argc);
Guido van Rossuma1065681999-01-25 23:20:23 +00006060
Victor Stinner8c62be82010-05-06 00:08:46 +00006061 if (spawnval == -1)
6062 return posix_error();
6063 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01006064 return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00006065}
6066
Larry Hastings2f936352014-08-05 14:04:04 +10006067/*[clinic input]
6068os.spawnve
6069
6070 mode: int
6071 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07006072 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10006073 Path of executable file.
6074 argv: object
6075 Tuple or list of strings.
6076 env: object
6077 Dictionary of strings mapping to strings.
6078 /
6079
6080Execute the program specified by path in a new process.
6081[clinic start generated code]*/
6082
Larry Hastings2f936352014-08-05 14:04:04 +10006083static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07006084os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006085 PyObject *env)
Steve Dowercc16be82016-09-08 10:35:16 -07006086/*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006087{
Steve Dowercc16be82016-09-08 10:35:16 -07006088 EXECV_CHAR **argvlist;
6089 EXECV_CHAR **envlist;
Victor Stinner8c62be82010-05-06 00:08:46 +00006090 PyObject *res = NULL;
Antoine Pitrou22e41552010-08-15 18:07:50 +00006091 Py_ssize_t argc, i, envc;
Benjamin Petersonca470632016-09-06 13:47:26 -07006092 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00006093 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006094 Py_ssize_t lastarg = 0;
Guido van Rossuma1065681999-01-25 23:20:23 +00006095
Victor Stinner8c62be82010-05-06 00:08:46 +00006096 /* spawnve has four arguments: (mode, path, argv, env), where
6097 argv is a list or tuple of strings and env is a dictionary
6098 like posix.environ. */
Guido van Rossuma1065681999-01-25 23:20:23 +00006099
Victor Stinner8c62be82010-05-06 00:08:46 +00006100 if (PyList_Check(argv)) {
6101 argc = PyList_Size(argv);
6102 getitem = PyList_GetItem;
6103 }
6104 else if (PyTuple_Check(argv)) {
6105 argc = PyTuple_Size(argv);
6106 getitem = PyTuple_GetItem;
6107 }
6108 else {
6109 PyErr_SetString(PyExc_TypeError,
6110 "spawnve() arg 2 must be a tuple or list");
6111 goto fail_0;
6112 }
Steve Dower859fd7b2016-11-19 18:53:19 -08006113 if (argc == 0) {
6114 PyErr_SetString(PyExc_ValueError,
6115 "spawnve() arg 2 cannot be empty");
6116 goto fail_0;
6117 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006118 if (!PyMapping_Check(env)) {
6119 PyErr_SetString(PyExc_TypeError,
6120 "spawnve() arg 3 must be a mapping object");
6121 goto fail_0;
6122 }
Guido van Rossuma1065681999-01-25 23:20:23 +00006123
Steve Dowercc16be82016-09-08 10:35:16 -07006124 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00006125 if (argvlist == NULL) {
6126 PyErr_NoMemory();
6127 goto fail_0;
6128 }
6129 for (i = 0; i < argc; i++) {
6130 if (!fsconvert_strdup((*getitem)(argv, i),
6131 &argvlist[i]))
6132 {
6133 lastarg = i;
6134 goto fail_1;
6135 }
Steve Dowerbce26262016-11-19 19:17:26 -08006136 if (i == 0 && !argvlist[0][0]) {
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006137 lastarg = i + 1;
Steve Dowerbce26262016-11-19 19:17:26 -08006138 PyErr_SetString(
6139 PyExc_ValueError,
6140 "spawnv() arg 2 first element cannot be empty");
6141 goto fail_1;
6142 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006143 }
6144 lastarg = argc;
6145 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00006146
Victor Stinner8c62be82010-05-06 00:08:46 +00006147 envlist = parse_envlist(env, &envc);
6148 if (envlist == NULL)
6149 goto fail_1;
Guido van Rossuma1065681999-01-25 23:20:23 +00006150
pxinwrf2d7ac72019-05-21 18:46:37 +08006151#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00006152 if (mode == _OLD_P_OVERLAY)
6153 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08006154#endif
Tim Peters25059d32001-12-07 20:35:43 +00006155
Saiyang Gou7514f4f2020-02-12 23:47:42 -08006156 if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv, env) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -08006157 goto fail_2;
6158 }
6159
Victor Stinner8c62be82010-05-06 00:08:46 +00006160 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07006161 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07006162#ifdef HAVE_WSPAWNV
6163 spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08006164#elif defined(HAVE_RTPSPAWN)
6165 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
6166 (const char **)envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07006167#else
6168 spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
6169#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07006170 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00006171 Py_END_ALLOW_THREADS
Tim Peters25059d32001-12-07 20:35:43 +00006172
Victor Stinner8c62be82010-05-06 00:08:46 +00006173 if (spawnval == -1)
6174 (void) posix_error();
6175 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01006176 res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00006177
Saiyang Gou95f60012020-02-04 16:15:00 -08006178 fail_2:
Victor Stinner8c62be82010-05-06 00:08:46 +00006179 while (--envc >= 0)
6180 PyMem_DEL(envlist[envc]);
6181 PyMem_DEL(envlist);
Guido van Rossum0847c5c2002-12-13 18:36:22 +00006182 fail_1:
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006183 free_string_array(argvlist, lastarg);
Martin v. Löwis114619e2002-10-07 06:44:21 +00006184 fail_0:
Victor Stinner8c62be82010-05-06 00:08:46 +00006185 return res;
Guido van Rossuma1065681999-01-25 23:20:23 +00006186}
Andrew MacIntyre69e18c92004-04-04 07:11:43 +00006187
Guido van Rossuma1065681999-01-25 23:20:23 +00006188#endif /* HAVE_SPAWNV */
6189
6190
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006191#ifdef HAVE_FORK
Gregory P. Smith163468a2017-05-29 10:03:41 -07006192
6193/* Helper function to validate arguments.
6194 Returns 0 on success. non-zero on failure with a TypeError raised.
6195 If obj is non-NULL it must be callable. */
6196static int
6197check_null_or_callable(PyObject *obj, const char* obj_name)
6198{
6199 if (obj && !PyCallable_Check(obj)) {
6200 PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
Eddie Elizondob3966632019-11-05 07:16:14 -08006201 obj_name, _PyType_Name(Py_TYPE(obj)));
Gregory P. Smith163468a2017-05-29 10:03:41 -07006202 return -1;
6203 }
6204 return 0;
6205}
6206
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006207/*[clinic input]
6208os.register_at_fork
6209
Gregory P. Smith163468a2017-05-29 10:03:41 -07006210 *
6211 before: object=NULL
6212 A callable to be called in the parent before the fork() syscall.
6213 after_in_child: object=NULL
6214 A callable to be called in the child after fork().
6215 after_in_parent: object=NULL
6216 A callable to be called in the parent after fork().
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006217
Gregory P. Smith163468a2017-05-29 10:03:41 -07006218Register callables to be called when forking a new process.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006219
Gregory P. Smith163468a2017-05-29 10:03:41 -07006220'before' callbacks are called in reverse order.
6221'after_in_child' and 'after_in_parent' callbacks are called in order.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006222
6223[clinic start generated code]*/
6224
6225static PyObject *
Gregory P. Smith163468a2017-05-29 10:03:41 -07006226os_register_at_fork_impl(PyObject *module, PyObject *before,
6227 PyObject *after_in_child, PyObject *after_in_parent)
6228/*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006229{
6230 PyInterpreterState *interp;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006231
Gregory P. Smith163468a2017-05-29 10:03:41 -07006232 if (!before && !after_in_child && !after_in_parent) {
6233 PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
6234 return NULL;
6235 }
6236 if (check_null_or_callable(before, "before") ||
6237 check_null_or_callable(after_in_child, "after_in_child") ||
6238 check_null_or_callable(after_in_parent, "after_in_parent")) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006239 return NULL;
6240 }
Victor Stinner81a7be32020-04-14 15:14:01 +02006241 interp = _PyInterpreterState_GET();
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006242
Gregory P. Smith163468a2017-05-29 10:03:41 -07006243 if (register_at_forker(&interp->before_forkers, before)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006244 return NULL;
6245 }
Gregory P. Smith163468a2017-05-29 10:03:41 -07006246 if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006247 return NULL;
Gregory P. Smith163468a2017-05-29 10:03:41 -07006248 }
6249 if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
6250 return NULL;
6251 }
6252 Py_RETURN_NONE;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006253}
6254#endif /* HAVE_FORK */
6255
6256
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006257#ifdef HAVE_FORK1
Larry Hastings2f936352014-08-05 14:04:04 +10006258/*[clinic input]
6259os.fork1
6260
6261Fork a child process with a single multiplexed (i.e., not bound) thread.
6262
6263Return 0 to child process and PID of child to parent process.
6264[clinic start generated code]*/
6265
Larry Hastings2f936352014-08-05 14:04:04 +10006266static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006267os_fork1_impl(PyObject *module)
6268/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006269{
Victor Stinner8c62be82010-05-06 00:08:46 +00006270 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006271
Victor Stinner81a7be32020-04-14 15:14:01 +02006272 if (_PyInterpreterState_GET() != PyInterpreterState_Main()) {
Eric Snow59032962018-09-14 14:17:20 -07006273 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6274 return NULL;
6275 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006276 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006277 pid = fork1();
6278 if (pid == 0) {
6279 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006280 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006281 } else {
6282 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006283 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006284 }
6285 if (pid == -1)
6286 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006287 return PyLong_FromPid(pid);
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006288}
Larry Hastings2f936352014-08-05 14:04:04 +10006289#endif /* HAVE_FORK1 */
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006290
6291
Guido van Rossumad0ee831995-03-01 10:34:45 +00006292#ifdef HAVE_FORK
Larry Hastings2f936352014-08-05 14:04:04 +10006293/*[clinic input]
6294os.fork
6295
6296Fork a child process.
6297
6298Return 0 to child process and PID of child to parent process.
6299[clinic start generated code]*/
6300
Larry Hastings2f936352014-08-05 14:04:04 +10006301static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006302os_fork_impl(PyObject *module)
6303/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006304{
Victor Stinner8c62be82010-05-06 00:08:46 +00006305 pid_t pid;
Victor Stinner252346a2020-05-01 11:33:44 +02006306 PyInterpreterState *interp = _PyInterpreterState_GET();
6307 if (interp->config._isolated_interpreter) {
6308 PyErr_SetString(PyExc_RuntimeError,
6309 "fork not supported for isolated subinterpreters");
Eric Snow59032962018-09-14 14:17:20 -07006310 return NULL;
6311 }
Saiyang Gou7514f4f2020-02-12 23:47:42 -08006312 if (PySys_Audit("os.fork", NULL) < 0) {
6313 return NULL;
6314 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006315 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006316 pid = fork();
6317 if (pid == 0) {
6318 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006319 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006320 } else {
6321 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006322 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006323 }
6324 if (pid == -1)
6325 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006326 return PyLong_FromPid(pid);
Guido van Rossum85e3b011991-06-03 12:42:10 +00006327}
Larry Hastings2f936352014-08-05 14:04:04 +10006328#endif /* HAVE_FORK */
6329
Guido van Rossum85e3b011991-06-03 12:42:10 +00006330
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006331#ifdef HAVE_SCHED_H
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006332#ifdef HAVE_SCHED_GET_PRIORITY_MAX
Larry Hastings2f936352014-08-05 14:04:04 +10006333/*[clinic input]
6334os.sched_get_priority_max
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006335
Larry Hastings2f936352014-08-05 14:04:04 +10006336 policy: int
6337
6338Get the maximum scheduling priority for policy.
6339[clinic start generated code]*/
6340
Larry Hastings2f936352014-08-05 14:04:04 +10006341static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006342os_sched_get_priority_max_impl(PyObject *module, int policy)
6343/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006344{
6345 int max;
6346
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006347 max = sched_get_priority_max(policy);
6348 if (max < 0)
6349 return posix_error();
6350 return PyLong_FromLong(max);
6351}
6352
Larry Hastings2f936352014-08-05 14:04:04 +10006353
6354/*[clinic input]
6355os.sched_get_priority_min
6356
6357 policy: int
6358
6359Get the minimum scheduling priority for policy.
6360[clinic start generated code]*/
6361
Larry Hastings2f936352014-08-05 14:04:04 +10006362static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006363os_sched_get_priority_min_impl(PyObject *module, int policy)
6364/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006365{
6366 int min = sched_get_priority_min(policy);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006367 if (min < 0)
6368 return posix_error();
6369 return PyLong_FromLong(min);
6370}
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006371#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
6372
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006373
Larry Hastings2f936352014-08-05 14:04:04 +10006374#ifdef HAVE_SCHED_SETSCHEDULER
6375/*[clinic input]
6376os.sched_getscheduler
6377 pid: pid_t
6378 /
6379
Min ho Kimc4cacc82019-07-31 08:16:13 +10006380Get the scheduling policy for the process identified by pid.
Larry Hastings2f936352014-08-05 14:04:04 +10006381
6382Passing 0 for pid returns the scheduling policy for the calling process.
6383[clinic start generated code]*/
6384
Larry Hastings2f936352014-08-05 14:04:04 +10006385static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006386os_sched_getscheduler_impl(PyObject *module, pid_t pid)
Min ho Kimc4cacc82019-07-31 08:16:13 +10006387/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=8d99dac505485ac8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006388{
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006389 int policy;
6390
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006391 policy = sched_getscheduler(pid);
6392 if (policy < 0)
6393 return posix_error();
6394 return PyLong_FromLong(policy);
6395}
Larry Hastings2f936352014-08-05 14:04:04 +10006396#endif /* HAVE_SCHED_SETSCHEDULER */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006397
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006398
William Orr81574b82018-10-01 22:19:56 -07006399#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Larry Hastings2f936352014-08-05 14:04:04 +10006400/*[clinic input]
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006401class os.sched_param "PyObject *" "SchedParamType"
Larry Hastings2f936352014-08-05 14:04:04 +10006402
6403@classmethod
6404os.sched_param.__new__
6405
6406 sched_priority: object
6407 A scheduling parameter.
6408
Eddie Elizondob3966632019-11-05 07:16:14 -08006409Currently has only one field: sched_priority
Larry Hastings2f936352014-08-05 14:04:04 +10006410[clinic start generated code]*/
6411
Larry Hastings2f936352014-08-05 14:04:04 +10006412static PyObject *
6413os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
Eddie Elizondob3966632019-11-05 07:16:14 -08006414/*[clinic end generated code: output=48f4067d60f48c13 input=eb42909a2c0e3e6c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006415{
6416 PyObject *res;
6417
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006418 res = PyStructSequence_New(type);
6419 if (!res)
6420 return NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10006421 Py_INCREF(sched_priority);
6422 PyStructSequence_SET_ITEM(res, 0, sched_priority);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006423 return res;
6424}
6425
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03006426PyDoc_VAR(os_sched_param__doc__);
6427
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006428static PyStructSequence_Field sched_param_fields[] = {
6429 {"sched_priority", "the scheduling priority"},
6430 {0}
6431};
6432
6433static PyStructSequence_Desc sched_param_desc = {
6434 "sched_param", /* name */
Larry Hastings2f936352014-08-05 14:04:04 +10006435 os_sched_param__doc__, /* doc */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006436 sched_param_fields,
6437 1
6438};
6439
6440static int
Victor Stinner1c2fa782020-05-10 11:05:29 +02006441convert_sched_param(PyObject *module, PyObject *param, struct sched_param *res)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006442{
6443 long priority;
6444
Victor Stinner1c2fa782020-05-10 11:05:29 +02006445 if (!Py_IS_TYPE(param, (PyTypeObject *)get_posix_state(module)->SchedParamType)) {
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006446 PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
6447 return 0;
6448 }
6449 priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
6450 if (priority == -1 && PyErr_Occurred())
6451 return 0;
6452 if (priority > INT_MAX || priority < INT_MIN) {
6453 PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
6454 return 0;
6455 }
6456 res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
6457 return 1;
6458}
William Orr81574b82018-10-01 22:19:56 -07006459#endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006460
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006461
6462#ifdef HAVE_SCHED_SETSCHEDULER
Larry Hastings2f936352014-08-05 14:04:04 +10006463/*[clinic input]
6464os.sched_setscheduler
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006465
Larry Hastings2f936352014-08-05 14:04:04 +10006466 pid: pid_t
6467 policy: int
Victor Stinner1c2fa782020-05-10 11:05:29 +02006468 param as param_obj: object
Larry Hastings2f936352014-08-05 14:04:04 +10006469 /
6470
6471Set the scheduling policy for the process identified by pid.
6472
6473If pid is 0, the calling process is changed.
6474param is an instance of sched_param.
6475[clinic start generated code]*/
6476
Larry Hastings2f936352014-08-05 14:04:04 +10006477static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006478os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
Victor Stinner1c2fa782020-05-10 11:05:29 +02006479 PyObject *param_obj)
6480/*[clinic end generated code: output=cde27faa55dc993e input=73013d731bd8fbe9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006481{
Victor Stinner1c2fa782020-05-10 11:05:29 +02006482 struct sched_param param;
6483 if (!convert_sched_param(module, param_obj, &param)) {
6484 return NULL;
6485 }
6486
Jesus Cea9c822272011-09-10 01:40:52 +02006487 /*
Jesus Cea54b01492011-09-10 01:53:19 +02006488 ** sched_setscheduler() returns 0 in Linux, but the previous
6489 ** scheduling policy under Solaris/Illumos, and others.
6490 ** On error, -1 is returned in all Operating Systems.
Jesus Cea9c822272011-09-10 01:40:52 +02006491 */
Victor Stinner1c2fa782020-05-10 11:05:29 +02006492 if (sched_setscheduler(pid, policy, &param) == -1)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006493 return posix_error();
6494 Py_RETURN_NONE;
6495}
Larry Hastings2f936352014-08-05 14:04:04 +10006496#endif /* HAVE_SCHED_SETSCHEDULER*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006497
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006498
6499#ifdef HAVE_SCHED_SETPARAM
Larry Hastings2f936352014-08-05 14:04:04 +10006500/*[clinic input]
6501os.sched_getparam
6502 pid: pid_t
6503 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006504
Larry Hastings2f936352014-08-05 14:04:04 +10006505Returns scheduling parameters for the process identified by pid.
6506
6507If pid is 0, returns parameters for the calling process.
6508Return value is an instance of sched_param.
6509[clinic start generated code]*/
6510
Larry Hastings2f936352014-08-05 14:04:04 +10006511static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006512os_sched_getparam_impl(PyObject *module, pid_t pid)
6513/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006514{
6515 struct sched_param param;
6516 PyObject *result;
6517 PyObject *priority;
6518
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006519 if (sched_getparam(pid, &param))
6520 return posix_error();
Victor Stinner1c2fa782020-05-10 11:05:29 +02006521 PyObject *SchedParamType = get_posix_state(module)->SchedParamType;
Eddie Elizondob3966632019-11-05 07:16:14 -08006522 result = PyStructSequence_New((PyTypeObject *)SchedParamType);
Larry Hastings2f936352014-08-05 14:04:04 +10006523 if (!result)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006524 return NULL;
6525 priority = PyLong_FromLong(param.sched_priority);
6526 if (!priority) {
Larry Hastings2f936352014-08-05 14:04:04 +10006527 Py_DECREF(result);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006528 return NULL;
6529 }
Larry Hastings2f936352014-08-05 14:04:04 +10006530 PyStructSequence_SET_ITEM(result, 0, priority);
6531 return result;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006532}
6533
Larry Hastings2f936352014-08-05 14:04:04 +10006534
6535/*[clinic input]
6536os.sched_setparam
6537 pid: pid_t
Victor Stinner1c2fa782020-05-10 11:05:29 +02006538 param as param_obj: object
Larry Hastings2f936352014-08-05 14:04:04 +10006539 /
6540
6541Set scheduling parameters for the process identified by pid.
6542
6543If pid is 0, sets parameters for the calling process.
6544param should be an instance of sched_param.
6545[clinic start generated code]*/
6546
Larry Hastings2f936352014-08-05 14:04:04 +10006547static PyObject *
Victor Stinner1c2fa782020-05-10 11:05:29 +02006548os_sched_setparam_impl(PyObject *module, pid_t pid, PyObject *param_obj)
6549/*[clinic end generated code: output=f19fe020a53741c1 input=27b98337c8b2dcc7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006550{
Victor Stinner1c2fa782020-05-10 11:05:29 +02006551 struct sched_param param;
6552 if (!convert_sched_param(module, param_obj, &param)) {
6553 return NULL;
6554 }
6555
6556 if (sched_setparam(pid, &param))
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006557 return posix_error();
6558 Py_RETURN_NONE;
6559}
Larry Hastings2f936352014-08-05 14:04:04 +10006560#endif /* HAVE_SCHED_SETPARAM */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006561
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006562
6563#ifdef HAVE_SCHED_RR_GET_INTERVAL
Larry Hastings2f936352014-08-05 14:04:04 +10006564/*[clinic input]
6565os.sched_rr_get_interval -> double
6566 pid: pid_t
6567 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006568
Larry Hastings2f936352014-08-05 14:04:04 +10006569Return the round-robin quantum for the process identified by pid, in seconds.
6570
6571Value returned is a float.
6572[clinic start generated code]*/
6573
Larry Hastings2f936352014-08-05 14:04:04 +10006574static double
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006575os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
6576/*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006577{
6578 struct timespec interval;
6579 if (sched_rr_get_interval(pid, &interval)) {
6580 posix_error();
6581 return -1.0;
6582 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006583#ifdef _Py_MEMORY_SANITIZER
6584 __msan_unpoison(&interval, sizeof(interval));
6585#endif
Larry Hastings2f936352014-08-05 14:04:04 +10006586 return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
6587}
6588#endif /* HAVE_SCHED_RR_GET_INTERVAL */
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006589
Larry Hastings2f936352014-08-05 14:04:04 +10006590
6591/*[clinic input]
6592os.sched_yield
6593
6594Voluntarily relinquish the CPU.
6595[clinic start generated code]*/
6596
Larry Hastings2f936352014-08-05 14:04:04 +10006597static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006598os_sched_yield_impl(PyObject *module)
6599/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006600{
6601 if (sched_yield())
6602 return posix_error();
6603 Py_RETURN_NONE;
6604}
6605
Benjamin Peterson2740af82011-08-02 17:41:34 -05006606#ifdef HAVE_SCHED_SETAFFINITY
Antoine Pitrou84869872012-08-04 16:16:35 +02006607/* The minimum number of CPUs allocated in a cpu_set_t */
6608static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006609
Larry Hastings2f936352014-08-05 14:04:04 +10006610/*[clinic input]
6611os.sched_setaffinity
6612 pid: pid_t
6613 mask : object
6614 /
6615
6616Set the CPU affinity of the process identified by pid to mask.
6617
6618mask should be an iterable of integers identifying CPUs.
6619[clinic start generated code]*/
6620
Larry Hastings2f936352014-08-05 14:04:04 +10006621static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006622os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
6623/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006624{
Antoine Pitrou84869872012-08-04 16:16:35 +02006625 int ncpus;
6626 size_t setsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006627 cpu_set_t *cpu_set = NULL;
6628 PyObject *iterator = NULL, *item;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006629
Larry Hastings2f936352014-08-05 14:04:04 +10006630 iterator = PyObject_GetIter(mask);
Antoine Pitrou84869872012-08-04 16:16:35 +02006631 if (iterator == NULL)
6632 return NULL;
6633
6634 ncpus = NCPUS_START;
6635 setsize = CPU_ALLOC_SIZE(ncpus);
Larry Hastings2f936352014-08-05 14:04:04 +10006636 cpu_set = CPU_ALLOC(ncpus);
6637 if (cpu_set == NULL) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006638 PyErr_NoMemory();
6639 goto error;
6640 }
Larry Hastings2f936352014-08-05 14:04:04 +10006641 CPU_ZERO_S(setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006642
6643 while ((item = PyIter_Next(iterator))) {
6644 long cpu;
6645 if (!PyLong_Check(item)) {
6646 PyErr_Format(PyExc_TypeError,
6647 "expected an iterator of ints, "
6648 "but iterator yielded %R",
6649 Py_TYPE(item));
6650 Py_DECREF(item);
6651 goto error;
6652 }
6653 cpu = PyLong_AsLong(item);
6654 Py_DECREF(item);
6655 if (cpu < 0) {
6656 if (!PyErr_Occurred())
6657 PyErr_SetString(PyExc_ValueError, "negative CPU number");
6658 goto error;
6659 }
6660 if (cpu > INT_MAX - 1) {
6661 PyErr_SetString(PyExc_OverflowError, "CPU number too large");
6662 goto error;
6663 }
6664 if (cpu >= ncpus) {
6665 /* Grow CPU mask to fit the CPU number */
6666 int newncpus = ncpus;
6667 cpu_set_t *newmask;
6668 size_t newsetsize;
6669 while (newncpus <= cpu) {
6670 if (newncpus > INT_MAX / 2)
6671 newncpus = cpu + 1;
6672 else
6673 newncpus = newncpus * 2;
6674 }
6675 newmask = CPU_ALLOC(newncpus);
6676 if (newmask == NULL) {
6677 PyErr_NoMemory();
6678 goto error;
6679 }
6680 newsetsize = CPU_ALLOC_SIZE(newncpus);
6681 CPU_ZERO_S(newsetsize, newmask);
Larry Hastings2f936352014-08-05 14:04:04 +10006682 memcpy(newmask, cpu_set, setsize);
6683 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006684 setsize = newsetsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006685 cpu_set = newmask;
Antoine Pitrou84869872012-08-04 16:16:35 +02006686 ncpus = newncpus;
6687 }
Larry Hastings2f936352014-08-05 14:04:04 +10006688 CPU_SET_S(cpu, setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006689 }
Brandt Bucher45a30af2019-06-27 09:10:57 -07006690 if (PyErr_Occurred()) {
6691 goto error;
6692 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006693 Py_CLEAR(iterator);
6694
Larry Hastings2f936352014-08-05 14:04:04 +10006695 if (sched_setaffinity(pid, setsize, cpu_set)) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006696 posix_error();
6697 goto error;
6698 }
Larry Hastings2f936352014-08-05 14:04:04 +10006699 CPU_FREE(cpu_set);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006700 Py_RETURN_NONE;
Antoine Pitrou84869872012-08-04 16:16:35 +02006701
6702error:
Larry Hastings2f936352014-08-05 14:04:04 +10006703 if (cpu_set)
6704 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006705 Py_XDECREF(iterator);
6706 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006707}
6708
Larry Hastings2f936352014-08-05 14:04:04 +10006709
6710/*[clinic input]
6711os.sched_getaffinity
6712 pid: pid_t
6713 /
6714
Charles-François Natalidc87e4b2015-07-13 21:01:39 +01006715Return the affinity of the process identified by pid (or the current process if zero).
Larry Hastings2f936352014-08-05 14:04:04 +10006716
6717The affinity is returned as a set of CPU identifiers.
6718[clinic start generated code]*/
6719
Larry Hastings2f936352014-08-05 14:04:04 +10006720static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006721os_sched_getaffinity_impl(PyObject *module, pid_t pid)
Serhiy Storchaka2954f832016-07-07 18:20:03 +03006722/*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006723{
Antoine Pitrou84869872012-08-04 16:16:35 +02006724 int cpu, ncpus, count;
6725 size_t setsize;
6726 cpu_set_t *mask = NULL;
6727 PyObject *res = NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006728
Antoine Pitrou84869872012-08-04 16:16:35 +02006729 ncpus = NCPUS_START;
6730 while (1) {
6731 setsize = CPU_ALLOC_SIZE(ncpus);
6732 mask = CPU_ALLOC(ncpus);
6733 if (mask == NULL)
6734 return PyErr_NoMemory();
6735 if (sched_getaffinity(pid, setsize, mask) == 0)
6736 break;
6737 CPU_FREE(mask);
6738 if (errno != EINVAL)
6739 return posix_error();
6740 if (ncpus > INT_MAX / 2) {
6741 PyErr_SetString(PyExc_OverflowError, "could not allocate "
6742 "a large enough CPU set");
6743 return NULL;
6744 }
6745 ncpus = ncpus * 2;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006746 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006747
6748 res = PySet_New(NULL);
6749 if (res == NULL)
6750 goto error;
6751 for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
6752 if (CPU_ISSET_S(cpu, setsize, mask)) {
6753 PyObject *cpu_num = PyLong_FromLong(cpu);
6754 --count;
6755 if (cpu_num == NULL)
6756 goto error;
6757 if (PySet_Add(res, cpu_num)) {
6758 Py_DECREF(cpu_num);
6759 goto error;
6760 }
6761 Py_DECREF(cpu_num);
6762 }
6763 }
6764 CPU_FREE(mask);
6765 return res;
6766
6767error:
6768 if (mask)
6769 CPU_FREE(mask);
6770 Py_XDECREF(res);
6771 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006772}
6773
Benjamin Peterson2740af82011-08-02 17:41:34 -05006774#endif /* HAVE_SCHED_SETAFFINITY */
6775
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006776#endif /* HAVE_SCHED_H */
6777
Larry Hastings2f936352014-08-05 14:04:04 +10006778
Neal Norwitzb59798b2003-03-21 01:43:31 +00006779/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
Neal Norwitz2deaddb2003-03-21 03:08:31 +00006780/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
6781#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
Neal Norwitzb59798b2003-03-21 01:43:31 +00006782#define DEV_PTY_FILE "/dev/ptc"
6783#define HAVE_DEV_PTMX
6784#else
6785#define DEV_PTY_FILE "/dev/ptmx"
6786#endif
6787
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006788#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
Fred Drake8cef4cf2000-06-28 16:40:38 +00006789#ifdef HAVE_PTY_H
6790#include <pty.h>
6791#else
6792#ifdef HAVE_LIBUTIL_H
6793#include <libutil.h>
Ronald Oussoren755740f2010-02-07 19:56:39 +00006794#else
6795#ifdef HAVE_UTIL_H
6796#include <util.h>
6797#endif /* HAVE_UTIL_H */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006798#endif /* HAVE_LIBUTIL_H */
6799#endif /* HAVE_PTY_H */
Martin v. Löwis14e73b12003-01-01 09:51:12 +00006800#ifdef HAVE_STROPTS_H
6801#include <stropts.h>
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006802#endif
ngie-eign7745ec42018-02-14 11:54:28 -08006803#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006804
Larry Hastings2f936352014-08-05 14:04:04 +10006805
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006806#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
Larry Hastings2f936352014-08-05 14:04:04 +10006807/*[clinic input]
6808os.openpty
6809
6810Open a pseudo-terminal.
6811
6812Return a tuple of (master_fd, slave_fd) containing open file descriptors
6813for both the master and slave ends.
6814[clinic start generated code]*/
6815
Larry Hastings2f936352014-08-05 14:04:04 +10006816static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006817os_openpty_impl(PyObject *module)
6818/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006819{
Victor Stinnerdaf45552013-08-28 00:53:59 +02006820 int master_fd = -1, slave_fd = -1;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006821#ifndef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006822 char * slave_name;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006823#endif
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006824#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006825 PyOS_sighandler_t sig_saved;
Jakub Kulík6f9bc722018-12-31 03:16:40 +01006826#if defined(__sun) && defined(__SVR4)
Victor Stinner8c62be82010-05-06 00:08:46 +00006827 extern char *ptsname(int fildes);
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006828#endif
6829#endif
Thomas Wouters70c21a12000-07-14 14:28:33 +00006830
Thomas Wouters70c21a12000-07-14 14:28:33 +00006831#ifdef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006832 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006833 goto posix_error;
6834
6835 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6836 goto error;
6837 if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
6838 goto error;
6839
Neal Norwitzb59798b2003-03-21 01:43:31 +00006840#elif defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006841 slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
6842 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006843 goto posix_error;
6844 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6845 goto error;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006846
Victor Stinnerdaf45552013-08-28 00:53:59 +02006847 slave_fd = _Py_open(slave_name, O_RDWR);
Victor Stinner8c62be82010-05-06 00:08:46 +00006848 if (slave_fd < 0)
Victor Stinnera555cfc2015-03-18 00:22:14 +01006849 goto error;
Victor Stinnerdaf45552013-08-28 00:53:59 +02006850
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006851#else
Victor Stinner000de532013-11-25 23:19:58 +01006852 master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
Victor Stinner8c62be82010-05-06 00:08:46 +00006853 if (master_fd < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006854 goto posix_error;
6855
Victor Stinner8c62be82010-05-06 00:08:46 +00006856 sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006857
Victor Stinner8c62be82010-05-06 00:08:46 +00006858 /* change permission of slave */
6859 if (grantpt(master_fd) < 0) {
6860 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006861 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006862 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006863
Victor Stinner8c62be82010-05-06 00:08:46 +00006864 /* unlock slave */
6865 if (unlockpt(master_fd) < 0) {
6866 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006867 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006868 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006869
Victor Stinner8c62be82010-05-06 00:08:46 +00006870 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006871
Victor Stinner8c62be82010-05-06 00:08:46 +00006872 slave_name = ptsname(master_fd); /* get name of slave */
6873 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006874 goto posix_error;
6875
6876 slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
Victor Stinnera555cfc2015-03-18 00:22:14 +01006877 if (slave_fd == -1)
6878 goto error;
Victor Stinner000de532013-11-25 23:19:58 +01006879
6880 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6881 goto posix_error;
6882
Stefan Krahfb7c8ae2016-04-26 17:04:18 +02006883#if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
Victor Stinner8c62be82010-05-06 00:08:46 +00006884 ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
6885 ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
Neal Norwitz6700e472002-12-31 16:16:07 +00006886#ifndef __hpux
Victor Stinner8c62be82010-05-06 00:08:46 +00006887 ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
Neal Norwitz6700e472002-12-31 16:16:07 +00006888#endif /* __hpux */
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006889#endif /* HAVE_CYGWIN */
Thomas Wouters1e0c2f42000-07-24 16:06:23 +00006890#endif /* HAVE_OPENPTY */
Thomas Wouters70c21a12000-07-14 14:28:33 +00006891
Victor Stinner8c62be82010-05-06 00:08:46 +00006892 return Py_BuildValue("(ii)", master_fd, slave_fd);
Thomas Wouters70c21a12000-07-14 14:28:33 +00006893
Victor Stinnerdaf45552013-08-28 00:53:59 +02006894posix_error:
6895 posix_error();
6896error:
6897 if (master_fd != -1)
6898 close(master_fd);
6899 if (slave_fd != -1)
6900 close(slave_fd);
6901 return NULL;
Fred Drake8cef4cf2000-06-28 16:40:38 +00006902}
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006903#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006904
Larry Hastings2f936352014-08-05 14:04:04 +10006905
Fred Drake8cef4cf2000-06-28 16:40:38 +00006906#ifdef HAVE_FORKPTY
Larry Hastings2f936352014-08-05 14:04:04 +10006907/*[clinic input]
6908os.forkpty
6909
6910Fork a new process with a new pseudo-terminal as controlling tty.
6911
6912Returns a tuple of (pid, master_fd).
6913Like fork(), return pid of 0 to the child process,
6914and pid of child to the parent process.
6915To both, return fd of newly opened pseudo-terminal.
6916[clinic start generated code]*/
6917
Larry Hastings2f936352014-08-05 14:04:04 +10006918static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006919os_forkpty_impl(PyObject *module)
6920/*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006921{
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006922 int master_fd = -1;
Victor Stinner8c62be82010-05-06 00:08:46 +00006923 pid_t pid;
Tim Peters5aa91602002-01-30 05:46:57 +00006924
Victor Stinner81a7be32020-04-14 15:14:01 +02006925 if (_PyInterpreterState_GET() != PyInterpreterState_Main()) {
Eric Snow59032962018-09-14 14:17:20 -07006926 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6927 return NULL;
6928 }
Saiyang Gou7514f4f2020-02-12 23:47:42 -08006929 if (PySys_Audit("os.forkpty", NULL) < 0) {
6930 return NULL;
6931 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006932 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006933 pid = forkpty(&master_fd, NULL, NULL, NULL);
6934 if (pid == 0) {
6935 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006936 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006937 } else {
6938 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006939 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006940 }
6941 if (pid == -1)
6942 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006943 return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
Fred Drake8cef4cf2000-06-28 16:40:38 +00006944}
Larry Hastings2f936352014-08-05 14:04:04 +10006945#endif /* HAVE_FORKPTY */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006946
Ross Lagerwall7807c352011-03-17 20:20:30 +02006947
Guido van Rossumad0ee831995-03-01 10:34:45 +00006948#ifdef HAVE_GETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10006949/*[clinic input]
6950os.getegid
6951
6952Return the current process's effective group id.
6953[clinic start generated code]*/
6954
Larry Hastings2f936352014-08-05 14:04:04 +10006955static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006956os_getegid_impl(PyObject *module)
6957/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006958{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006959 return _PyLong_FromGid(getegid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006960}
Larry Hastings2f936352014-08-05 14:04:04 +10006961#endif /* HAVE_GETEGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006962
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006963
Guido van Rossumad0ee831995-03-01 10:34:45 +00006964#ifdef HAVE_GETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10006965/*[clinic input]
6966os.geteuid
6967
6968Return the current process's effective user id.
6969[clinic start generated code]*/
6970
Larry Hastings2f936352014-08-05 14:04:04 +10006971static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006972os_geteuid_impl(PyObject *module)
6973/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006974{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006975 return _PyLong_FromUid(geteuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006976}
Larry Hastings2f936352014-08-05 14:04:04 +10006977#endif /* HAVE_GETEUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006978
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006979
Guido van Rossumad0ee831995-03-01 10:34:45 +00006980#ifdef HAVE_GETGID
Larry Hastings2f936352014-08-05 14:04:04 +10006981/*[clinic input]
6982os.getgid
6983
6984Return the current process's group id.
6985[clinic start generated code]*/
6986
Larry Hastings2f936352014-08-05 14:04:04 +10006987static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006988os_getgid_impl(PyObject *module)
6989/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006990{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006991 return _PyLong_FromGid(getgid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006992}
Larry Hastings2f936352014-08-05 14:04:04 +10006993#endif /* HAVE_GETGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006994
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006995
Berker Peksag39404992016-09-15 20:45:16 +03006996#ifdef HAVE_GETPID
Larry Hastings2f936352014-08-05 14:04:04 +10006997/*[clinic input]
6998os.getpid
6999
7000Return the current process id.
7001[clinic start generated code]*/
7002
Larry Hastings2f936352014-08-05 14:04:04 +10007003static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007004os_getpid_impl(PyObject *module)
7005/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00007006{
Victor Stinner8c62be82010-05-06 00:08:46 +00007007 return PyLong_FromPid(getpid());
Guido van Rossum85e3b011991-06-03 12:42:10 +00007008}
Berker Peksag39404992016-09-15 20:45:16 +03007009#endif /* HAVE_GETPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007010
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07007011#ifdef NGROUPS_MAX
7012#define MAX_GROUPS NGROUPS_MAX
7013#else
7014 /* defined to be 16 on Solaris7, so this should be a small number */
7015#define MAX_GROUPS 64
7016#endif
7017
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007018#ifdef HAVE_GETGROUPLIST
Larry Hastings2f936352014-08-05 14:04:04 +10007019
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007020#ifdef __APPLE__
7021/*[clinic input]
7022os.getgrouplist
7023
7024 user: str
7025 username to lookup
7026 group as basegid: int
7027 base group id of the user
7028 /
7029
7030Returns a list of groups to which a user belongs.
7031[clinic start generated code]*/
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007032
7033static PyObject *
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007034os_getgrouplist_impl(PyObject *module, const char *user, int basegid)
7035/*[clinic end generated code: output=6e734697b8c26de0 input=f8d870374b09a490]*/
7036#else
7037/*[clinic input]
7038os.getgrouplist
7039
7040 user: str
7041 username to lookup
7042 group as basegid: gid_t
7043 base group id of the user
7044 /
7045
7046Returns a list of groups to which a user belongs.
7047[clinic start generated code]*/
7048
7049static PyObject *
7050os_getgrouplist_impl(PyObject *module, const char *user, gid_t basegid)
7051/*[clinic end generated code: output=0ebd7fb70115575b input=cc61d5c20b08958d]*/
7052#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007053{
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007054 int i, ngroups;
7055 PyObject *list;
7056#ifdef __APPLE__
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007057 int *groups;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007058#else
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007059 gid_t *groups;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007060#endif
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07007061
7062 /*
7063 * NGROUPS_MAX is defined by POSIX.1 as the maximum
7064 * number of supplimental groups a users can belong to.
7065 * We have to increment it by one because
7066 * getgrouplist() returns both the supplemental groups
7067 * and the primary group, i.e. all of the groups the
7068 * user belongs to.
7069 */
7070 ngroups = 1 + MAX_GROUPS;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007071
Victor Stinnerf5c7cab2020-03-24 18:22:10 +01007072 while (1) {
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007073#ifdef __APPLE__
Victor Stinner8ec73702020-03-23 20:00:57 +01007074 groups = PyMem_New(int, ngroups);
Victor Stinnerf5c7cab2020-03-24 18:22:10 +01007075#else
7076 groups = PyMem_New(gid_t, ngroups);
7077#endif
Victor Stinner8ec73702020-03-23 20:00:57 +01007078 if (groups == NULL) {
7079 return PyErr_NoMemory();
7080 }
Victor Stinnerf5c7cab2020-03-24 18:22:10 +01007081
7082 int old_ngroups = ngroups;
7083 if (getgrouplist(user, basegid, groups, &ngroups) != -1) {
7084 /* Success */
7085 break;
7086 }
7087
7088 /* getgrouplist() fails if the group list is too small */
7089 PyMem_Free(groups);
7090
7091 if (ngroups > old_ngroups) {
7092 /* If the group list is too small, the glibc implementation of
7093 getgrouplist() sets ngroups to the total number of groups and
7094 returns -1. */
7095 }
7096 else {
7097 /* Double the group list size */
7098 if (ngroups > INT_MAX / 2) {
7099 return PyErr_NoMemory();
7100 }
7101 ngroups *= 2;
7102 }
7103
7104 /* Retry getgrouplist() with a larger group list */
Victor Stinner8ec73702020-03-23 20:00:57 +01007105 }
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007106
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08007107#ifdef _Py_MEMORY_SANITIZER
7108 /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
7109 __msan_unpoison(&ngroups, sizeof(ngroups));
7110 __msan_unpoison(groups, ngroups*sizeof(*groups));
7111#endif
7112
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007113 list = PyList_New(ngroups);
7114 if (list == NULL) {
7115 PyMem_Del(groups);
7116 return NULL;
7117 }
7118
7119 for (i = 0; i < ngroups; i++) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007120#ifdef __APPLE__
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007121 PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007122#else
7123 PyObject *o = _PyLong_FromGid(groups[i]);
7124#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007125 if (o == NULL) {
7126 Py_DECREF(list);
7127 PyMem_Del(groups);
7128 return NULL;
7129 }
7130 PyList_SET_ITEM(list, i, o);
7131 }
7132
7133 PyMem_Del(groups);
7134
7135 return list;
7136}
Larry Hastings2f936352014-08-05 14:04:04 +10007137#endif /* HAVE_GETGROUPLIST */
7138
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007139
Fred Drakec9680921999-12-13 16:37:25 +00007140#ifdef HAVE_GETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007141/*[clinic input]
7142os.getgroups
7143
7144Return list of supplemental group IDs for the process.
7145[clinic start generated code]*/
7146
Larry Hastings2f936352014-08-05 14:04:04 +10007147static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007148os_getgroups_impl(PyObject *module)
7149/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
Fred Drakec9680921999-12-13 16:37:25 +00007150{
7151 PyObject *result = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00007152 gid_t grouplist[MAX_GROUPS];
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007153
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007154 /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007155 * This is a helper variable to store the intermediate result when
7156 * that happens.
7157 *
7158 * To keep the code readable the OSX behaviour is unconditional,
7159 * according to the POSIX spec this should be safe on all unix-y
7160 * systems.
7161 */
7162 gid_t* alt_grouplist = grouplist;
Victor Stinner8c62be82010-05-06 00:08:46 +00007163 int n;
Fred Drakec9680921999-12-13 16:37:25 +00007164
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007165#ifdef __APPLE__
7166 /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
7167 * there are more groups than can fit in grouplist. Therefore, on OS X
7168 * always first call getgroups with length 0 to get the actual number
7169 * of groups.
7170 */
7171 n = getgroups(0, NULL);
7172 if (n < 0) {
7173 return posix_error();
7174 } else if (n <= MAX_GROUPS) {
7175 /* groups will fit in existing array */
7176 alt_grouplist = grouplist;
7177 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02007178 alt_grouplist = PyMem_New(gid_t, n);
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007179 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07007180 return PyErr_NoMemory();
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007181 }
7182 }
7183
7184 n = getgroups(n, alt_grouplist);
7185 if (n == -1) {
7186 if (alt_grouplist != grouplist) {
7187 PyMem_Free(alt_grouplist);
7188 }
7189 return posix_error();
7190 }
7191#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007192 n = getgroups(MAX_GROUPS, grouplist);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007193 if (n < 0) {
7194 if (errno == EINVAL) {
7195 n = getgroups(0, NULL);
7196 if (n == -1) {
7197 return posix_error();
7198 }
7199 if (n == 0) {
7200 /* Avoid malloc(0) */
7201 alt_grouplist = grouplist;
7202 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02007203 alt_grouplist = PyMem_New(gid_t, n);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007204 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07007205 return PyErr_NoMemory();
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007206 }
7207 n = getgroups(n, alt_grouplist);
7208 if (n == -1) {
7209 PyMem_Free(alt_grouplist);
7210 return posix_error();
7211 }
7212 }
7213 } else {
7214 return posix_error();
7215 }
7216 }
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007217#endif
7218
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007219 result = PyList_New(n);
7220 if (result != NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007221 int i;
7222 for (i = 0; i < n; ++i) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007223 PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
Victor Stinner8c62be82010-05-06 00:08:46 +00007224 if (o == NULL) {
Stefan Krah0e803b32010-11-26 16:16:47 +00007225 Py_DECREF(result);
7226 result = NULL;
7227 break;
Fred Drakec9680921999-12-13 16:37:25 +00007228 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007229 PyList_SET_ITEM(result, i, o);
Fred Drakec9680921999-12-13 16:37:25 +00007230 }
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007231 }
7232
7233 if (alt_grouplist != grouplist) {
7234 PyMem_Free(alt_grouplist);
Victor Stinner8c62be82010-05-06 00:08:46 +00007235 }
Neal Norwitze241ce82003-02-17 18:17:05 +00007236
Fred Drakec9680921999-12-13 16:37:25 +00007237 return result;
7238}
Larry Hastings2f936352014-08-05 14:04:04 +10007239#endif /* HAVE_GETGROUPS */
Fred Drakec9680921999-12-13 16:37:25 +00007240
Antoine Pitroub7572f02009-12-02 20:46:48 +00007241#ifdef HAVE_INITGROUPS
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007242#ifdef __APPLE__
7243/*[clinic input]
7244os.initgroups
Antoine Pitroub7572f02009-12-02 20:46:48 +00007245
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007246 username as oname: FSConverter
7247 gid: int
7248 /
7249
7250Initialize the group access list.
7251
7252Call the system initgroups() to initialize the group access list with all of
7253the groups of which the specified username is a member, plus the specified
7254group id.
7255[clinic start generated code]*/
7256
Antoine Pitroub7572f02009-12-02 20:46:48 +00007257static PyObject *
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007258os_initgroups_impl(PyObject *module, PyObject *oname, int gid)
7259/*[clinic end generated code: output=7f074d30a425fd3a input=df3d54331b0af204]*/
7260#else
7261/*[clinic input]
7262os.initgroups
7263
7264 username as oname: FSConverter
7265 gid: gid_t
7266 /
7267
7268Initialize the group access list.
7269
7270Call the system initgroups() to initialize the group access list with all of
7271the groups of which the specified username is a member, plus the specified
7272group id.
7273[clinic start generated code]*/
7274
7275static PyObject *
7276os_initgroups_impl(PyObject *module, PyObject *oname, gid_t gid)
7277/*[clinic end generated code: output=59341244521a9e3f input=0cb91bdc59a4c564]*/
7278#endif
Antoine Pitroub7572f02009-12-02 20:46:48 +00007279{
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007280 const char *username = PyBytes_AS_STRING(oname);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007281
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007282 if (initgroups(username, gid) == -1)
Victor Stinner8c62be82010-05-06 00:08:46 +00007283 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007284
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007285 Py_RETURN_NONE;
Antoine Pitroub7572f02009-12-02 20:46:48 +00007286}
Larry Hastings2f936352014-08-05 14:04:04 +10007287#endif /* HAVE_INITGROUPS */
7288
Antoine Pitroub7572f02009-12-02 20:46:48 +00007289
Martin v. Löwis606edc12002-06-13 21:09:11 +00007290#ifdef HAVE_GETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10007291/*[clinic input]
7292os.getpgid
7293
7294 pid: pid_t
7295
7296Call the system call getpgid(), and return the result.
7297[clinic start generated code]*/
7298
Larry Hastings2f936352014-08-05 14:04:04 +10007299static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007300os_getpgid_impl(PyObject *module, pid_t pid)
7301/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007302{
7303 pid_t pgid = getpgid(pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007304 if (pgid < 0)
7305 return posix_error();
7306 return PyLong_FromPid(pgid);
Martin v. Löwis606edc12002-06-13 21:09:11 +00007307}
7308#endif /* HAVE_GETPGID */
7309
7310
Guido van Rossumb6775db1994-08-01 11:34:53 +00007311#ifdef HAVE_GETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007312/*[clinic input]
7313os.getpgrp
7314
7315Return the current process group id.
7316[clinic start generated code]*/
7317
Larry Hastings2f936352014-08-05 14:04:04 +10007318static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007319os_getpgrp_impl(PyObject *module)
7320/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
Guido van Rossum04814471991-06-04 20:23:49 +00007321{
Guido van Rossumb6775db1994-08-01 11:34:53 +00007322#ifdef GETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007323 return PyLong_FromPid(getpgrp(0));
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007324#else /* GETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007325 return PyLong_FromPid(getpgrp());
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007326#endif /* GETPGRP_HAVE_ARG */
Guido van Rossum04814471991-06-04 20:23:49 +00007327}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007328#endif /* HAVE_GETPGRP */
Guido van Rossum04814471991-06-04 20:23:49 +00007329
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007330
Guido van Rossumb6775db1994-08-01 11:34:53 +00007331#ifdef HAVE_SETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007332/*[clinic input]
7333os.setpgrp
7334
7335Make the current process the leader of its process group.
7336[clinic start generated code]*/
7337
Larry Hastings2f936352014-08-05 14:04:04 +10007338static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007339os_setpgrp_impl(PyObject *module)
7340/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00007341{
Guido van Rossum64933891994-10-20 21:56:42 +00007342#ifdef SETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007343 if (setpgrp(0, 0) < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007344#else /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007345 if (setpgrp() < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007346#endif /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007347 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007348 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00007349}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007350#endif /* HAVE_SETPGRP */
7351
Guido van Rossumad0ee831995-03-01 10:34:45 +00007352#ifdef HAVE_GETPPID
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007353
7354#ifdef MS_WINDOWS
7355#include <tlhelp32.h>
7356
7357static PyObject*
7358win32_getppid()
7359{
7360 HANDLE snapshot;
7361 pid_t mypid;
7362 PyObject* result = NULL;
7363 BOOL have_record;
7364 PROCESSENTRY32 pe;
7365
7366 mypid = getpid(); /* This function never fails */
7367
7368 snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
7369 if (snapshot == INVALID_HANDLE_VALUE)
7370 return PyErr_SetFromWindowsErr(GetLastError());
7371
7372 pe.dwSize = sizeof(pe);
7373 have_record = Process32First(snapshot, &pe);
7374 while (have_record) {
7375 if (mypid == (pid_t)pe.th32ProcessID) {
7376 /* We could cache the ulong value in a static variable. */
7377 result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
7378 break;
7379 }
7380
7381 have_record = Process32Next(snapshot, &pe);
7382 }
7383
7384 /* If our loop exits and our pid was not found (result will be NULL)
7385 * then GetLastError will return ERROR_NO_MORE_FILES. This is an
7386 * error anyway, so let's raise it. */
7387 if (!result)
7388 result = PyErr_SetFromWindowsErr(GetLastError());
7389
7390 CloseHandle(snapshot);
7391
7392 return result;
7393}
7394#endif /*MS_WINDOWS*/
7395
Larry Hastings2f936352014-08-05 14:04:04 +10007396
7397/*[clinic input]
7398os.getppid
7399
7400Return the parent's process id.
7401
7402If the parent process has already exited, Windows machines will still
7403return its id; others systems will return the id of the 'init' process (1).
7404[clinic start generated code]*/
7405
Larry Hastings2f936352014-08-05 14:04:04 +10007406static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007407os_getppid_impl(PyObject *module)
7408/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00007409{
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007410#ifdef MS_WINDOWS
7411 return win32_getppid();
7412#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007413 return PyLong_FromPid(getppid());
Guido van Rossumad0ee831995-03-01 10:34:45 +00007414#endif
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007415}
7416#endif /* HAVE_GETPPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007417
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007418
Fred Drake12c6e2d1999-12-14 21:25:03 +00007419#ifdef HAVE_GETLOGIN
Larry Hastings2f936352014-08-05 14:04:04 +10007420/*[clinic input]
7421os.getlogin
7422
7423Return the actual login name.
7424[clinic start generated code]*/
7425
Larry Hastings2f936352014-08-05 14:04:04 +10007426static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007427os_getlogin_impl(PyObject *module)
7428/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
Fred Drake12c6e2d1999-12-14 21:25:03 +00007429{
Victor Stinner8c62be82010-05-06 00:08:46 +00007430 PyObject *result = NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007431#ifdef MS_WINDOWS
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007432 wchar_t user_name[UNLEN + 1];
Victor Stinner63941882011-09-29 00:42:28 +02007433 DWORD num_chars = Py_ARRAY_LENGTH(user_name);
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007434
7435 if (GetUserNameW(user_name, &num_chars)) {
7436 /* num_chars is the number of unicode chars plus null terminator */
7437 result = PyUnicode_FromWideChar(user_name, num_chars - 1);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007438 }
7439 else
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007440 result = PyErr_SetFromWindowsErr(GetLastError());
7441#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007442 char *name;
7443 int old_errno = errno;
Fred Drake12c6e2d1999-12-14 21:25:03 +00007444
Victor Stinner8c62be82010-05-06 00:08:46 +00007445 errno = 0;
7446 name = getlogin();
7447 if (name == NULL) {
7448 if (errno)
Victor Stinnere039ffe2010-08-15 09:33:08 +00007449 posix_error();
Fred Drake12c6e2d1999-12-14 21:25:03 +00007450 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007451 PyErr_SetString(PyExc_OSError, "unable to determine login name");
Victor Stinner8c62be82010-05-06 00:08:46 +00007452 }
7453 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007454 result = PyUnicode_DecodeFSDefault(name);
Victor Stinner8c62be82010-05-06 00:08:46 +00007455 errno = old_errno;
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007456#endif
Fred Drake12c6e2d1999-12-14 21:25:03 +00007457 return result;
7458}
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007459#endif /* HAVE_GETLOGIN */
Fred Drake12c6e2d1999-12-14 21:25:03 +00007460
Larry Hastings2f936352014-08-05 14:04:04 +10007461
Guido van Rossumad0ee831995-03-01 10:34:45 +00007462#ifdef HAVE_GETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007463/*[clinic input]
7464os.getuid
7465
7466Return the current process's user id.
7467[clinic start generated code]*/
7468
Larry Hastings2f936352014-08-05 14:04:04 +10007469static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007470os_getuid_impl(PyObject *module)
7471/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00007472{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007473 return _PyLong_FromUid(getuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00007474}
Larry Hastings2f936352014-08-05 14:04:04 +10007475#endif /* HAVE_GETUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00007476
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007477
Brian Curtineb24d742010-04-12 17:16:38 +00007478#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007479#define HAVE_KILL
7480#endif /* MS_WINDOWS */
7481
7482#ifdef HAVE_KILL
7483/*[clinic input]
7484os.kill
7485
7486 pid: pid_t
7487 signal: Py_ssize_t
7488 /
7489
7490Kill a process with a signal.
7491[clinic start generated code]*/
7492
Larry Hastings2f936352014-08-05 14:04:04 +10007493static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007494os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
7495/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007496{
Saiyang Gou7514f4f2020-02-12 23:47:42 -08007497 if (PySys_Audit("os.kill", "in", pid, signal) < 0) {
7498 return NULL;
7499 }
7500#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007501 if (kill(pid, (int)signal) == -1)
7502 return posix_error();
7503 Py_RETURN_NONE;
Larry Hastings2f936352014-08-05 14:04:04 +10007504#else /* !MS_WINDOWS */
Amaury Forgeot d'Arc0a589c92010-05-15 20:35:12 +00007505 PyObject *result;
Larry Hastings2f936352014-08-05 14:04:04 +10007506 DWORD sig = (DWORD)signal;
7507 DWORD err;
Victor Stinner8c62be82010-05-06 00:08:46 +00007508 HANDLE handle;
Brian Curtineb24d742010-04-12 17:16:38 +00007509
Victor Stinner8c62be82010-05-06 00:08:46 +00007510 /* Console processes which share a common console can be sent CTRL+C or
7511 CTRL+BREAK events, provided they handle said events. */
7512 if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007513 if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007514 err = GetLastError();
7515 PyErr_SetFromWindowsErr(err);
7516 }
7517 else
7518 Py_RETURN_NONE;
7519 }
Brian Curtineb24d742010-04-12 17:16:38 +00007520
Victor Stinner8c62be82010-05-06 00:08:46 +00007521 /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
7522 attempt to open and terminate the process. */
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007523 handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007524 if (handle == NULL) {
7525 err = GetLastError();
7526 return PyErr_SetFromWindowsErr(err);
7527 }
Brian Curtineb24d742010-04-12 17:16:38 +00007528
Victor Stinner8c62be82010-05-06 00:08:46 +00007529 if (TerminateProcess(handle, sig) == 0) {
7530 err = GetLastError();
7531 result = PyErr_SetFromWindowsErr(err);
7532 } else {
7533 Py_INCREF(Py_None);
7534 result = Py_None;
7535 }
Brian Curtineb24d742010-04-12 17:16:38 +00007536
Victor Stinner8c62be82010-05-06 00:08:46 +00007537 CloseHandle(handle);
7538 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10007539#endif /* !MS_WINDOWS */
Saiyang Gou7514f4f2020-02-12 23:47:42 -08007540}
Larry Hastings2f936352014-08-05 14:04:04 +10007541#endif /* HAVE_KILL */
7542
7543
7544#ifdef HAVE_KILLPG
7545/*[clinic input]
7546os.killpg
7547
7548 pgid: pid_t
7549 signal: int
7550 /
7551
7552Kill a process group with a signal.
7553[clinic start generated code]*/
7554
Larry Hastings2f936352014-08-05 14:04:04 +10007555static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007556os_killpg_impl(PyObject *module, pid_t pgid, int signal)
7557/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007558{
Saiyang Gou7514f4f2020-02-12 23:47:42 -08007559 if (PySys_Audit("os.killpg", "ii", pgid, signal) < 0) {
7560 return NULL;
7561 }
Larry Hastings2f936352014-08-05 14:04:04 +10007562 /* XXX some man pages make the `pgid` parameter an int, others
7563 a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
7564 take the same type. Moreover, pid_t is always at least as wide as
7565 int (else compilation of this module fails), which is safe. */
7566 if (killpg(pgid, signal) == -1)
7567 return posix_error();
7568 Py_RETURN_NONE;
7569}
7570#endif /* HAVE_KILLPG */
7571
Brian Curtineb24d742010-04-12 17:16:38 +00007572
Guido van Rossumc0125471996-06-28 18:55:32 +00007573#ifdef HAVE_PLOCK
Guido van Rossumc0125471996-06-28 18:55:32 +00007574#ifdef HAVE_SYS_LOCK_H
7575#include <sys/lock.h>
7576#endif
7577
Larry Hastings2f936352014-08-05 14:04:04 +10007578/*[clinic input]
7579os.plock
7580 op: int
7581 /
7582
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007583Lock program segments into memory.");
Larry Hastings2f936352014-08-05 14:04:04 +10007584[clinic start generated code]*/
7585
Larry Hastings2f936352014-08-05 14:04:04 +10007586static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007587os_plock_impl(PyObject *module, int op)
7588/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007589{
Victor Stinner8c62be82010-05-06 00:08:46 +00007590 if (plock(op) == -1)
7591 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007592 Py_RETURN_NONE;
Guido van Rossumc0125471996-06-28 18:55:32 +00007593}
Larry Hastings2f936352014-08-05 14:04:04 +10007594#endif /* HAVE_PLOCK */
7595
Guido van Rossumc0125471996-06-28 18:55:32 +00007596
Guido van Rossumb6775db1994-08-01 11:34:53 +00007597#ifdef HAVE_SETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007598/*[clinic input]
7599os.setuid
7600
7601 uid: uid_t
7602 /
7603
7604Set the current process's user id.
7605[clinic start generated code]*/
7606
Larry Hastings2f936352014-08-05 14:04:04 +10007607static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007608os_setuid_impl(PyObject *module, uid_t uid)
7609/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007610{
Victor Stinner8c62be82010-05-06 00:08:46 +00007611 if (setuid(uid) < 0)
7612 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007613 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007614}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007615#endif /* HAVE_SETUID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007616
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007617
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007618#ifdef HAVE_SETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10007619/*[clinic input]
7620os.seteuid
7621
7622 euid: uid_t
7623 /
7624
7625Set the current process's effective user id.
7626[clinic start generated code]*/
7627
Larry Hastings2f936352014-08-05 14:04:04 +10007628static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007629os_seteuid_impl(PyObject *module, uid_t euid)
7630/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007631{
7632 if (seteuid(euid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007633 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007634 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007635}
7636#endif /* HAVE_SETEUID */
7637
Larry Hastings2f936352014-08-05 14:04:04 +10007638
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007639#ifdef HAVE_SETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10007640/*[clinic input]
7641os.setegid
7642
7643 egid: gid_t
7644 /
7645
7646Set the current process's effective group id.
7647[clinic start generated code]*/
7648
Larry Hastings2f936352014-08-05 14:04:04 +10007649static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007650os_setegid_impl(PyObject *module, gid_t egid)
7651/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007652{
7653 if (setegid(egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007654 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007655 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007656}
7657#endif /* HAVE_SETEGID */
7658
Larry Hastings2f936352014-08-05 14:04:04 +10007659
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007660#ifdef HAVE_SETREUID
Larry Hastings2f936352014-08-05 14:04:04 +10007661/*[clinic input]
7662os.setreuid
7663
7664 ruid: uid_t
7665 euid: uid_t
7666 /
7667
7668Set the current process's real and effective user ids.
7669[clinic start generated code]*/
7670
Larry Hastings2f936352014-08-05 14:04:04 +10007671static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007672os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
7673/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007674{
Victor Stinner8c62be82010-05-06 00:08:46 +00007675 if (setreuid(ruid, euid) < 0) {
7676 return posix_error();
7677 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007678 Py_RETURN_NONE;
Victor Stinner8c62be82010-05-06 00:08:46 +00007679 }
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007680}
7681#endif /* HAVE_SETREUID */
7682
Larry Hastings2f936352014-08-05 14:04:04 +10007683
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007684#ifdef HAVE_SETREGID
Larry Hastings2f936352014-08-05 14:04:04 +10007685/*[clinic input]
7686os.setregid
7687
7688 rgid: gid_t
7689 egid: gid_t
7690 /
7691
7692Set the current process's real and effective group ids.
7693[clinic start generated code]*/
7694
Larry Hastings2f936352014-08-05 14:04:04 +10007695static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007696os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
7697/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007698{
7699 if (setregid(rgid, egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007700 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007701 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007702}
7703#endif /* HAVE_SETREGID */
7704
Larry Hastings2f936352014-08-05 14:04:04 +10007705
Guido van Rossumb6775db1994-08-01 11:34:53 +00007706#ifdef HAVE_SETGID
Larry Hastings2f936352014-08-05 14:04:04 +10007707/*[clinic input]
7708os.setgid
7709 gid: gid_t
7710 /
7711
7712Set the current process's group id.
7713[clinic start generated code]*/
7714
Larry Hastings2f936352014-08-05 14:04:04 +10007715static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007716os_setgid_impl(PyObject *module, gid_t gid)
7717/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007718{
Victor Stinner8c62be82010-05-06 00:08:46 +00007719 if (setgid(gid) < 0)
7720 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007721 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007722}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007723#endif /* HAVE_SETGID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007724
Larry Hastings2f936352014-08-05 14:04:04 +10007725
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007726#ifdef HAVE_SETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007727/*[clinic input]
7728os.setgroups
7729
7730 groups: object
7731 /
7732
7733Set the groups of the current process to list.
7734[clinic start generated code]*/
7735
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007736static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007737os_setgroups(PyObject *module, PyObject *groups)
7738/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007739{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007740 Py_ssize_t i, len;
Victor Stinner8c62be82010-05-06 00:08:46 +00007741 gid_t grouplist[MAX_GROUPS];
Tim Peters5aa91602002-01-30 05:46:57 +00007742
Victor Stinner8c62be82010-05-06 00:08:46 +00007743 if (!PySequence_Check(groups)) {
7744 PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
7745 return NULL;
7746 }
7747 len = PySequence_Size(groups);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007748 if (len < 0) {
7749 return NULL;
7750 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007751 if (len > MAX_GROUPS) {
7752 PyErr_SetString(PyExc_ValueError, "too many groups");
7753 return NULL;
7754 }
7755 for(i = 0; i < len; i++) {
7756 PyObject *elem;
7757 elem = PySequence_GetItem(groups, i);
7758 if (!elem)
7759 return NULL;
7760 if (!PyLong_Check(elem)) {
7761 PyErr_SetString(PyExc_TypeError,
7762 "groups must be integers");
7763 Py_DECREF(elem);
7764 return NULL;
7765 } else {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007766 if (!_Py_Gid_Converter(elem, &grouplist[i])) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007767 Py_DECREF(elem);
7768 return NULL;
7769 }
7770 }
7771 Py_DECREF(elem);
7772 }
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007773
Victor Stinner8c62be82010-05-06 00:08:46 +00007774 if (setgroups(len, grouplist) < 0)
7775 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007776 Py_RETURN_NONE;
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007777}
7778#endif /* HAVE_SETGROUPS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007779
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007780#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
7781static PyObject *
Victor Stinner1c2fa782020-05-10 11:05:29 +02007782wait_helper(PyObject *module, pid_t pid, int status, struct rusage *ru)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007783{
Victor Stinner8c62be82010-05-06 00:08:46 +00007784 PyObject *result;
Eddie Elizondob3966632019-11-05 07:16:14 -08007785 PyObject *struct_rusage;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007786
Victor Stinner8c62be82010-05-06 00:08:46 +00007787 if (pid == -1)
7788 return posix_error();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007789
Zackery Spytz682107c2019-09-09 09:48:32 -06007790 // If wait succeeded but no child was ready to report status, ru will not
7791 // have been populated.
7792 if (pid == 0) {
7793 memset(ru, 0, sizeof(*ru));
7794 }
7795
Eddie Elizondob3966632019-11-05 07:16:14 -08007796 PyObject *m = PyImport_ImportModuleNoBlock("resource");
7797 if (m == NULL)
7798 return NULL;
Victor Stinner1c2fa782020-05-10 11:05:29 +02007799 struct_rusage = PyObject_GetAttr(m, get_posix_state(module)->struct_rusage);
Eddie Elizondob3966632019-11-05 07:16:14 -08007800 Py_DECREF(m);
7801 if (struct_rusage == NULL)
7802 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007803
Victor Stinner8c62be82010-05-06 00:08:46 +00007804 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
7805 result = PyStructSequence_New((PyTypeObject*) struct_rusage);
Eddie Elizondoe4db1f02019-11-25 19:07:37 -08007806 Py_DECREF(struct_rusage);
Victor Stinner8c62be82010-05-06 00:08:46 +00007807 if (!result)
7808 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007809
7810#ifndef doubletime
7811#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
7812#endif
7813
Victor Stinner8c62be82010-05-06 00:08:46 +00007814 PyStructSequence_SET_ITEM(result, 0,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007815 PyFloat_FromDouble(doubletime(ru->ru_utime)));
Victor Stinner8c62be82010-05-06 00:08:46 +00007816 PyStructSequence_SET_ITEM(result, 1,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007817 PyFloat_FromDouble(doubletime(ru->ru_stime)));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007818#define SET_INT(result, index, value)\
Victor Stinner8c62be82010-05-06 00:08:46 +00007819 PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
7820 SET_INT(result, 2, ru->ru_maxrss);
7821 SET_INT(result, 3, ru->ru_ixrss);
7822 SET_INT(result, 4, ru->ru_idrss);
7823 SET_INT(result, 5, ru->ru_isrss);
7824 SET_INT(result, 6, ru->ru_minflt);
7825 SET_INT(result, 7, ru->ru_majflt);
7826 SET_INT(result, 8, ru->ru_nswap);
7827 SET_INT(result, 9, ru->ru_inblock);
7828 SET_INT(result, 10, ru->ru_oublock);
7829 SET_INT(result, 11, ru->ru_msgsnd);
7830 SET_INT(result, 12, ru->ru_msgrcv);
7831 SET_INT(result, 13, ru->ru_nsignals);
7832 SET_INT(result, 14, ru->ru_nvcsw);
7833 SET_INT(result, 15, ru->ru_nivcsw);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007834#undef SET_INT
7835
Victor Stinner8c62be82010-05-06 00:08:46 +00007836 if (PyErr_Occurred()) {
7837 Py_DECREF(result);
7838 return NULL;
7839 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007840
Victor Stinner8c62be82010-05-06 00:08:46 +00007841 return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007842}
7843#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
7844
Larry Hastings2f936352014-08-05 14:04:04 +10007845
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007846#ifdef HAVE_WAIT3
Larry Hastings2f936352014-08-05 14:04:04 +10007847/*[clinic input]
7848os.wait3
7849
7850 options: int
7851Wait for completion of a child process.
7852
7853Returns a tuple of information about the child process:
7854 (pid, status, rusage)
7855[clinic start generated code]*/
7856
Larry Hastings2f936352014-08-05 14:04:04 +10007857static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007858os_wait3_impl(PyObject *module, int options)
7859/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007860{
Victor Stinner8c62be82010-05-06 00:08:46 +00007861 pid_t pid;
Victor Stinner8c62be82010-05-06 00:08:46 +00007862 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007863 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007864 WAIT_TYPE status;
7865 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007866
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007867 do {
7868 Py_BEGIN_ALLOW_THREADS
7869 pid = wait3(&status, options, &ru);
7870 Py_END_ALLOW_THREADS
7871 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7872 if (pid < 0)
7873 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007874
Victor Stinner1c2fa782020-05-10 11:05:29 +02007875 return wait_helper(module, pid, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007876}
7877#endif /* HAVE_WAIT3 */
7878
Larry Hastings2f936352014-08-05 14:04:04 +10007879
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007880#ifdef HAVE_WAIT4
Larry Hastings2f936352014-08-05 14:04:04 +10007881/*[clinic input]
7882
7883os.wait4
7884
7885 pid: pid_t
7886 options: int
7887
7888Wait for completion of a specific child process.
7889
7890Returns a tuple of information about the child process:
7891 (pid, status, rusage)
7892[clinic start generated code]*/
7893
Larry Hastings2f936352014-08-05 14:04:04 +10007894static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007895os_wait4_impl(PyObject *module, pid_t pid, int options)
7896/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007897{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007898 pid_t res;
Victor Stinner8c62be82010-05-06 00:08:46 +00007899 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007900 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007901 WAIT_TYPE status;
7902 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007903
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007904 do {
7905 Py_BEGIN_ALLOW_THREADS
7906 res = wait4(pid, &status, options, &ru);
7907 Py_END_ALLOW_THREADS
7908 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7909 if (res < 0)
7910 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007911
Victor Stinner1c2fa782020-05-10 11:05:29 +02007912 return wait_helper(module, res, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007913}
7914#endif /* HAVE_WAIT4 */
7915
Larry Hastings2f936352014-08-05 14:04:04 +10007916
Ross Lagerwall7807c352011-03-17 20:20:30 +02007917#if defined(HAVE_WAITID) && !defined(__APPLE__)
Larry Hastings2f936352014-08-05 14:04:04 +10007918/*[clinic input]
7919os.waitid
7920
7921 idtype: idtype_t
7922 Must be one of be P_PID, P_PGID or P_ALL.
7923 id: id_t
7924 The id to wait on.
7925 options: int
7926 Constructed from the ORing of one or more of WEXITED, WSTOPPED
7927 or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
7928 /
7929
7930Returns the result of waiting for a process or processes.
7931
7932Returns either waitid_result or None if WNOHANG is specified and there are
7933no children in a waitable state.
7934[clinic start generated code]*/
7935
Larry Hastings2f936352014-08-05 14:04:04 +10007936static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007937os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
7938/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007939{
7940 PyObject *result;
7941 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007942 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007943 siginfo_t si;
7944 si.si_pid = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007945
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007946 do {
7947 Py_BEGIN_ALLOW_THREADS
7948 res = waitid(idtype, id, &si, options);
7949 Py_END_ALLOW_THREADS
7950 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7951 if (res < 0)
7952 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007953
7954 if (si.si_pid == 0)
7955 Py_RETURN_NONE;
7956
Hai Shif707d942020-03-16 21:15:01 +08007957 PyObject *WaitidResultType = get_posix_state(module)->WaitidResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -08007958 result = PyStructSequence_New((PyTypeObject *)WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +02007959 if (!result)
7960 return NULL;
7961
7962 PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007963 PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
Ross Lagerwall7807c352011-03-17 20:20:30 +02007964 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
7965 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
7966 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
7967 if (PyErr_Occurred()) {
7968 Py_DECREF(result);
7969 return NULL;
7970 }
7971
7972 return result;
7973}
Larry Hastings2f936352014-08-05 14:04:04 +10007974#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
Ross Lagerwall7807c352011-03-17 20:20:30 +02007975
Larry Hastings2f936352014-08-05 14:04:04 +10007976
7977#if defined(HAVE_WAITPID)
7978/*[clinic input]
7979os.waitpid
7980 pid: pid_t
7981 options: int
7982 /
7983
7984Wait for completion of a given child process.
7985
7986Returns a tuple of information regarding the child process:
7987 (pid, status)
7988
7989The options argument is ignored on Windows.
7990[clinic start generated code]*/
7991
Larry Hastings2f936352014-08-05 14:04:04 +10007992static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007993os_waitpid_impl(PyObject *module, pid_t pid, int options)
7994/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007995{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007996 pid_t res;
7997 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007998 WAIT_TYPE status;
7999 WAIT_STATUS_INT(status) = 0;
Guido van Rossum54ecc3d1999-01-27 17:53:11 +00008000
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008001 do {
8002 Py_BEGIN_ALLOW_THREADS
8003 res = waitpid(pid, &status, options);
8004 Py_END_ALLOW_THREADS
8005 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8006 if (res < 0)
8007 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008008
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008009 return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
Guido van Rossum21803b81992-08-09 12:55:27 +00008010}
Tim Petersab034fa2002-02-01 11:27:43 +00008011#elif defined(HAVE_CWAIT)
Tim Petersab034fa2002-02-01 11:27:43 +00008012/* MS C has a variant of waitpid() that's usable for most purposes. */
Larry Hastings2f936352014-08-05 14:04:04 +10008013/*[clinic input]
8014os.waitpid
Benjamin Petersonca470632016-09-06 13:47:26 -07008015 pid: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +10008016 options: int
8017 /
8018
8019Wait for completion of a given process.
8020
8021Returns a tuple of information regarding the process:
8022 (pid, status << 8)
8023
8024The options argument is ignored on Windows.
8025[clinic start generated code]*/
8026
Larry Hastings2f936352014-08-05 14:04:04 +10008027static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -07008028os_waitpid_impl(PyObject *module, intptr_t pid, int options)
Victor Stinner581139c2016-09-06 15:54:20 -07008029/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008030{
8031 int status;
Benjamin Petersonca470632016-09-06 13:47:26 -07008032 intptr_t res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008033 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008034
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008035 do {
8036 Py_BEGIN_ALLOW_THREADS
Steve Dower11f43262016-11-19 18:33:39 -08008037 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008038 res = _cwait(&status, pid, options);
Steve Dower11f43262016-11-19 18:33:39 -08008039 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008040 Py_END_ALLOW_THREADS
8041 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinnerd3ffd322015-09-15 10:11:03 +02008042 if (res < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008043 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008044
Victor Stinner9bee32b2020-04-22 16:30:35 +02008045 unsigned long long ustatus = (unsigned int)status;
8046
Victor Stinner8c62be82010-05-06 00:08:46 +00008047 /* shift the status left a byte so this is more like the POSIX waitpid */
Victor Stinner9bee32b2020-04-22 16:30:35 +02008048 return Py_BuildValue(_Py_PARSE_INTPTR "K", res, ustatus << 8);
Tim Petersab034fa2002-02-01 11:27:43 +00008049}
Larry Hastings2f936352014-08-05 14:04:04 +10008050#endif
8051
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008052
Guido van Rossumad0ee831995-03-01 10:34:45 +00008053#ifdef HAVE_WAIT
Larry Hastings2f936352014-08-05 14:04:04 +10008054/*[clinic input]
8055os.wait
8056
8057Wait for completion of a child process.
8058
8059Returns a tuple of information about the child process:
8060 (pid, status)
8061[clinic start generated code]*/
8062
Larry Hastings2f936352014-08-05 14:04:04 +10008063static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008064os_wait_impl(PyObject *module)
8065/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
Guido van Rossum21803b81992-08-09 12:55:27 +00008066{
Victor Stinner8c62be82010-05-06 00:08:46 +00008067 pid_t pid;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008068 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00008069 WAIT_TYPE status;
8070 WAIT_STATUS_INT(status) = 0;
Neal Norwitze241ce82003-02-17 18:17:05 +00008071
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008072 do {
8073 Py_BEGIN_ALLOW_THREADS
8074 pid = wait(&status);
8075 Py_END_ALLOW_THREADS
8076 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8077 if (pid < 0)
8078 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008079
Victor Stinner8c62be82010-05-06 00:08:46 +00008080 return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
Guido van Rossum85e3b011991-06-03 12:42:10 +00008081}
Larry Hastings2f936352014-08-05 14:04:04 +10008082#endif /* HAVE_WAIT */
Guido van Rossum85e3b011991-06-03 12:42:10 +00008083
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -08008084#if defined(__linux__) && defined(__NR_pidfd_open)
8085/*[clinic input]
8086os.pidfd_open
8087 pid: pid_t
8088 flags: unsigned_int = 0
8089
8090Return a file descriptor referring to the process *pid*.
8091
8092The descriptor can be used to perform process management without races and
8093signals.
8094[clinic start generated code]*/
8095
8096static PyObject *
8097os_pidfd_open_impl(PyObject *module, pid_t pid, unsigned int flags)
8098/*[clinic end generated code: output=5c7252698947dc41 input=c3fd99ce947ccfef]*/
8099{
8100 int fd = syscall(__NR_pidfd_open, pid, flags);
8101 if (fd < 0) {
8102 return posix_error();
8103 }
8104 return PyLong_FromLong(fd);
8105}
8106#endif
8107
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008108
Larry Hastings9cf065c2012-06-22 16:30:09 -07008109#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008110/*[clinic input]
8111os.readlink
8112
8113 path: path_t
8114 *
8115 dir_fd: dir_fd(requires='readlinkat') = None
8116
8117Return a string representing the path to which the symbolic link points.
8118
8119If dir_fd is not None, it should be a file descriptor open to a directory,
8120and path should be relative; path will then be relative to that directory.
8121
8122dir_fd may not be implemented on your platform. If it is unavailable,
8123using it will raise a NotImplementedError.
8124[clinic start generated code]*/
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008125
Barry Warsaw53699e91996-12-10 23:23:01 +00008126static PyObject *
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008127os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
8128/*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008129{
Berker Peksage0b5b202018-08-15 13:03:41 +03008130#if defined(HAVE_READLINK)
Christian Heimes3cb091e2016-09-23 20:24:28 +02008131 char buffer[MAXPATHLEN+1];
Larry Hastings9cf065c2012-06-22 16:30:09 -07008132 ssize_t length;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008133
8134 Py_BEGIN_ALLOW_THREADS
8135#ifdef HAVE_READLINKAT
8136 if (dir_fd != DEFAULT_DIR_FD)
8137 length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
8138 else
8139#endif
8140 length = readlink(path->narrow, buffer, MAXPATHLEN);
8141 Py_END_ALLOW_THREADS
8142
8143 if (length < 0) {
8144 return path_error(path);
8145 }
8146 buffer[length] = '\0';
8147
8148 if (PyUnicode_Check(path->object))
8149 return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
8150 else
8151 return PyBytes_FromStringAndSize(buffer, length);
Berker Peksage0b5b202018-08-15 13:03:41 +03008152#elif defined(MS_WINDOWS)
8153 DWORD n_bytes_returned;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008154 DWORD io_result = 0;
Berker Peksage0b5b202018-08-15 13:03:41 +03008155 HANDLE reparse_point_handle;
Berker Peksage0b5b202018-08-15 13:03:41 +03008156 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
8157 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Steve Dower993ac922019-09-03 12:50:51 -07008158 PyObject *result = NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00008159
Larry Hastings2f936352014-08-05 14:04:04 +10008160 /* First get a handle to the reparse point */
8161 Py_BEGIN_ALLOW_THREADS
8162 reparse_point_handle = CreateFileW(
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008163 path->wide,
Larry Hastings2f936352014-08-05 14:04:04 +10008164 0,
8165 0,
8166 0,
8167 OPEN_EXISTING,
8168 FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
8169 0);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008170 if (reparse_point_handle != INVALID_HANDLE_VALUE) {
8171 /* New call DeviceIoControl to read the reparse point */
8172 io_result = DeviceIoControl(
8173 reparse_point_handle,
8174 FSCTL_GET_REPARSE_POINT,
8175 0, 0, /* in buffer */
8176 target_buffer, sizeof(target_buffer),
8177 &n_bytes_returned,
8178 0 /* we're not using OVERLAPPED_IO */
8179 );
8180 CloseHandle(reparse_point_handle);
Berker Peksage0b5b202018-08-15 13:03:41 +03008181 }
Larry Hastings2f936352014-08-05 14:04:04 +10008182 Py_END_ALLOW_THREADS
8183
Berker Peksage0b5b202018-08-15 13:03:41 +03008184 if (io_result == 0) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008185 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03008186 }
Larry Hastings2f936352014-08-05 14:04:04 +10008187
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008188 wchar_t *name = NULL;
8189 Py_ssize_t nameLen = 0;
8190 if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
Larry Hastings2f936352014-08-05 14:04:04 +10008191 {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008192 name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
8193 rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
8194 nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
Larry Hastings2f936352014-08-05 14:04:04 +10008195 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008196 else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
8197 {
8198 name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
8199 rdb->MountPointReparseBuffer.SubstituteNameOffset);
8200 nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
8201 }
8202 else
8203 {
8204 PyErr_SetString(PyExc_ValueError, "not a symbolic link");
8205 }
8206 if (name) {
8207 if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
8208 /* Our buffer is mutable, so this is okay */
8209 name[1] = L'\\';
8210 }
8211 result = PyUnicode_FromWideChar(name, nameLen);
Steve Dower993ac922019-09-03 12:50:51 -07008212 if (result && path->narrow) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008213 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
8214 }
Berker Peksage0b5b202018-08-15 13:03:41 +03008215 }
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008216 return result;
Berker Peksage0b5b202018-08-15 13:03:41 +03008217#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008218}
Berker Peksage0b5b202018-08-15 13:03:41 +03008219#endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008220
Larry Hastings9cf065c2012-06-22 16:30:09 -07008221#if defined(MS_WINDOWS)
8222
Steve Dower6921e732018-03-05 14:26:08 -08008223/* Remove the last portion of the path - return 0 on success */
8224static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008225_dirnameW(WCHAR *path)
8226{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008227 WCHAR *ptr;
Steve Dower6921e732018-03-05 14:26:08 -08008228 size_t length = wcsnlen_s(path, MAX_PATH);
8229 if (length == MAX_PATH) {
8230 return -1;
8231 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008232
8233 /* walk the path from the end until a backslash is encountered */
Steve Dower6921e732018-03-05 14:26:08 -08008234 for(ptr = path + length; ptr != path; ptr--) {
8235 if (*ptr == L'\\' || *ptr == L'/') {
Jason R. Coombs3a092862013-05-27 23:21:28 -04008236 break;
Steve Dower6921e732018-03-05 14:26:08 -08008237 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008238 }
8239 *ptr = 0;
Steve Dower6921e732018-03-05 14:26:08 -08008240 return 0;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008241}
8242
Minmin Gong7f21c9a2020-05-18 09:17:19 -07008243#endif
8244
8245#ifdef HAVE_SYMLINK
8246
8247#if defined(MS_WINDOWS)
8248
Victor Stinner31b3b922013-06-05 01:49:17 +02008249/* Is this path absolute? */
8250static int
8251_is_absW(const WCHAR *path)
8252{
Steve Dower6921e732018-03-05 14:26:08 -08008253 return path[0] == L'\\' || path[0] == L'/' ||
8254 (path[0] && path[1] == L':');
Jason R. Coombs3a092862013-05-27 23:21:28 -04008255}
8256
Steve Dower6921e732018-03-05 14:26:08 -08008257/* join root and rest with a backslash - return 0 on success */
8258static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008259_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
8260{
Victor Stinner31b3b922013-06-05 01:49:17 +02008261 if (_is_absW(rest)) {
Steve Dower6921e732018-03-05 14:26:08 -08008262 return wcscpy_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008263 }
8264
Steve Dower6921e732018-03-05 14:26:08 -08008265 if (wcscpy_s(dest_path, MAX_PATH, root)) {
8266 return -1;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008267 }
Steve Dower6921e732018-03-05 14:26:08 -08008268
8269 if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
8270 return -1;
8271 }
8272
8273 return wcscat_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008274}
8275
Victor Stinner31b3b922013-06-05 01:49:17 +02008276/* Return True if the path at src relative to dest is a directory */
8277static int
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03008278_check_dirW(LPCWSTR src, LPCWSTR dest)
Jason R. Coombs3a092862013-05-27 23:21:28 -04008279{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008280 WIN32_FILE_ATTRIBUTE_DATA src_info;
8281 WCHAR dest_parent[MAX_PATH];
8282 WCHAR src_resolved[MAX_PATH] = L"";
8283
8284 /* dest_parent = os.path.dirname(dest) */
Steve Dower6921e732018-03-05 14:26:08 -08008285 if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
8286 _dirnameW(dest_parent)) {
8287 return 0;
8288 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008289 /* src_resolved = os.path.join(dest_parent, src) */
Steve Dower6921e732018-03-05 14:26:08 -08008290 if (_joinW(src_resolved, dest_parent, src)) {
8291 return 0;
8292 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008293 return (
8294 GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
8295 && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
8296 );
8297}
Larry Hastings9cf065c2012-06-22 16:30:09 -07008298#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008299
Larry Hastings2f936352014-08-05 14:04:04 +10008300
8301/*[clinic input]
8302os.symlink
8303 src: path_t
8304 dst: path_t
8305 target_is_directory: bool = False
8306 *
8307 dir_fd: dir_fd(requires='symlinkat')=None
8308
8309# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
8310
8311Create a symbolic link pointing to src named dst.
8312
8313target_is_directory is required on Windows if the target is to be
8314 interpreted as a directory. (On Windows, symlink requires
8315 Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
8316 target_is_directory is ignored on non-Windows platforms.
8317
8318If dir_fd is not None, it should be a file descriptor open to a directory,
8319 and path should be relative; path will then be relative to that directory.
8320dir_fd may not be implemented on your platform.
8321 If it is unavailable, using it will raise a NotImplementedError.
8322
8323[clinic start generated code]*/
8324
Larry Hastings2f936352014-08-05 14:04:04 +10008325static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008326os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
Larry Hastings89964c42015-04-14 18:07:59 -04008327 int target_is_directory, int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008328/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008329{
Larry Hastings9cf065c2012-06-22 16:30:09 -07008330#ifdef MS_WINDOWS
8331 DWORD result;
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008332 DWORD flags = 0;
8333
8334 /* Assumed true, set to false if detected to not be available. */
8335 static int windows_has_symlink_unprivileged_flag = TRUE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008336#else
8337 int result;
8338#endif
8339
Saiyang Gou7514f4f2020-02-12 23:47:42 -08008340 if (PySys_Audit("os.symlink", "OOi", src->object, dst->object,
8341 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
8342 return NULL;
8343 }
8344
Larry Hastings9cf065c2012-06-22 16:30:09 -07008345#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008346
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008347 if (windows_has_symlink_unprivileged_flag) {
8348 /* Allow non-admin symlinks if system allows it. */
8349 flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
8350 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008351
Larry Hastings9cf065c2012-06-22 16:30:09 -07008352 Py_BEGIN_ALLOW_THREADS
Steve Dower6921e732018-03-05 14:26:08 -08008353 _Py_BEGIN_SUPPRESS_IPH
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008354 /* if src is a directory, ensure flags==1 (target_is_directory bit) */
8355 if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
8356 flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
8357 }
8358
8359 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
Steve Dower6921e732018-03-05 14:26:08 -08008360 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07008361 Py_END_ALLOW_THREADS
8362
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008363 if (windows_has_symlink_unprivileged_flag && !result &&
8364 ERROR_INVALID_PARAMETER == GetLastError()) {
8365
8366 Py_BEGIN_ALLOW_THREADS
8367 _Py_BEGIN_SUPPRESS_IPH
8368 /* This error might be caused by
8369 SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
8370 Try again, and update windows_has_symlink_unprivileged_flag if we
8371 are successful this time.
8372
8373 NOTE: There is a risk of a race condition here if there are other
8374 conditions than the flag causing ERROR_INVALID_PARAMETER, and
8375 another process (or thread) changes that condition in between our
8376 calls to CreateSymbolicLink.
8377 */
8378 flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
8379 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
8380 _Py_END_SUPPRESS_IPH
8381 Py_END_ALLOW_THREADS
8382
8383 if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
8384 windows_has_symlink_unprivileged_flag = FALSE;
8385 }
8386 }
8387
Larry Hastings2f936352014-08-05 14:04:04 +10008388 if (!result)
8389 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008390
8391#else
8392
Steve Dower6921e732018-03-05 14:26:08 -08008393 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
8394 PyErr_SetString(PyExc_ValueError,
8395 "symlink: src and dst must be the same type");
8396 return NULL;
8397 }
8398
Larry Hastings9cf065c2012-06-22 16:30:09 -07008399 Py_BEGIN_ALLOW_THREADS
8400#if HAVE_SYMLINKAT
8401 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10008402 result = symlinkat(src->narrow, dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008403 else
8404#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008405 result = symlink(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008406 Py_END_ALLOW_THREADS
8407
Larry Hastings2f936352014-08-05 14:04:04 +10008408 if (result)
8409 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008410#endif
8411
Larry Hastings2f936352014-08-05 14:04:04 +10008412 Py_RETURN_NONE;
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008413}
8414#endif /* HAVE_SYMLINK */
8415
Larry Hastings9cf065c2012-06-22 16:30:09 -07008416
Brian Curtind40e6f72010-07-08 21:39:08 +00008417
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008418
Larry Hastings605a62d2012-06-24 04:33:36 -07008419static PyStructSequence_Field times_result_fields[] = {
8420 {"user", "user time"},
8421 {"system", "system time"},
8422 {"children_user", "user time of children"},
8423 {"children_system", "system time of children"},
8424 {"elapsed", "elapsed time since an arbitrary point in the past"},
8425 {NULL}
8426};
8427
8428PyDoc_STRVAR(times_result__doc__,
8429"times_result: Result from os.times().\n\n\
8430This object may be accessed either as a tuple of\n\
8431 (user, system, children_user, children_system, elapsed),\n\
8432or via the attributes user, system, children_user, children_system,\n\
8433and elapsed.\n\
8434\n\
8435See os.times for more information.");
8436
8437static PyStructSequence_Desc times_result_desc = {
8438 "times_result", /* name */
8439 times_result__doc__, /* doc */
8440 times_result_fields,
8441 5
8442};
8443
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008444#ifdef MS_WINDOWS
8445#define HAVE_TIMES /* mandatory, for the method table */
8446#endif
Larry Hastings605a62d2012-06-24 04:33:36 -07008447
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008448#ifdef HAVE_TIMES
Larry Hastings605a62d2012-06-24 04:33:36 -07008449
8450static PyObject *
Victor Stinner1c2fa782020-05-10 11:05:29 +02008451build_times_result(PyObject *module, double user, double system,
Larry Hastings605a62d2012-06-24 04:33:36 -07008452 double children_user, double children_system,
8453 double elapsed)
8454{
Victor Stinner1c2fa782020-05-10 11:05:29 +02008455 PyObject *TimesResultType = get_posix_state(module)->TimesResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -08008456 PyObject *value = PyStructSequence_New((PyTypeObject *)TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07008457 if (value == NULL)
8458 return NULL;
8459
8460#define SET(i, field) \
8461 { \
8462 PyObject *o = PyFloat_FromDouble(field); \
8463 if (!o) { \
8464 Py_DECREF(value); \
8465 return NULL; \
8466 } \
8467 PyStructSequence_SET_ITEM(value, i, o); \
8468 } \
8469
8470 SET(0, user);
8471 SET(1, system);
8472 SET(2, children_user);
8473 SET(3, children_system);
8474 SET(4, elapsed);
8475
8476#undef SET
8477
8478 return value;
8479}
8480
Larry Hastings605a62d2012-06-24 04:33:36 -07008481
Larry Hastings2f936352014-08-05 14:04:04 +10008482#ifndef MS_WINDOWS
8483#define NEED_TICKS_PER_SECOND
8484static long ticks_per_second = -1;
8485#endif /* MS_WINDOWS */
8486
8487/*[clinic input]
8488os.times
8489
8490Return a collection containing process timing information.
8491
8492The object returned behaves like a named tuple with these fields:
8493 (utime, stime, cutime, cstime, elapsed_time)
8494All fields are floating point numbers.
8495[clinic start generated code]*/
8496
Larry Hastings2f936352014-08-05 14:04:04 +10008497static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008498os_times_impl(PyObject *module)
8499/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008500#ifdef MS_WINDOWS
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008501{
Victor Stinner8c62be82010-05-06 00:08:46 +00008502 FILETIME create, exit, kernel, user;
8503 HANDLE hProc;
8504 hProc = GetCurrentProcess();
8505 GetProcessTimes(hProc, &create, &exit, &kernel, &user);
8506 /* The fields of a FILETIME structure are the hi and lo part
8507 of a 64-bit value expressed in 100 nanosecond units.
8508 1e7 is one second in such units; 1e-7 the inverse.
8509 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
8510 */
Victor Stinner1c2fa782020-05-10 11:05:29 +02008511 return build_times_result(module,
Victor Stinner8c62be82010-05-06 00:08:46 +00008512 (double)(user.dwHighDateTime*429.4967296 +
8513 user.dwLowDateTime*1e-7),
8514 (double)(kernel.dwHighDateTime*429.4967296 +
8515 kernel.dwLowDateTime*1e-7),
8516 (double)0,
8517 (double)0,
8518 (double)0);
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008519}
Larry Hastings2f936352014-08-05 14:04:04 +10008520#else /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008521{
Larry Hastings2f936352014-08-05 14:04:04 +10008522
8523
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008524 struct tms t;
8525 clock_t c;
8526 errno = 0;
8527 c = times(&t);
8528 if (c == (clock_t) -1)
8529 return posix_error();
Victor Stinner1c2fa782020-05-10 11:05:29 +02008530 return build_times_result(module,
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008531 (double)t.tms_utime / ticks_per_second,
8532 (double)t.tms_stime / ticks_per_second,
8533 (double)t.tms_cutime / ticks_per_second,
8534 (double)t.tms_cstime / ticks_per_second,
8535 (double)c / ticks_per_second);
8536}
Larry Hastings2f936352014-08-05 14:04:04 +10008537#endif /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008538#endif /* HAVE_TIMES */
8539
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008540
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008541#ifdef HAVE_GETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008542/*[clinic input]
8543os.getsid
8544
8545 pid: pid_t
8546 /
8547
8548Call the system call getsid(pid) and return the result.
8549[clinic start generated code]*/
8550
Larry Hastings2f936352014-08-05 14:04:04 +10008551static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008552os_getsid_impl(PyObject *module, pid_t pid)
8553/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008554{
Victor Stinner8c62be82010-05-06 00:08:46 +00008555 int sid;
Victor Stinner8c62be82010-05-06 00:08:46 +00008556 sid = getsid(pid);
8557 if (sid < 0)
8558 return posix_error();
8559 return PyLong_FromLong((long)sid);
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008560}
8561#endif /* HAVE_GETSID */
8562
8563
Guido van Rossumb6775db1994-08-01 11:34:53 +00008564#ifdef HAVE_SETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008565/*[clinic input]
8566os.setsid
8567
8568Call the system call setsid().
8569[clinic start generated code]*/
8570
Larry Hastings2f936352014-08-05 14:04:04 +10008571static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008572os_setsid_impl(PyObject *module)
8573/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00008574{
Victor Stinner8c62be82010-05-06 00:08:46 +00008575 if (setsid() < 0)
8576 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008577 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008578}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008579#endif /* HAVE_SETSID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008580
Larry Hastings2f936352014-08-05 14:04:04 +10008581
Guido van Rossumb6775db1994-08-01 11:34:53 +00008582#ifdef HAVE_SETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10008583/*[clinic input]
8584os.setpgid
8585
8586 pid: pid_t
8587 pgrp: pid_t
8588 /
8589
8590Call the system call setpgid(pid, pgrp).
8591[clinic start generated code]*/
8592
Larry Hastings2f936352014-08-05 14:04:04 +10008593static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008594os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
8595/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008596{
Victor Stinner8c62be82010-05-06 00:08:46 +00008597 if (setpgid(pid, pgrp) < 0)
8598 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008599 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008600}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008601#endif /* HAVE_SETPGID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008602
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008603
Guido van Rossumb6775db1994-08-01 11:34:53 +00008604#ifdef HAVE_TCGETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008605/*[clinic input]
8606os.tcgetpgrp
8607
8608 fd: int
8609 /
8610
8611Return the process group associated with the terminal specified by fd.
8612[clinic start generated code]*/
8613
Larry Hastings2f936352014-08-05 14:04:04 +10008614static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008615os_tcgetpgrp_impl(PyObject *module, int fd)
8616/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008617{
8618 pid_t pgid = tcgetpgrp(fd);
Victor Stinner8c62be82010-05-06 00:08:46 +00008619 if (pgid < 0)
8620 return posix_error();
8621 return PyLong_FromPid(pgid);
Guido van Rossum7066dd71992-09-17 17:54:56 +00008622}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008623#endif /* HAVE_TCGETPGRP */
Guido van Rossum7066dd71992-09-17 17:54:56 +00008624
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008625
Guido van Rossumb6775db1994-08-01 11:34:53 +00008626#ifdef HAVE_TCSETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008627/*[clinic input]
8628os.tcsetpgrp
8629
8630 fd: int
8631 pgid: pid_t
8632 /
8633
8634Set the process group associated with the terminal specified by fd.
8635[clinic start generated code]*/
8636
Larry Hastings2f936352014-08-05 14:04:04 +10008637static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008638os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
8639/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008640{
Victor Stinner8c62be82010-05-06 00:08:46 +00008641 if (tcsetpgrp(fd, pgid) < 0)
8642 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008643 Py_RETURN_NONE;
Guido van Rossum7066dd71992-09-17 17:54:56 +00008644}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008645#endif /* HAVE_TCSETPGRP */
Guido van Rossum22db57e1992-04-05 14:25:30 +00008646
Guido van Rossum687dd131993-05-17 08:34:16 +00008647/* Functions acting on file descriptors */
8648
Victor Stinnerdaf45552013-08-28 00:53:59 +02008649#ifdef O_CLOEXEC
8650extern int _Py_open_cloexec_works;
8651#endif
8652
Larry Hastings2f936352014-08-05 14:04:04 +10008653
8654/*[clinic input]
8655os.open -> int
8656 path: path_t
8657 flags: int
8658 mode: int = 0o777
8659 *
8660 dir_fd: dir_fd(requires='openat') = None
8661
8662# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
8663
8664Open a file for low level IO. Returns a file descriptor (integer).
8665
8666If dir_fd is not None, it should be a file descriptor open to a directory,
8667 and path should be relative; path will then be relative to that directory.
8668dir_fd may not be implemented on your platform.
8669 If it is unavailable, using it will raise a NotImplementedError.
8670[clinic start generated code]*/
8671
Larry Hastings2f936352014-08-05 14:04:04 +10008672static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008673os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
8674/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008675{
8676 int fd;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008677 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008678
Victor Stinnerdaf45552013-08-28 00:53:59 +02008679#ifdef O_CLOEXEC
8680 int *atomic_flag_works = &_Py_open_cloexec_works;
8681#elif !defined(MS_WINDOWS)
8682 int *atomic_flag_works = NULL;
8683#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +00008684
Victor Stinnerdaf45552013-08-28 00:53:59 +02008685#ifdef MS_WINDOWS
8686 flags |= O_NOINHERIT;
8687#elif defined(O_CLOEXEC)
8688 flags |= O_CLOEXEC;
8689#endif
8690
Steve Dowerb82e17e2019-05-23 08:45:22 -07008691 if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
8692 return -1;
8693 }
8694
Steve Dower8fc89802015-04-12 00:26:27 -04008695 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008696 do {
8697 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008698#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07008699 fd = _wopen(path->wide, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008700#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07008701#ifdef HAVE_OPENAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008702 if (dir_fd != DEFAULT_DIR_FD)
8703 fd = openat(dir_fd, path->narrow, flags, mode);
8704 else
Steve Dower6230aaf2016-09-09 09:03:15 -07008705#endif /* HAVE_OPENAT */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008706 fd = open(path->narrow, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008707#endif /* !MS_WINDOWS */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008708 Py_END_ALLOW_THREADS
8709 } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04008710 _Py_END_SUPPRESS_IPH
Guido van Rossum687dd131993-05-17 08:34:16 +00008711
Victor Stinnerd3ffd322015-09-15 10:11:03 +02008712 if (fd < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008713 if (!async_err)
8714 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Larry Hastings2f936352014-08-05 14:04:04 +10008715 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008716 }
8717
Victor Stinnerdaf45552013-08-28 00:53:59 +02008718#ifndef MS_WINDOWS
8719 if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
8720 close(fd);
Larry Hastings2f936352014-08-05 14:04:04 +10008721 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008722 }
8723#endif
8724
Larry Hastings2f936352014-08-05 14:04:04 +10008725 return fd;
8726}
8727
8728
8729/*[clinic input]
8730os.close
8731
8732 fd: int
8733
8734Close a file descriptor.
8735[clinic start generated code]*/
8736
Barry Warsaw53699e91996-12-10 23:23:01 +00008737static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008738os_close_impl(PyObject *module, int fd)
8739/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00008740{
Larry Hastings2f936352014-08-05 14:04:04 +10008741 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008742 /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
8743 * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
8744 * for more details.
8745 */
Victor Stinner8c62be82010-05-06 00:08:46 +00008746 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008747 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008748 res = close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04008749 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008750 Py_END_ALLOW_THREADS
8751 if (res < 0)
8752 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008753 Py_RETURN_NONE;
Guido van Rossum687dd131993-05-17 08:34:16 +00008754}
8755
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008756
Jakub Kulíke20134f2019-09-11 17:11:57 +02008757#ifdef HAVE_FDWALK
8758static int
8759_fdwalk_close_func(void *lohi, int fd)
8760{
8761 int lo = ((int *)lohi)[0];
8762 int hi = ((int *)lohi)[1];
8763
Victor Stinner162c5672020-04-24 12:00:51 +02008764 if (fd >= hi) {
Jakub Kulíke20134f2019-09-11 17:11:57 +02008765 return 1;
Victor Stinner162c5672020-04-24 12:00:51 +02008766 }
8767 else if (fd >= lo) {
8768 /* Ignore errors */
8769 (void)close(fd);
8770 }
Jakub Kulíke20134f2019-09-11 17:11:57 +02008771 return 0;
8772}
8773#endif /* HAVE_FDWALK */
8774
Larry Hastings2f936352014-08-05 14:04:04 +10008775/*[clinic input]
8776os.closerange
8777
8778 fd_low: int
8779 fd_high: int
8780 /
8781
8782Closes all file descriptors in [fd_low, fd_high), ignoring errors.
8783[clinic start generated code]*/
8784
Larry Hastings2f936352014-08-05 14:04:04 +10008785static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008786os_closerange_impl(PyObject *module, int fd_low, int fd_high)
8787/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008788{
Jakub Kulíke20134f2019-09-11 17:11:57 +02008789#ifdef HAVE_FDWALK
8790 int lohi[2];
Jakub Kulíke20134f2019-09-11 17:11:57 +02008791#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00008792 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008793 _Py_BEGIN_SUPPRESS_IPH
Jakub Kulíke20134f2019-09-11 17:11:57 +02008794#ifdef HAVE_FDWALK
8795 lohi[0] = Py_MAX(fd_low, 0);
8796 lohi[1] = fd_high;
8797 fdwalk(_fdwalk_close_func, lohi);
8798#else
Victor Stinner162c5672020-04-24 12:00:51 +02008799 fd_low = Py_MAX(fd_low, 0);
8800#ifdef __FreeBSD__
8801 if (fd_high >= sysconf(_SC_OPEN_MAX)) {
8802 /* Any errors encountered while closing file descriptors are ignored */
8803 closefrom(fd_low);
8804 }
8805 else
8806#endif
8807 {
8808 for (int i = fd_low; i < fd_high; i++) {
8809 /* Ignore errors */
8810 (void)close(i);
8811 }
8812 }
Jakub Kulíke20134f2019-09-11 17:11:57 +02008813#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008814 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008815 Py_END_ALLOW_THREADS
8816 Py_RETURN_NONE;
Christian Heimesfdab48e2008-01-20 09:06:41 +00008817}
8818
8819
Larry Hastings2f936352014-08-05 14:04:04 +10008820/*[clinic input]
8821os.dup -> int
8822
8823 fd: int
8824 /
8825
8826Return a duplicate of a file descriptor.
8827[clinic start generated code]*/
8828
Larry Hastings2f936352014-08-05 14:04:04 +10008829static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008830os_dup_impl(PyObject *module, int fd)
8831/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008832{
8833 return _Py_dup(fd);
Guido van Rossum687dd131993-05-17 08:34:16 +00008834}
8835
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008836
Larry Hastings2f936352014-08-05 14:04:04 +10008837/*[clinic input]
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008838os.dup2 -> int
Larry Hastings2f936352014-08-05 14:04:04 +10008839 fd: int
8840 fd2: int
8841 inheritable: bool=True
8842
8843Duplicate file descriptor.
8844[clinic start generated code]*/
8845
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008846static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008847os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008848/*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008849{
Stéphane Wirtel3d86e482018-01-30 07:04:36 +01008850 int res = 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008851#if defined(HAVE_DUP3) && \
8852 !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
8853 /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
Alexey Izbyshevb3caf382018-02-20 10:25:46 +03008854 static int dup3_works = -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008855#endif
8856
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008857 if (fd < 0 || fd2 < 0) {
8858 posix_error();
8859 return -1;
8860 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008861
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008862 /* dup2() can fail with EINTR if the target FD is already open, because it
8863 * then has to be closed. See os_close_impl() for why we don't handle EINTR
8864 * upon close(), and therefore below.
8865 */
Victor Stinnerdaf45552013-08-28 00:53:59 +02008866#ifdef MS_WINDOWS
8867 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008868 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008869 res = dup2(fd, fd2);
Steve Dower8fc89802015-04-12 00:26:27 -04008870 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02008871 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008872 if (res < 0) {
8873 posix_error();
8874 return -1;
8875 }
8876 res = fd2; // msvcrt dup2 returns 0 on success.
Victor Stinnerdaf45552013-08-28 00:53:59 +02008877
8878 /* Character files like console cannot be make non-inheritable */
8879 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8880 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008881 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008882 }
8883
8884#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
8885 Py_BEGIN_ALLOW_THREADS
8886 if (!inheritable)
8887 res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
8888 else
8889 res = dup2(fd, fd2);
8890 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008891 if (res < 0) {
8892 posix_error();
8893 return -1;
8894 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008895
8896#else
8897
8898#ifdef HAVE_DUP3
8899 if (!inheritable && dup3_works != 0) {
8900 Py_BEGIN_ALLOW_THREADS
8901 res = dup3(fd, fd2, O_CLOEXEC);
8902 Py_END_ALLOW_THREADS
8903 if (res < 0) {
8904 if (dup3_works == -1)
8905 dup3_works = (errno != ENOSYS);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008906 if (dup3_works) {
8907 posix_error();
8908 return -1;
8909 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008910 }
8911 }
8912
8913 if (inheritable || dup3_works == 0)
8914 {
8915#endif
8916 Py_BEGIN_ALLOW_THREADS
8917 res = dup2(fd, fd2);
8918 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008919 if (res < 0) {
8920 posix_error();
8921 return -1;
8922 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008923
8924 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8925 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008926 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008927 }
8928#ifdef HAVE_DUP3
8929 }
8930#endif
8931
8932#endif
8933
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008934 return res;
Guido van Rossum687dd131993-05-17 08:34:16 +00008935}
8936
Larry Hastings2f936352014-08-05 14:04:04 +10008937
Ross Lagerwall7807c352011-03-17 20:20:30 +02008938#ifdef HAVE_LOCKF
Larry Hastings2f936352014-08-05 14:04:04 +10008939/*[clinic input]
8940os.lockf
8941
8942 fd: int
8943 An open file descriptor.
8944 command: int
8945 One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
8946 length: Py_off_t
8947 The number of bytes to lock, starting at the current position.
8948 /
8949
8950Apply, test or remove a POSIX lock on an open file descriptor.
8951
8952[clinic start generated code]*/
8953
Larry Hastings2f936352014-08-05 14:04:04 +10008954static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008955os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
8956/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008957{
8958 int res;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008959
Saiyang Gou7514f4f2020-02-12 23:47:42 -08008960 if (PySys_Audit("os.lockf", "iiL", fd, command, length) < 0) {
8961 return NULL;
8962 }
8963
Ross Lagerwall7807c352011-03-17 20:20:30 +02008964 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008965 res = lockf(fd, command, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008966 Py_END_ALLOW_THREADS
8967
8968 if (res < 0)
8969 return posix_error();
8970
8971 Py_RETURN_NONE;
8972}
Larry Hastings2f936352014-08-05 14:04:04 +10008973#endif /* HAVE_LOCKF */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008974
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008975
Larry Hastings2f936352014-08-05 14:04:04 +10008976/*[clinic input]
8977os.lseek -> Py_off_t
8978
8979 fd: int
8980 position: Py_off_t
8981 how: int
8982 /
8983
8984Set the position of a file descriptor. Return the new position.
8985
8986Return the new cursor position in number of bytes
8987relative to the beginning of the file.
8988[clinic start generated code]*/
8989
Larry Hastings2f936352014-08-05 14:04:04 +10008990static Py_off_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008991os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
8992/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008993{
8994 Py_off_t result;
8995
Guido van Rossum687dd131993-05-17 08:34:16 +00008996#ifdef SEEK_SET
Victor Stinner8c62be82010-05-06 00:08:46 +00008997 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
8998 switch (how) {
Larry Hastings2f936352014-08-05 14:04:04 +10008999 case 0: how = SEEK_SET; break;
9000 case 1: how = SEEK_CUR; break;
9001 case 2: how = SEEK_END; break;
Victor Stinner8c62be82010-05-06 00:08:46 +00009002 }
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00009003#endif /* SEEK_END */
Guido van Rossum94f6f721999-01-06 18:42:14 +00009004
Victor Stinner8c62be82010-05-06 00:08:46 +00009005 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009006 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner14b9b112013-06-25 00:37:25 +02009007#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009008 result = _lseeki64(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00009009#else
Larry Hastings2f936352014-08-05 14:04:04 +10009010 result = lseek(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00009011#endif
Steve Dower8fc89802015-04-12 00:26:27 -04009012 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00009013 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009014 if (result < 0)
9015 posix_error();
Guido van Rossum94f6f721999-01-06 18:42:14 +00009016
Larry Hastings2f936352014-08-05 14:04:04 +10009017 return result;
Guido van Rossum687dd131993-05-17 08:34:16 +00009018}
9019
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009020
Larry Hastings2f936352014-08-05 14:04:04 +10009021/*[clinic input]
9022os.read
9023 fd: int
9024 length: Py_ssize_t
9025 /
9026
9027Read from a file descriptor. Returns a bytes object.
9028[clinic start generated code]*/
9029
Larry Hastings2f936352014-08-05 14:04:04 +10009030static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009031os_read_impl(PyObject *module, int fd, Py_ssize_t length)
9032/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009033{
Victor Stinner8c62be82010-05-06 00:08:46 +00009034 Py_ssize_t n;
9035 PyObject *buffer;
Larry Hastings2f936352014-08-05 14:04:04 +10009036
9037 if (length < 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00009038 errno = EINVAL;
9039 return posix_error();
9040 }
Larry Hastings2f936352014-08-05 14:04:04 +10009041
Victor Stinner9a0d7a72018-11-22 15:03:40 +01009042 length = Py_MIN(length, _PY_READ_MAX);
Larry Hastings2f936352014-08-05 14:04:04 +10009043
9044 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Victor Stinner8c62be82010-05-06 00:08:46 +00009045 if (buffer == NULL)
9046 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009047
Victor Stinner66aab0c2015-03-19 22:53:20 +01009048 n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
9049 if (n == -1) {
Victor Stinner8c62be82010-05-06 00:08:46 +00009050 Py_DECREF(buffer);
Victor Stinner66aab0c2015-03-19 22:53:20 +01009051 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00009052 }
Larry Hastings2f936352014-08-05 14:04:04 +10009053
9054 if (n != length)
Victor Stinner8c62be82010-05-06 00:08:46 +00009055 _PyBytes_Resize(&buffer, n);
Larry Hastings2f936352014-08-05 14:04:04 +10009056
Victor Stinner8c62be82010-05-06 00:08:46 +00009057 return buffer;
Guido van Rossum687dd131993-05-17 08:34:16 +00009058}
9059
Ross Lagerwall7807c352011-03-17 20:20:30 +02009060#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009061 || defined(__APPLE__))) \
9062 || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
9063 || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
9064static int
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009065iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009066{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009067 Py_ssize_t i, j;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009068
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009069 *iov = PyMem_New(struct iovec, cnt);
9070 if (*iov == NULL) {
9071 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01009072 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009073 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009074
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009075 *buf = PyMem_New(Py_buffer, cnt);
9076 if (*buf == NULL) {
9077 PyMem_Del(*iov);
9078 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01009079 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009080 }
9081
9082 for (i = 0; i < cnt; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02009083 PyObject *item = PySequence_GetItem(seq, i);
9084 if (item == NULL)
9085 goto fail;
9086 if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
9087 Py_DECREF(item);
9088 goto fail;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009089 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02009090 Py_DECREF(item);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009091 (*iov)[i].iov_base = (*buf)[i].buf;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009092 (*iov)[i].iov_len = (*buf)[i].len;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009093 }
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009094 return 0;
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02009095
9096fail:
9097 PyMem_Del(*iov);
9098 for (j = 0; j < i; j++) {
9099 PyBuffer_Release(&(*buf)[j]);
9100 }
9101 PyMem_Del(*buf);
Victor Stinner57ddf782014-01-08 15:21:28 +01009102 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009103}
9104
9105static void
9106iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
9107{
9108 int i;
9109 PyMem_Del(iov);
9110 for (i = 0; i < cnt; i++) {
9111 PyBuffer_Release(&buf[i]);
9112 }
9113 PyMem_Del(buf);
9114}
9115#endif
9116
Larry Hastings2f936352014-08-05 14:04:04 +10009117
Ross Lagerwall7807c352011-03-17 20:20:30 +02009118#ifdef HAVE_READV
Larry Hastings2f936352014-08-05 14:04:04 +10009119/*[clinic input]
9120os.readv -> Py_ssize_t
9121
9122 fd: int
9123 buffers: object
9124 /
9125
9126Read from a file descriptor fd into an iterable of buffers.
9127
9128The buffers should be mutable buffers accepting bytes.
9129readv will transfer data into each buffer until it is full
9130and then move on to the next buffer in the sequence to hold
9131the rest of the data.
9132
9133readv returns the total number of bytes read,
9134which may be less than the total capacity of all the buffers.
9135[clinic start generated code]*/
9136
Larry Hastings2f936352014-08-05 14:04:04 +10009137static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009138os_readv_impl(PyObject *module, int fd, PyObject *buffers)
9139/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009140{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009141 Py_ssize_t cnt, n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009142 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009143 struct iovec *iov;
9144 Py_buffer *buf;
9145
Larry Hastings2f936352014-08-05 14:04:04 +10009146 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009147 PyErr_SetString(PyExc_TypeError,
9148 "readv() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009149 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009150 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02009151
Larry Hastings2f936352014-08-05 14:04:04 +10009152 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009153 if (cnt < 0)
9154 return -1;
Larry Hastings2f936352014-08-05 14:04:04 +10009155
9156 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
9157 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009158
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009159 do {
9160 Py_BEGIN_ALLOW_THREADS
9161 n = readv(fd, iov, cnt);
9162 Py_END_ALLOW_THREADS
9163 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009164
9165 iov_cleanup(iov, buf, cnt);
Larry Hastings2f936352014-08-05 14:04:04 +10009166 if (n < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009167 if (!async_err)
9168 posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10009169 return -1;
9170 }
Victor Stinner57ddf782014-01-08 15:21:28 +01009171
Larry Hastings2f936352014-08-05 14:04:04 +10009172 return n;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009173}
Larry Hastings2f936352014-08-05 14:04:04 +10009174#endif /* HAVE_READV */
9175
Ross Lagerwall7807c352011-03-17 20:20:30 +02009176
9177#ifdef HAVE_PREAD
Larry Hastings2f936352014-08-05 14:04:04 +10009178/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10009179os.pread
9180
9181 fd: int
Dong-hee Naad7736f2019-09-25 14:47:04 +09009182 length: Py_ssize_t
Larry Hastings2f936352014-08-05 14:04:04 +10009183 offset: Py_off_t
9184 /
9185
9186Read a number of bytes from a file descriptor starting at a particular offset.
9187
9188Read length bytes from file descriptor fd, starting at offset bytes from
9189the beginning of the file. The file offset remains unchanged.
9190[clinic start generated code]*/
9191
Larry Hastings2f936352014-08-05 14:04:04 +10009192static PyObject *
Dong-hee Naad7736f2019-09-25 14:47:04 +09009193os_pread_impl(PyObject *module, int fd, Py_ssize_t length, Py_off_t offset)
9194/*[clinic end generated code: output=3f875c1eef82e32f input=85cb4a5589627144]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009195{
Ross Lagerwall7807c352011-03-17 20:20:30 +02009196 Py_ssize_t n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009197 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009198 PyObject *buffer;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009199
Larry Hastings2f936352014-08-05 14:04:04 +10009200 if (length < 0) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009201 errno = EINVAL;
9202 return posix_error();
9203 }
Larry Hastings2f936352014-08-05 14:04:04 +10009204 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02009205 if (buffer == NULL)
9206 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009207
9208 do {
9209 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009210 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009211 n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009212 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009213 Py_END_ALLOW_THREADS
9214 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9215
Ross Lagerwall7807c352011-03-17 20:20:30 +02009216 if (n < 0) {
9217 Py_DECREF(buffer);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009218 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009219 }
Larry Hastings2f936352014-08-05 14:04:04 +10009220 if (n != length)
Ross Lagerwall7807c352011-03-17 20:20:30 +02009221 _PyBytes_Resize(&buffer, n);
9222 return buffer;
9223}
Larry Hastings2f936352014-08-05 14:04:04 +10009224#endif /* HAVE_PREAD */
Ross Lagerwall7807c352011-03-17 20:20:30 +02009225
Pablo Galindo4defba32018-01-27 16:16:37 +00009226#if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
9227/*[clinic input]
9228os.preadv -> Py_ssize_t
9229
9230 fd: int
9231 buffers: object
9232 offset: Py_off_t
9233 flags: int = 0
9234 /
9235
9236Reads from a file descriptor into a number of mutable bytes-like objects.
9237
9238Combines the functionality of readv() and pread(). As readv(), it will
9239transfer data into each buffer until it is full and then move on to the next
9240buffer in the sequence to hold the rest of the data. Its fourth argument,
9241specifies the file offset at which the input operation is to be performed. It
9242will return the total number of bytes read (which can be less than the total
9243capacity of all the objects).
9244
9245The flags argument contains a bitwise OR of zero or more of the following flags:
9246
9247- RWF_HIPRI
9248- RWF_NOWAIT
9249
9250Using non-zero flags requires Linux 4.6 or newer.
9251[clinic start generated code]*/
9252
9253static Py_ssize_t
9254os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9255 int flags)
9256/*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
9257{
9258 Py_ssize_t cnt, n;
9259 int async_err = 0;
9260 struct iovec *iov;
9261 Py_buffer *buf;
9262
9263 if (!PySequence_Check(buffers)) {
9264 PyErr_SetString(PyExc_TypeError,
9265 "preadv2() arg 2 must be a sequence");
9266 return -1;
9267 }
9268
9269 cnt = PySequence_Size(buffers);
9270 if (cnt < 0) {
9271 return -1;
9272 }
9273
9274#ifndef HAVE_PREADV2
9275 if(flags != 0) {
9276 argument_unavailable_error("preadv2", "flags");
9277 return -1;
9278 }
9279#endif
9280
9281 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
9282 return -1;
9283 }
9284#ifdef HAVE_PREADV2
9285 do {
9286 Py_BEGIN_ALLOW_THREADS
9287 _Py_BEGIN_SUPPRESS_IPH
9288 n = preadv2(fd, iov, cnt, offset, flags);
9289 _Py_END_SUPPRESS_IPH
9290 Py_END_ALLOW_THREADS
9291 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9292#else
9293 do {
9294 Py_BEGIN_ALLOW_THREADS
9295 _Py_BEGIN_SUPPRESS_IPH
9296 n = preadv(fd, iov, cnt, offset);
9297 _Py_END_SUPPRESS_IPH
9298 Py_END_ALLOW_THREADS
9299 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9300#endif
9301
9302 iov_cleanup(iov, buf, cnt);
9303 if (n < 0) {
9304 if (!async_err) {
9305 posix_error();
9306 }
9307 return -1;
9308 }
9309
9310 return n;
9311}
9312#endif /* HAVE_PREADV */
9313
Larry Hastings2f936352014-08-05 14:04:04 +10009314
9315/*[clinic input]
9316os.write -> Py_ssize_t
9317
9318 fd: int
9319 data: Py_buffer
9320 /
9321
9322Write a bytes object to a file descriptor.
9323[clinic start generated code]*/
9324
Larry Hastings2f936352014-08-05 14:04:04 +10009325static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009326os_write_impl(PyObject *module, int fd, Py_buffer *data)
9327/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009328{
Victor Stinner66aab0c2015-03-19 22:53:20 +01009329 return _Py_write(fd, data->buf, data->len);
Ross Lagerwall7807c352011-03-17 20:20:30 +02009330}
9331
9332#ifdef HAVE_SENDFILE
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009333#ifdef __APPLE__
9334/*[clinic input]
9335os.sendfile
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009336
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009337 out_fd: int
9338 in_fd: int
9339 offset: Py_off_t
9340 count as sbytes: Py_off_t
9341 headers: object(c_default="NULL") = ()
9342 trailers: object(c_default="NULL") = ()
9343 flags: int = 0
9344
9345Copy count bytes from file descriptor in_fd to file descriptor out_fd.
9346[clinic start generated code]*/
9347
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009348static PyObject *
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009349os_sendfile_impl(PyObject *module, int out_fd, int in_fd, Py_off_t offset,
9350 Py_off_t sbytes, PyObject *headers, PyObject *trailers,
9351 int flags)
9352/*[clinic end generated code: output=81c4bcd143f5c82b input=b0d72579d4c69afa]*/
9353#elif defined(__FreeBSD__) || defined(__DragonFly__)
9354/*[clinic input]
9355os.sendfile
9356
9357 out_fd: int
9358 in_fd: int
9359 offset: Py_off_t
9360 count: Py_ssize_t
9361 headers: object(c_default="NULL") = ()
9362 trailers: object(c_default="NULL") = ()
9363 flags: int = 0
9364
9365Copy count bytes from file descriptor in_fd to file descriptor out_fd.
9366[clinic start generated code]*/
9367
9368static PyObject *
9369os_sendfile_impl(PyObject *module, int out_fd, int in_fd, Py_off_t offset,
9370 Py_ssize_t count, PyObject *headers, PyObject *trailers,
9371 int flags)
9372/*[clinic end generated code: output=329ea009bdd55afc input=338adb8ff84ae8cd]*/
9373#else
9374/*[clinic input]
9375os.sendfile
9376
9377 out_fd: int
9378 in_fd: int
9379 offset as offobj: object
9380 count: Py_ssize_t
9381
9382Copy count bytes from file descriptor in_fd to file descriptor out_fd.
9383[clinic start generated code]*/
9384
9385static PyObject *
9386os_sendfile_impl(PyObject *module, int out_fd, int in_fd, PyObject *offobj,
9387 Py_ssize_t count)
9388/*[clinic end generated code: output=ae81216e40f167d8 input=76d64058c74477ba]*/
9389#endif
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009390{
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009391 Py_ssize_t ret;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009392 int async_err = 0;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009393
9394#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
9395#ifndef __APPLE__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009396 off_t sbytes;
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009397#endif
9398 Py_buffer *hbuf, *tbuf;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009399 struct sf_hdtr sf;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009400
Victor Stinner6ce0dbf2013-07-07 16:32:36 +02009401 sf.headers = NULL;
9402 sf.trailers = NULL;
9403
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009404 if (headers != NULL) {
9405 if (!PySequence_Check(headers)) {
9406 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009407 "sendfile() headers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009408 return NULL;
9409 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009410 Py_ssize_t i = PySequence_Size(headers);
9411 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009412 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009413 if (i > INT_MAX) {
9414 PyErr_SetString(PyExc_OverflowError,
9415 "sendfile() header is too large");
9416 return NULL;
9417 }
9418 if (i > 0) {
9419 sf.hdr_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009420 if (iov_setup(&(sf.headers), &hbuf,
9421 headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009422 return NULL;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009423#ifdef __APPLE__
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009424 for (i = 0; i < sf.hdr_cnt; i++) {
9425 Py_ssize_t blen = sf.headers[i].iov_len;
9426# define OFF_T_MAX 0x7fffffffffffffff
9427 if (sbytes >= OFF_T_MAX - blen) {
9428 PyErr_SetString(PyExc_OverflowError,
9429 "sendfile() header is too large");
9430 return NULL;
9431 }
9432 sbytes += blen;
9433 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009434#endif
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009435 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009436 }
9437 }
9438 if (trailers != NULL) {
9439 if (!PySequence_Check(trailers)) {
9440 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009441 "sendfile() trailers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009442 return NULL;
9443 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009444 Py_ssize_t i = PySequence_Size(trailers);
9445 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009446 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009447 if (i > INT_MAX) {
9448 PyErr_SetString(PyExc_OverflowError,
9449 "sendfile() trailer is too large");
9450 return NULL;
9451 }
9452 if (i > 0) {
9453 sf.trl_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009454 if (iov_setup(&(sf.trailers), &tbuf,
9455 trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009456 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009457 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009458 }
9459 }
9460
Steve Dower8fc89802015-04-12 00:26:27 -04009461 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009462 do {
9463 Py_BEGIN_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009464#ifdef __APPLE__
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009465 ret = sendfile(in_fd, out_fd, offset, &sbytes, &sf, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009466#else
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009467 ret = sendfile(in_fd, out_fd, offset, count, &sf, &sbytes, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009468#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009469 Py_END_ALLOW_THREADS
9470 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04009471 _Py_END_SUPPRESS_IPH
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009472
9473 if (sf.headers != NULL)
9474 iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
9475 if (sf.trailers != NULL)
9476 iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
9477
9478 if (ret < 0) {
9479 if ((errno == EAGAIN) || (errno == EBUSY)) {
9480 if (sbytes != 0) {
9481 // some data has been sent
9482 goto done;
9483 }
9484 else {
9485 // no data has been sent; upper application is supposed
9486 // to retry on EAGAIN or EBUSY
9487 return posix_error();
9488 }
9489 }
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009490 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009491 }
9492 goto done;
9493
9494done:
9495 #if !defined(HAVE_LARGEFILE_SUPPORT)
9496 return Py_BuildValue("l", sbytes);
9497 #else
9498 return Py_BuildValue("L", sbytes);
9499 #endif
9500
9501#else
Benjamin Peterson840ef8f2016-09-07 14:45:10 -07009502#ifdef __linux__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009503 if (offobj == Py_None) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009504 do {
9505 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009506 ret = sendfile(out_fd, in_fd, NULL, count);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009507 Py_END_ALLOW_THREADS
9508 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009509 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009510 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodola'ff1a7352011-04-19 09:47:16 +02009511 return Py_BuildValue("n", ret);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009512 }
9513#endif
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009514 off_t offset;
Larry Hastings2f936352014-08-05 14:04:04 +10009515 if (!Py_off_t_converter(offobj, &offset))
Antoine Pitroudcc20b82011-02-26 13:38:35 +00009516 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009517
9518 do {
9519 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009520 ret = sendfile(out_fd, in_fd, &offset, count);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009521 Py_END_ALLOW_THREADS
9522 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009523 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009524 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009525 return Py_BuildValue("n", ret);
9526#endif
9527}
Larry Hastings2f936352014-08-05 14:04:04 +10009528#endif /* HAVE_SENDFILE */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009529
Larry Hastings2f936352014-08-05 14:04:04 +10009530
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009531#if defined(__APPLE__)
9532/*[clinic input]
9533os._fcopyfile
9534
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009535 in_fd: int
9536 out_fd: int
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009537 flags: int
9538 /
9539
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009540Efficiently copy content or metadata of 2 regular file descriptors (macOS).
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009541[clinic start generated code]*/
9542
9543static PyObject *
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009544os__fcopyfile_impl(PyObject *module, int in_fd, int out_fd, int flags)
9545/*[clinic end generated code: output=c9d1a35a992e401b input=1e34638a86948795]*/
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009546{
9547 int ret;
9548
9549 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009550 ret = fcopyfile(in_fd, out_fd, NULL, flags);
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009551 Py_END_ALLOW_THREADS
9552 if (ret < 0)
9553 return posix_error();
9554 Py_RETURN_NONE;
9555}
9556#endif
9557
9558
Larry Hastings2f936352014-08-05 14:04:04 +10009559/*[clinic input]
9560os.fstat
9561
9562 fd : int
9563
9564Perform a stat system call on the given file descriptor.
9565
9566Like stat(), but for an open file descriptor.
9567Equivalent to os.stat(fd).
9568[clinic start generated code]*/
9569
Larry Hastings2f936352014-08-05 14:04:04 +10009570static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009571os_fstat_impl(PyObject *module, int fd)
9572/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009573{
Victor Stinner8c62be82010-05-06 00:08:46 +00009574 STRUCT_STAT st;
9575 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009576 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009577
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009578 do {
9579 Py_BEGIN_ALLOW_THREADS
9580 res = FSTAT(fd, &st);
9581 Py_END_ALLOW_THREADS
9582 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner8c62be82010-05-06 00:08:46 +00009583 if (res != 0) {
Martin v. Löwis14694662006-02-03 12:54:16 +00009584#ifdef MS_WINDOWS
Victor Stinnerb024e842012-10-31 22:24:06 +01009585 return PyErr_SetFromWindowsErr(0);
Martin v. Löwis14694662006-02-03 12:54:16 +00009586#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009587 return (!async_err) ? posix_error() : NULL;
Martin v. Löwis14694662006-02-03 12:54:16 +00009588#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00009589 }
Tim Peters5aa91602002-01-30 05:46:57 +00009590
Victor Stinner1c2fa782020-05-10 11:05:29 +02009591 return _pystat_fromstructstat(module, &st);
Guido van Rossum687dd131993-05-17 08:34:16 +00009592}
9593
Larry Hastings2f936352014-08-05 14:04:04 +10009594
9595/*[clinic input]
9596os.isatty -> bool
9597 fd: int
9598 /
9599
9600Return True if the fd is connected to a terminal.
9601
9602Return True if the file descriptor is an open file descriptor
9603connected to the slave end of a terminal.
9604[clinic start generated code]*/
9605
Larry Hastings2f936352014-08-05 14:04:04 +10009606static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009607os_isatty_impl(PyObject *module, int fd)
9608/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009609{
Steve Dower8fc89802015-04-12 00:26:27 -04009610 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -04009611 _Py_BEGIN_SUPPRESS_IPH
9612 return_value = isatty(fd);
9613 _Py_END_SUPPRESS_IPH
9614 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +10009615}
9616
9617
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009618#ifdef HAVE_PIPE
Larry Hastings2f936352014-08-05 14:04:04 +10009619/*[clinic input]
9620os.pipe
9621
9622Create a pipe.
9623
9624Returns a tuple of two file descriptors:
9625 (read_fd, write_fd)
9626[clinic start generated code]*/
9627
Larry Hastings2f936352014-08-05 14:04:04 +10009628static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009629os_pipe_impl(PyObject *module)
9630/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00009631{
Victor Stinner8c62be82010-05-06 00:08:46 +00009632 int fds[2];
Victor Stinnerdaf45552013-08-28 00:53:59 +02009633#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00009634 HANDLE read, write;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009635 SECURITY_ATTRIBUTES attr;
Victor Stinner8c62be82010-05-06 00:08:46 +00009636 BOOL ok;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009637#else
9638 int res;
9639#endif
9640
9641#ifdef MS_WINDOWS
9642 attr.nLength = sizeof(attr);
9643 attr.lpSecurityDescriptor = NULL;
9644 attr.bInheritHandle = FALSE;
9645
9646 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08009647 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009648 ok = CreatePipe(&read, &write, &attr, 0);
9649 if (ok) {
Benjamin Petersonca470632016-09-06 13:47:26 -07009650 fds[0] = _open_osfhandle((intptr_t)read, _O_RDONLY);
9651 fds[1] = _open_osfhandle((intptr_t)write, _O_WRONLY);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009652 if (fds[0] == -1 || fds[1] == -1) {
9653 CloseHandle(read);
9654 CloseHandle(write);
9655 ok = 0;
9656 }
9657 }
Steve Dowerc3630612016-11-19 18:41:16 -08009658 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009659 Py_END_ALLOW_THREADS
9660
Victor Stinner8c62be82010-05-06 00:08:46 +00009661 if (!ok)
Victor Stinnerb024e842012-10-31 22:24:06 +01009662 return PyErr_SetFromWindowsErr(0);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009663#else
9664
9665#ifdef HAVE_PIPE2
9666 Py_BEGIN_ALLOW_THREADS
9667 res = pipe2(fds, O_CLOEXEC);
9668 Py_END_ALLOW_THREADS
9669
9670 if (res != 0 && errno == ENOSYS)
9671 {
9672#endif
9673 Py_BEGIN_ALLOW_THREADS
9674 res = pipe(fds);
9675 Py_END_ALLOW_THREADS
9676
9677 if (res == 0) {
9678 if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
9679 close(fds[0]);
9680 close(fds[1]);
9681 return NULL;
9682 }
9683 if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
9684 close(fds[0]);
9685 close(fds[1]);
9686 return NULL;
9687 }
9688 }
9689#ifdef HAVE_PIPE2
9690 }
9691#endif
9692
9693 if (res != 0)
9694 return PyErr_SetFromErrno(PyExc_OSError);
9695#endif /* !MS_WINDOWS */
9696 return Py_BuildValue("(ii)", fds[0], fds[1]);
Guido van Rossum687dd131993-05-17 08:34:16 +00009697}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009698#endif /* HAVE_PIPE */
9699
Larry Hastings2f936352014-08-05 14:04:04 +10009700
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009701#ifdef HAVE_PIPE2
Larry Hastings2f936352014-08-05 14:04:04 +10009702/*[clinic input]
9703os.pipe2
9704
9705 flags: int
9706 /
9707
9708Create a pipe with flags set atomically.
9709
9710Returns a tuple of two file descriptors:
9711 (read_fd, write_fd)
9712
9713flags can be constructed by ORing together one or more of these values:
9714O_NONBLOCK, O_CLOEXEC.
9715[clinic start generated code]*/
9716
Larry Hastings2f936352014-08-05 14:04:04 +10009717static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009718os_pipe2_impl(PyObject *module, int flags)
9719/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009720{
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009721 int fds[2];
9722 int res;
9723
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009724 res = pipe2(fds, flags);
9725 if (res != 0)
9726 return posix_error();
9727 return Py_BuildValue("(ii)", fds[0], fds[1]);
9728}
9729#endif /* HAVE_PIPE2 */
9730
Larry Hastings2f936352014-08-05 14:04:04 +10009731
Ross Lagerwall7807c352011-03-17 20:20:30 +02009732#ifdef HAVE_WRITEV
Larry Hastings2f936352014-08-05 14:04:04 +10009733/*[clinic input]
9734os.writev -> Py_ssize_t
9735 fd: int
9736 buffers: object
9737 /
9738
9739Iterate over buffers, and write the contents of each to a file descriptor.
9740
9741Returns the total number of bytes written.
9742buffers must be a sequence of bytes-like objects.
9743[clinic start generated code]*/
9744
Larry Hastings2f936352014-08-05 14:04:04 +10009745static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009746os_writev_impl(PyObject *module, int fd, PyObject *buffers)
9747/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009748{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009749 Py_ssize_t cnt;
Larry Hastings2f936352014-08-05 14:04:04 +10009750 Py_ssize_t result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009751 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009752 struct iovec *iov;
9753 Py_buffer *buf;
Larry Hastings2f936352014-08-05 14:04:04 +10009754
9755 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009756 PyErr_SetString(PyExc_TypeError,
9757 "writev() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009758 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009759 }
Larry Hastings2f936352014-08-05 14:04:04 +10009760 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009761 if (cnt < 0)
9762 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009763
Larry Hastings2f936352014-08-05 14:04:04 +10009764 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9765 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009766 }
9767
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009768 do {
9769 Py_BEGIN_ALLOW_THREADS
9770 result = writev(fd, iov, cnt);
9771 Py_END_ALLOW_THREADS
9772 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009773
9774 iov_cleanup(iov, buf, cnt);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009775 if (result < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009776 posix_error();
Victor Stinner57ddf782014-01-08 15:21:28 +01009777
Georg Brandl306336b2012-06-24 12:55:33 +02009778 return result;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009779}
Larry Hastings2f936352014-08-05 14:04:04 +10009780#endif /* HAVE_WRITEV */
9781
9782
9783#ifdef HAVE_PWRITE
9784/*[clinic input]
9785os.pwrite -> Py_ssize_t
9786
9787 fd: int
9788 buffer: Py_buffer
9789 offset: Py_off_t
9790 /
9791
9792Write bytes to a file descriptor starting at a particular offset.
9793
9794Write buffer to fd, starting at offset bytes from the beginning of
9795the file. Returns the number of bytes writte. Does not change the
9796current file offset.
9797[clinic start generated code]*/
9798
Larry Hastings2f936352014-08-05 14:04:04 +10009799static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009800os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
9801/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009802{
9803 Py_ssize_t size;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009804 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009805
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009806 do {
9807 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009808 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009809 size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009810 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009811 Py_END_ALLOW_THREADS
9812 } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +10009813
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009814 if (size < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009815 posix_error();
9816 return size;
9817}
9818#endif /* HAVE_PWRITE */
9819
Pablo Galindo4defba32018-01-27 16:16:37 +00009820#if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
9821/*[clinic input]
9822os.pwritev -> Py_ssize_t
9823
9824 fd: int
9825 buffers: object
9826 offset: Py_off_t
9827 flags: int = 0
9828 /
9829
9830Writes the contents of bytes-like objects to a file descriptor at a given offset.
9831
9832Combines the functionality of writev() and pwrite(). All buffers must be a sequence
9833of bytes-like objects. Buffers are processed in array order. Entire contents of first
9834buffer is written before proceeding to second, and so on. The operating system may
9835set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
9836This function writes the contents of each object to the file descriptor and returns
9837the total number of bytes written.
9838
9839The flags argument contains a bitwise OR of zero or more of the following flags:
9840
9841- RWF_DSYNC
9842- RWF_SYNC
YoSTEALTH76ef2552020-05-27 15:32:22 -06009843- RWF_APPEND
Pablo Galindo4defba32018-01-27 16:16:37 +00009844
9845Using non-zero flags requires Linux 4.7 or newer.
9846[clinic start generated code]*/
9847
9848static Py_ssize_t
9849os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9850 int flags)
YoSTEALTH76ef2552020-05-27 15:32:22 -06009851/*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=35358c327e1a2a8e]*/
Pablo Galindo4defba32018-01-27 16:16:37 +00009852{
9853 Py_ssize_t cnt;
9854 Py_ssize_t result;
9855 int async_err = 0;
9856 struct iovec *iov;
9857 Py_buffer *buf;
9858
9859 if (!PySequence_Check(buffers)) {
9860 PyErr_SetString(PyExc_TypeError,
9861 "pwritev() arg 2 must be a sequence");
9862 return -1;
9863 }
9864
9865 cnt = PySequence_Size(buffers);
9866 if (cnt < 0) {
9867 return -1;
9868 }
9869
9870#ifndef HAVE_PWRITEV2
9871 if(flags != 0) {
9872 argument_unavailable_error("pwritev2", "flags");
9873 return -1;
9874 }
9875#endif
9876
9877 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9878 return -1;
9879 }
9880#ifdef HAVE_PWRITEV2
9881 do {
9882 Py_BEGIN_ALLOW_THREADS
9883 _Py_BEGIN_SUPPRESS_IPH
9884 result = pwritev2(fd, iov, cnt, offset, flags);
9885 _Py_END_SUPPRESS_IPH
9886 Py_END_ALLOW_THREADS
9887 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9888#else
9889 do {
9890 Py_BEGIN_ALLOW_THREADS
9891 _Py_BEGIN_SUPPRESS_IPH
9892 result = pwritev(fd, iov, cnt, offset);
9893 _Py_END_SUPPRESS_IPH
9894 Py_END_ALLOW_THREADS
9895 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9896#endif
9897
9898 iov_cleanup(iov, buf, cnt);
9899 if (result < 0) {
9900 if (!async_err) {
9901 posix_error();
9902 }
9903 return -1;
9904 }
9905
9906 return result;
9907}
9908#endif /* HAVE_PWRITEV */
9909
Pablo Galindoaac4d032019-05-31 19:39:47 +01009910#ifdef HAVE_COPY_FILE_RANGE
9911/*[clinic input]
9912
9913os.copy_file_range
9914 src: int
9915 Source file descriptor.
9916 dst: int
9917 Destination file descriptor.
9918 count: Py_ssize_t
9919 Number of bytes to copy.
9920 offset_src: object = None
9921 Starting offset in src.
9922 offset_dst: object = None
9923 Starting offset in dst.
9924
9925Copy count bytes from one file descriptor to another.
9926
9927If offset_src is None, then src is read from the current position;
9928respectively for offset_dst.
9929[clinic start generated code]*/
9930
9931static PyObject *
9932os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
9933 PyObject *offset_src, PyObject *offset_dst)
9934/*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
9935{
9936 off_t offset_src_val, offset_dst_val;
9937 off_t *p_offset_src = NULL;
9938 off_t *p_offset_dst = NULL;
9939 Py_ssize_t ret;
9940 int async_err = 0;
9941 /* The flags argument is provided to allow
9942 * for future extensions and currently must be to 0. */
9943 int flags = 0;
Pablo Galindo4defba32018-01-27 16:16:37 +00009944
9945
Pablo Galindoaac4d032019-05-31 19:39:47 +01009946 if (count < 0) {
9947 PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
9948 return NULL;
9949 }
9950
9951 if (offset_src != Py_None) {
9952 if (!Py_off_t_converter(offset_src, &offset_src_val)) {
9953 return NULL;
9954 }
9955 p_offset_src = &offset_src_val;
9956 }
9957
9958 if (offset_dst != Py_None) {
9959 if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
9960 return NULL;
9961 }
9962 p_offset_dst = &offset_dst_val;
9963 }
9964
9965 do {
9966 Py_BEGIN_ALLOW_THREADS
9967 ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
9968 Py_END_ALLOW_THREADS
9969 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9970
9971 if (ret < 0) {
9972 return (!async_err) ? posix_error() : NULL;
9973 }
9974
9975 return PyLong_FromSsize_t(ret);
9976}
9977#endif /* HAVE_COPY_FILE_RANGE*/
Larry Hastings2f936352014-08-05 14:04:04 +10009978
9979#ifdef HAVE_MKFIFO
9980/*[clinic input]
9981os.mkfifo
9982
9983 path: path_t
9984 mode: int=0o666
9985 *
9986 dir_fd: dir_fd(requires='mkfifoat')=None
9987
9988Create a "fifo" (a POSIX named pipe).
9989
9990If dir_fd is not None, it should be a file descriptor open to a directory,
9991 and path should be relative; path will then be relative to that directory.
9992dir_fd may not be implemented on your platform.
9993 If it is unavailable, using it will raise a NotImplementedError.
9994[clinic start generated code]*/
9995
Larry Hastings2f936352014-08-05 14:04:04 +10009996static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009997os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
9998/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009999{
10000 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010001 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +100010002
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010003 do {
10004 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +100010005#ifdef HAVE_MKFIFOAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010006 if (dir_fd != DEFAULT_DIR_FD)
10007 result = mkfifoat(dir_fd, path->narrow, mode);
10008 else
Ross Lagerwall7807c352011-03-17 20:20:30 +020010009#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010010 result = mkfifo(path->narrow, mode);
10011 Py_END_ALLOW_THREADS
10012 } while (result != 0 && errno == EINTR &&
10013 !(async_err = PyErr_CheckSignals()));
10014 if (result != 0)
10015 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100010016
10017 Py_RETURN_NONE;
10018}
10019#endif /* HAVE_MKFIFO */
10020
10021
10022#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
10023/*[clinic input]
10024os.mknod
10025
10026 path: path_t
10027 mode: int=0o600
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +020010028 device: dev_t=0
Larry Hastings2f936352014-08-05 14:04:04 +100010029 *
10030 dir_fd: dir_fd(requires='mknodat')=None
10031
10032Create a node in the file system.
10033
10034Create a node in the file system (file, device special file or named pipe)
10035at path. mode specifies both the permissions to use and the
10036type of node to be created, being combined (bitwise OR) with one of
10037S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
10038device defines the newly created device special file (probably using
10039os.makedev()). Otherwise device is ignored.
10040
10041If dir_fd is not None, it should be a file descriptor open to a directory,
10042 and path should be relative; path will then be relative to that directory.
10043dir_fd may not be implemented on your platform.
10044 If it is unavailable, using it will raise a NotImplementedError.
10045[clinic start generated code]*/
10046
Larry Hastings2f936352014-08-05 14:04:04 +100010047static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010048os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
Larry Hastings89964c42015-04-14 18:07:59 -040010049 int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010050/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010051{
10052 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010053 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +100010054
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010055 do {
10056 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +100010057#ifdef HAVE_MKNODAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010058 if (dir_fd != DEFAULT_DIR_FD)
10059 result = mknodat(dir_fd, path->narrow, mode, device);
10060 else
Larry Hastings2f936352014-08-05 14:04:04 +100010061#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010062 result = mknod(path->narrow, mode, device);
10063 Py_END_ALLOW_THREADS
10064 } while (result != 0 && errno == EINTR &&
10065 !(async_err = PyErr_CheckSignals()));
10066 if (result != 0)
10067 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100010068
10069 Py_RETURN_NONE;
10070}
10071#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
10072
10073
10074#ifdef HAVE_DEVICE_MACROS
10075/*[clinic input]
10076os.major -> unsigned_int
10077
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +020010078 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +100010079 /
10080
10081Extracts a device major number from a raw device number.
10082[clinic start generated code]*/
10083
Larry Hastings2f936352014-08-05 14:04:04 +100010084static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010085os_major_impl(PyObject *module, dev_t device)
10086/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010087{
10088 return major(device);
10089}
10090
10091
10092/*[clinic input]
10093os.minor -> unsigned_int
10094
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +020010095 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +100010096 /
10097
10098Extracts a device minor number from a raw device number.
10099[clinic start generated code]*/
10100
Larry Hastings2f936352014-08-05 14:04:04 +100010101static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010102os_minor_impl(PyObject *module, dev_t device)
10103/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010104{
10105 return minor(device);
10106}
10107
10108
10109/*[clinic input]
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +020010110os.makedev -> dev_t
Larry Hastings2f936352014-08-05 14:04:04 +100010111
10112 major: int
10113 minor: int
10114 /
10115
10116Composes a raw device number from the major and minor device numbers.
10117[clinic start generated code]*/
10118
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +020010119static dev_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010120os_makedev_impl(PyObject *module, int major, int minor)
10121/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010122{
10123 return makedev(major, minor);
10124}
10125#endif /* HAVE_DEVICE_MACROS */
10126
10127
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010128#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010129/*[clinic input]
10130os.ftruncate
10131
10132 fd: int
10133 length: Py_off_t
10134 /
10135
10136Truncate a file, specified by file descriptor, to a specific length.
10137[clinic start generated code]*/
10138
Larry Hastings2f936352014-08-05 14:04:04 +100010139static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010140os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
10141/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010142{
10143 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010144 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +100010145
Steve Dowerb82e17e2019-05-23 08:45:22 -070010146 if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
10147 return NULL;
10148 }
10149
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010150 do {
10151 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -040010152 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010153#ifdef MS_WINDOWS
10154 result = _chsize_s(fd, length);
10155#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010156 result = ftruncate(fd, length);
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010157#endif
Steve Dowera1c7e722015-04-12 00:26:43 -040010158 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010159 Py_END_ALLOW_THREADS
10160 } while (result != 0 && errno == EINTR &&
10161 !(async_err = PyErr_CheckSignals()));
10162 if (result != 0)
10163 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100010164 Py_RETURN_NONE;
10165}
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010166#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +100010167
10168
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010169#if defined HAVE_TRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010170/*[clinic input]
10171os.truncate
10172 path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
10173 length: Py_off_t
10174
10175Truncate a file, specified by path, to a specific length.
10176
10177On some platforms, path may also be specified as an open file descriptor.
10178 If this functionality is unavailable, using it raises an exception.
10179[clinic start generated code]*/
10180
Larry Hastings2f936352014-08-05 14:04:04 +100010181static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010182os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
10183/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010184{
10185 int result;
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010186#ifdef MS_WINDOWS
10187 int fd;
10188#endif
10189
10190 if (path->fd != -1)
10191 return os_ftruncate_impl(module, path->fd, length);
Larry Hastings2f936352014-08-05 14:04:04 +100010192
Steve Dowerb82e17e2019-05-23 08:45:22 -070010193 if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
10194 return NULL;
10195 }
10196
Larry Hastings2f936352014-08-05 14:04:04 +100010197 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -040010198 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010199#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -070010200 fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
Victor Stinnercc0bbbc2015-04-25 00:21:52 +020010201 if (fd < 0)
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010202 result = -1;
10203 else {
10204 result = _chsize_s(fd, length);
10205 close(fd);
10206 if (result < 0)
10207 errno = result;
10208 }
10209#else
10210 result = truncate(path->narrow, length);
Larry Hastings2f936352014-08-05 14:04:04 +100010211#endif
Steve Dowera1c7e722015-04-12 00:26:43 -040010212 _Py_END_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +100010213 Py_END_ALLOW_THREADS
10214 if (result < 0)
Alexey Izbyshev83460312018-10-20 03:28:22 +030010215 return posix_path_error(path);
Larry Hastings2f936352014-08-05 14:04:04 +100010216
10217 Py_RETURN_NONE;
10218}
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010219#endif /* HAVE_TRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +100010220
Ross Lagerwall7807c352011-03-17 20:20:30 +020010221
Victor Stinnerd6b17692014-09-30 12:20:05 +020010222/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
10223 and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
10224 defined, which is the case in Python on AIX. AIX bug report:
10225 http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
10226#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
10227# define POSIX_FADVISE_AIX_BUG
10228#endif
10229
Victor Stinnerec39e262014-09-30 12:35:58 +020010230
Victor Stinnerd6b17692014-09-30 12:20:05 +020010231#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +100010232/*[clinic input]
10233os.posix_fallocate
10234
10235 fd: int
10236 offset: Py_off_t
10237 length: Py_off_t
10238 /
10239
10240Ensure a file has allocated at least a particular number of bytes on disk.
10241
10242Ensure that the file specified by fd encompasses a range of bytes
10243starting at offset bytes from the beginning and continuing for length bytes.
10244[clinic start generated code]*/
10245
Larry Hastings2f936352014-08-05 14:04:04 +100010246static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010247os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -040010248 Py_off_t length)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010249/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010250{
10251 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010252 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010253
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010254 do {
10255 Py_BEGIN_ALLOW_THREADS
10256 result = posix_fallocate(fd, offset, length);
10257 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010258 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10259
10260 if (result == 0)
10261 Py_RETURN_NONE;
10262
10263 if (async_err)
10264 return NULL;
10265
10266 errno = result;
10267 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010268}
Victor Stinnerec39e262014-09-30 12:35:58 +020010269#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
Larry Hastings2f936352014-08-05 14:04:04 +100010270
Ross Lagerwall7807c352011-03-17 20:20:30 +020010271
Victor Stinnerd6b17692014-09-30 12:20:05 +020010272#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +100010273/*[clinic input]
10274os.posix_fadvise
10275
10276 fd: int
10277 offset: Py_off_t
10278 length: Py_off_t
10279 advice: int
10280 /
10281
10282Announce an intention to access data in a specific pattern.
10283
10284Announce an intention to access data in a specific pattern, thus allowing
10285the kernel to make optimizations.
10286The advice applies to the region of the file specified by fd starting at
10287offset and continuing for length bytes.
10288advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
10289POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
10290POSIX_FADV_DONTNEED.
10291[clinic start generated code]*/
10292
Larry Hastings2f936352014-08-05 14:04:04 +100010293static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010294os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -040010295 Py_off_t length, int advice)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010296/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010297{
10298 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010299 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010300
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010301 do {
10302 Py_BEGIN_ALLOW_THREADS
10303 result = posix_fadvise(fd, offset, length, advice);
10304 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010305 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10306
10307 if (result == 0)
10308 Py_RETURN_NONE;
10309
10310 if (async_err)
10311 return NULL;
10312
10313 errno = result;
10314 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010315}
Victor Stinnerec39e262014-09-30 12:35:58 +020010316#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
Ross Lagerwall7807c352011-03-17 20:20:30 +020010317
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000010318
Thomas Hellerf78f12a2007-11-08 19:33:05 +000010319#ifdef MS_WINDOWS
Victor Stinner161e7b32020-01-24 11:53:44 +010010320static PyObject*
10321win32_putenv(PyObject *name, PyObject *value)
10322{
10323 /* Search from index 1 because on Windows starting '=' is allowed for
10324 defining hidden environment variables. */
10325 if (PyUnicode_GET_LENGTH(name) == 0 ||
10326 PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
10327 {
10328 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10329 return NULL;
10330 }
10331 PyObject *unicode;
10332 if (value != NULL) {
10333 unicode = PyUnicode_FromFormat("%U=%U", name, value);
10334 }
10335 else {
10336 unicode = PyUnicode_FromFormat("%U=", name);
10337 }
10338 if (unicode == NULL) {
10339 return NULL;
10340 }
10341
10342 Py_ssize_t size;
10343 /* PyUnicode_AsWideCharString() rejects embedded null characters */
10344 wchar_t *env = PyUnicode_AsWideCharString(unicode, &size);
10345 Py_DECREF(unicode);
10346
10347 if (env == NULL) {
10348 return NULL;
10349 }
10350 if (size > _MAX_ENV) {
10351 PyErr_Format(PyExc_ValueError,
10352 "the environment variable is longer than %u characters",
10353 _MAX_ENV);
10354 PyMem_Free(env);
10355 return NULL;
10356 }
10357
10358 /* _wputenv() and SetEnvironmentVariableW() update the environment in the
10359 Process Environment Block (PEB). _wputenv() also updates CRT 'environ'
10360 and '_wenviron' variables, whereas SetEnvironmentVariableW() does not.
10361
10362 Prefer _wputenv() to be compatible with C libraries using CRT
10363 variables and CRT functions using these variables (ex: getenv()). */
10364 int err = _wputenv(env);
10365 PyMem_Free(env);
10366
10367 if (err) {
10368 posix_error();
10369 return NULL;
10370 }
10371
10372 Py_RETURN_NONE;
10373}
10374#endif
10375
10376
10377#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010378/*[clinic input]
10379os.putenv
10380
10381 name: unicode
10382 value: unicode
10383 /
10384
10385Change or add an environment variable.
10386[clinic start generated code]*/
10387
Larry Hastings2f936352014-08-05 14:04:04 +100010388static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010389os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10390/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010391{
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010392 if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
10393 return NULL;
10394 }
Victor Stinner161e7b32020-01-24 11:53:44 +010010395 return win32_putenv(name, value);
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010396}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010397#else
Larry Hastings2f936352014-08-05 14:04:04 +100010398/*[clinic input]
10399os.putenv
Guido van Rossumb6a47161997-09-15 22:54:34 +000010400
Larry Hastings2f936352014-08-05 14:04:04 +100010401 name: FSConverter
10402 value: FSConverter
10403 /
10404
10405Change or add an environment variable.
10406[clinic start generated code]*/
10407
Larry Hastings2f936352014-08-05 14:04:04 +100010408static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010409os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10410/*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010411{
Serhiy Storchaka77703942017-06-25 07:33:01 +030010412 const char *name_string = PyBytes_AS_STRING(name);
10413 const char *value_string = PyBytes_AS_STRING(value);
Larry Hastings2f936352014-08-05 14:04:04 +100010414
Serhiy Storchaka77703942017-06-25 07:33:01 +030010415 if (strchr(name_string, '=') != NULL) {
10416 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10417 return NULL;
10418 }
Victor Stinnerb477d192020-01-22 22:48:16 +010010419
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010420 if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
10421 return NULL;
10422 }
10423
Victor Stinnerb477d192020-01-22 22:48:16 +010010424 if (setenv(name_string, value_string, 1)) {
10425 return posix_error();
10426 }
Larry Hastings2f936352014-08-05 14:04:04 +100010427 Py_RETURN_NONE;
10428}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010429#endif /* !defined(MS_WINDOWS) */
Larry Hastings2f936352014-08-05 14:04:04 +100010430
10431
Victor Stinner161e7b32020-01-24 11:53:44 +010010432#ifdef MS_WINDOWS
10433/*[clinic input]
10434os.unsetenv
10435 name: unicode
10436 /
10437
10438Delete an environment variable.
10439[clinic start generated code]*/
10440
10441static PyObject *
10442os_unsetenv_impl(PyObject *module, PyObject *name)
10443/*[clinic end generated code: output=54c4137ab1834f02 input=4d6a1747cc526d2f]*/
10444{
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010445 if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
10446 return NULL;
10447 }
Victor Stinner161e7b32020-01-24 11:53:44 +010010448 return win32_putenv(name, NULL);
10449}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010450#else
Larry Hastings2f936352014-08-05 14:04:04 +100010451/*[clinic input]
10452os.unsetenv
10453 name: FSConverter
10454 /
10455
10456Delete an environment variable.
10457[clinic start generated code]*/
10458
Larry Hastings2f936352014-08-05 14:04:04 +100010459static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010460os_unsetenv_impl(PyObject *module, PyObject *name)
10461/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010462{
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010463 if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
10464 return NULL;
10465 }
Victor Stinner984890f2011-11-24 13:53:38 +010010466#ifdef HAVE_BROKEN_UNSETENV
10467 unsetenv(PyBytes_AS_STRING(name));
10468#else
Victor Stinner161e7b32020-01-24 11:53:44 +010010469 int err = unsetenv(PyBytes_AS_STRING(name));
10470 if (err) {
Victor Stinner60b385e2011-11-22 22:01:28 +010010471 return posix_error();
Victor Stinner161e7b32020-01-24 11:53:44 +010010472 }
Victor Stinner984890f2011-11-24 13:53:38 +010010473#endif
Guido van Rossumc524d952001-10-19 01:31:59 +000010474
Victor Stinner84ae1182010-05-06 22:05:07 +000010475 Py_RETURN_NONE;
Guido van Rossumc524d952001-10-19 01:31:59 +000010476}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010477#endif /* !MS_WINDOWS */
Guido van Rossumc524d952001-10-19 01:31:59 +000010478
Larry Hastings2f936352014-08-05 14:04:04 +100010479
10480/*[clinic input]
10481os.strerror
10482
10483 code: int
10484 /
10485
10486Translate an error code to a message string.
10487[clinic start generated code]*/
10488
Larry Hastings2f936352014-08-05 14:04:04 +100010489static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010490os_strerror_impl(PyObject *module, int code)
10491/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010492{
10493 char *message = strerror(code);
Victor Stinner8c62be82010-05-06 00:08:46 +000010494 if (message == NULL) {
10495 PyErr_SetString(PyExc_ValueError,
10496 "strerror() argument out of range");
10497 return NULL;
10498 }
Victor Stinner1b579672011-12-17 05:47:23 +010010499 return PyUnicode_DecodeLocale(message, "surrogateescape");
Guido van Rossumb6a47161997-09-15 22:54:34 +000010500}
Guido van Rossumb6a47161997-09-15 22:54:34 +000010501
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010502
Guido van Rossumc9641791998-08-04 15:26:23 +000010503#ifdef HAVE_SYS_WAIT_H
Fred Drake106c1a02002-04-23 15:58:02 +000010504#ifdef WCOREDUMP
Larry Hastings2f936352014-08-05 14:04:04 +100010505/*[clinic input]
10506os.WCOREDUMP -> bool
10507
10508 status: int
10509 /
10510
10511Return True if the process returning status was dumped to a core file.
10512[clinic start generated code]*/
10513
Larry Hastings2f936352014-08-05 14:04:04 +100010514static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010515os_WCOREDUMP_impl(PyObject *module, int status)
10516/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010517{
10518 WAIT_TYPE wait_status;
10519 WAIT_STATUS_INT(wait_status) = status;
10520 return WCOREDUMP(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010521}
10522#endif /* WCOREDUMP */
10523
Larry Hastings2f936352014-08-05 14:04:04 +100010524
Fred Drake106c1a02002-04-23 15:58:02 +000010525#ifdef WIFCONTINUED
Larry Hastings2f936352014-08-05 14:04:04 +100010526/*[clinic input]
10527os.WIFCONTINUED -> bool
10528
10529 status: int
10530
10531Return True if a particular process was continued from a job control stop.
10532
10533Return True if the process returning status was continued from a
10534job control stop.
10535[clinic start generated code]*/
10536
Larry Hastings2f936352014-08-05 14:04:04 +100010537static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010538os_WIFCONTINUED_impl(PyObject *module, int status)
10539/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010540{
10541 WAIT_TYPE wait_status;
10542 WAIT_STATUS_INT(wait_status) = status;
10543 return WIFCONTINUED(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010544}
10545#endif /* WIFCONTINUED */
10546
Larry Hastings2f936352014-08-05 14:04:04 +100010547
Guido van Rossumc9641791998-08-04 15:26:23 +000010548#ifdef WIFSTOPPED
Larry Hastings2f936352014-08-05 14:04:04 +100010549/*[clinic input]
10550os.WIFSTOPPED -> bool
10551
10552 status: int
10553
10554Return True if the process returning status was stopped.
10555[clinic start generated code]*/
10556
Larry Hastings2f936352014-08-05 14:04:04 +100010557static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010558os_WIFSTOPPED_impl(PyObject *module, int status)
10559/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010560{
10561 WAIT_TYPE wait_status;
10562 WAIT_STATUS_INT(wait_status) = status;
10563 return WIFSTOPPED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010564}
10565#endif /* WIFSTOPPED */
10566
Larry Hastings2f936352014-08-05 14:04:04 +100010567
Guido van Rossumc9641791998-08-04 15:26:23 +000010568#ifdef WIFSIGNALED
Larry Hastings2f936352014-08-05 14:04:04 +100010569/*[clinic input]
10570os.WIFSIGNALED -> bool
10571
10572 status: int
10573
10574Return True if the process returning status was terminated by a signal.
10575[clinic start generated code]*/
10576
Larry Hastings2f936352014-08-05 14:04:04 +100010577static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010578os_WIFSIGNALED_impl(PyObject *module, int status)
10579/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010580{
10581 WAIT_TYPE wait_status;
10582 WAIT_STATUS_INT(wait_status) = status;
10583 return WIFSIGNALED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010584}
10585#endif /* WIFSIGNALED */
10586
Larry Hastings2f936352014-08-05 14:04:04 +100010587
Guido van Rossumc9641791998-08-04 15:26:23 +000010588#ifdef WIFEXITED
Larry Hastings2f936352014-08-05 14:04:04 +100010589/*[clinic input]
10590os.WIFEXITED -> bool
10591
10592 status: int
10593
10594Return True if the process returning status exited via the exit() system call.
10595[clinic start generated code]*/
10596
Larry Hastings2f936352014-08-05 14:04:04 +100010597static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010598os_WIFEXITED_impl(PyObject *module, int status)
10599/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010600{
10601 WAIT_TYPE wait_status;
10602 WAIT_STATUS_INT(wait_status) = status;
10603 return WIFEXITED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010604}
10605#endif /* WIFEXITED */
10606
Larry Hastings2f936352014-08-05 14:04:04 +100010607
Guido van Rossum54ecc3d1999-01-27 17:53:11 +000010608#ifdef WEXITSTATUS
Larry Hastings2f936352014-08-05 14:04:04 +100010609/*[clinic input]
10610os.WEXITSTATUS -> int
10611
10612 status: int
10613
10614Return the process return code from status.
10615[clinic start generated code]*/
10616
Larry Hastings2f936352014-08-05 14:04:04 +100010617static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010618os_WEXITSTATUS_impl(PyObject *module, int status)
10619/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010620{
10621 WAIT_TYPE wait_status;
10622 WAIT_STATUS_INT(wait_status) = status;
10623 return WEXITSTATUS(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010624}
10625#endif /* WEXITSTATUS */
10626
Larry Hastings2f936352014-08-05 14:04:04 +100010627
Guido van Rossumc9641791998-08-04 15:26:23 +000010628#ifdef WTERMSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010629/*[clinic input]
10630os.WTERMSIG -> int
10631
10632 status: int
10633
10634Return the signal that terminated the process that provided the status value.
10635[clinic start generated code]*/
10636
Larry Hastings2f936352014-08-05 14:04:04 +100010637static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010638os_WTERMSIG_impl(PyObject *module, int status)
10639/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010640{
10641 WAIT_TYPE wait_status;
10642 WAIT_STATUS_INT(wait_status) = status;
10643 return WTERMSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010644}
10645#endif /* WTERMSIG */
10646
Larry Hastings2f936352014-08-05 14:04:04 +100010647
Guido van Rossumc9641791998-08-04 15:26:23 +000010648#ifdef WSTOPSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010649/*[clinic input]
10650os.WSTOPSIG -> int
10651
10652 status: int
10653
10654Return the signal that stopped the process that provided the status value.
10655[clinic start generated code]*/
10656
Larry Hastings2f936352014-08-05 14:04:04 +100010657static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010658os_WSTOPSIG_impl(PyObject *module, int status)
10659/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010660{
10661 WAIT_TYPE wait_status;
10662 WAIT_STATUS_INT(wait_status) = status;
10663 return WSTOPSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010664}
10665#endif /* WSTOPSIG */
Guido van Rossumc9641791998-08-04 15:26:23 +000010666#endif /* HAVE_SYS_WAIT_H */
10667
10668
Thomas Wouters477c8d52006-05-27 19:21:47 +000010669#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossumd5753e11999-10-19 13:29:23 +000010670#ifdef _SCO_DS
10671/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
10672 needed definitions in sys/statvfs.h */
10673#define _SVID3
10674#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000010675#include <sys/statvfs.h>
10676
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010677static PyObject*
Victor Stinner1c2fa782020-05-10 11:05:29 +020010678_pystatvfs_fromstructstatvfs(PyObject *module, struct statvfs st) {
10679 PyObject *StatVFSResultType = get_posix_state(module)->StatVFSResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -080010680 PyObject *v = PyStructSequence_New((PyTypeObject *)StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000010681 if (v == NULL)
10682 return NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010683
10684#if !defined(HAVE_LARGEFILE_SUPPORT)
Victor Stinner8c62be82010-05-06 00:08:46 +000010685 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10686 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10687 PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
10688 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
10689 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
10690 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
10691 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
10692 PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
10693 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10694 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010695#else
Victor Stinner8c62be82010-05-06 00:08:46 +000010696 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10697 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10698 PyStructSequence_SET_ITEM(v, 2,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010699 PyLong_FromLongLong((long long) st.f_blocks));
Victor Stinner8c62be82010-05-06 00:08:46 +000010700 PyStructSequence_SET_ITEM(v, 3,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010701 PyLong_FromLongLong((long long) st.f_bfree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010702 PyStructSequence_SET_ITEM(v, 4,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010703 PyLong_FromLongLong((long long) st.f_bavail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010704 PyStructSequence_SET_ITEM(v, 5,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010705 PyLong_FromLongLong((long long) st.f_files));
Victor Stinner8c62be82010-05-06 00:08:46 +000010706 PyStructSequence_SET_ITEM(v, 6,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010707 PyLong_FromLongLong((long long) st.f_ffree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010708 PyStructSequence_SET_ITEM(v, 7,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010709 PyLong_FromLongLong((long long) st.f_favail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010710 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10711 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010712#endif
Michael Felt502d5512018-01-05 13:01:58 +010010713/* The _ALL_SOURCE feature test macro defines f_fsid as a structure
10714 * (issue #32390). */
10715#if defined(_AIX) && defined(_ALL_SOURCE)
10716 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
10717#else
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +010010718 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid));
Michael Felt502d5512018-01-05 13:01:58 +010010719#endif
Victor Stinnerf0a7bac2013-10-30 18:55:24 +010010720 if (PyErr_Occurred()) {
10721 Py_DECREF(v);
10722 return NULL;
10723 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010724
Victor Stinner8c62be82010-05-06 00:08:46 +000010725 return v;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010726}
10727
Larry Hastings2f936352014-08-05 14:04:04 +100010728
10729/*[clinic input]
10730os.fstatvfs
10731 fd: int
10732 /
10733
10734Perform an fstatvfs system call on the given fd.
10735
10736Equivalent to statvfs(fd).
10737[clinic start generated code]*/
10738
Larry Hastings2f936352014-08-05 14:04:04 +100010739static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010740os_fstatvfs_impl(PyObject *module, int fd)
10741/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010742{
10743 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010744 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010745 struct statvfs st;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010746
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010747 do {
10748 Py_BEGIN_ALLOW_THREADS
10749 result = fstatvfs(fd, &st);
10750 Py_END_ALLOW_THREADS
10751 } while (result != 0 && errno == EINTR &&
10752 !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +100010753 if (result != 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010754 return (!async_err) ? posix_error() : NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010755
Victor Stinner1c2fa782020-05-10 11:05:29 +020010756 return _pystatvfs_fromstructstatvfs(module, st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010757}
Larry Hastings2f936352014-08-05 14:04:04 +100010758#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
Guido van Rossum94f6f721999-01-06 18:42:14 +000010759
10760
Thomas Wouters477c8d52006-05-27 19:21:47 +000010761#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossum94f6f721999-01-06 18:42:14 +000010762#include <sys/statvfs.h>
Larry Hastings2f936352014-08-05 14:04:04 +100010763/*[clinic input]
10764os.statvfs
Guido van Rossum94f6f721999-01-06 18:42:14 +000010765
Larry Hastings2f936352014-08-05 14:04:04 +100010766 path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
10767
10768Perform a statvfs system call on the given path.
10769
10770path may always be specified as a string.
10771On some platforms, path may also be specified as an open file descriptor.
10772 If this functionality is unavailable, using it raises an exception.
10773[clinic start generated code]*/
10774
Larry Hastings2f936352014-08-05 14:04:04 +100010775static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010776os_statvfs_impl(PyObject *module, path_t *path)
10777/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010778{
10779 int result;
10780 struct statvfs st;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010781
10782 Py_BEGIN_ALLOW_THREADS
10783#ifdef HAVE_FSTATVFS
Larry Hastings2f936352014-08-05 14:04:04 +100010784 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -070010785#ifdef __APPLE__
10786 /* handle weak-linking on Mac OS X 10.3 */
10787 if (fstatvfs == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010788 fd_specified("statvfs", path->fd);
10789 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010790 }
10791#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010792 result = fstatvfs(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010793 }
10794 else
10795#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010796 result = statvfs(path->narrow, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010797 Py_END_ALLOW_THREADS
10798
10799 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100010800 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010801 }
10802
Victor Stinner1c2fa782020-05-10 11:05:29 +020010803 return _pystatvfs_fromstructstatvfs(module, st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010804}
Larry Hastings2f936352014-08-05 14:04:04 +100010805#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
10806
Guido van Rossum94f6f721999-01-06 18:42:14 +000010807
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010808#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010809/*[clinic input]
10810os._getdiskusage
10811
Steve Dower23ad6d02018-02-22 10:39:10 -080010812 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +100010813
10814Return disk usage statistics about the given path as a (total, free) tuple.
10815[clinic start generated code]*/
10816
Larry Hastings2f936352014-08-05 14:04:04 +100010817static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -080010818os__getdiskusage_impl(PyObject *module, path_t *path)
10819/*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010820{
10821 BOOL retval;
10822 ULARGE_INTEGER _, total, free;
Joe Pamerc8c02492018-09-25 10:57:36 -040010823 DWORD err = 0;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010824
10825 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -080010826 retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010827 Py_END_ALLOW_THREADS
Joe Pamerc8c02492018-09-25 10:57:36 -040010828 if (retval == 0) {
10829 if (GetLastError() == ERROR_DIRECTORY) {
10830 wchar_t *dir_path = NULL;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010831
Joe Pamerc8c02492018-09-25 10:57:36 -040010832 dir_path = PyMem_New(wchar_t, path->length + 1);
10833 if (dir_path == NULL) {
10834 return PyErr_NoMemory();
10835 }
10836
10837 wcscpy_s(dir_path, path->length + 1, path->wide);
10838
10839 if (_dirnameW(dir_path) != -1) {
10840 Py_BEGIN_ALLOW_THREADS
10841 retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
10842 Py_END_ALLOW_THREADS
10843 }
10844 /* Record the last error in case it's modified by PyMem_Free. */
10845 err = GetLastError();
10846 PyMem_Free(dir_path);
10847 if (retval) {
10848 goto success;
10849 }
10850 }
10851 return PyErr_SetFromWindowsErr(err);
10852 }
10853
10854success:
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010855 return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
10856}
Larry Hastings2f936352014-08-05 14:04:04 +100010857#endif /* MS_WINDOWS */
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010858
10859
Fred Drakec9680921999-12-13 16:37:25 +000010860/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
10861 * It maps strings representing configuration variable names to
10862 * integer values, allowing those functions to be called with the
Thomas Wouters7e474022000-07-16 12:04:32 +000010863 * magic names instead of polluting the module's namespace with tons of
Fred Drake12c6e2d1999-12-14 21:25:03 +000010864 * rarely-used constants. There are three separate tables that use
10865 * these definitions.
Fred Drakebec628d1999-12-15 18:31:10 +000010866 *
10867 * This code is always included, even if none of the interfaces that
10868 * need it are included. The #if hackery needed to avoid it would be
10869 * sufficiently pervasive that it's not worth the loss of readability.
Fred Drakec9680921999-12-13 16:37:25 +000010870 */
10871struct constdef {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020010872 const char *name;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010873 int value;
Fred Drakec9680921999-12-13 16:37:25 +000010874};
10875
Fred Drake12c6e2d1999-12-14 21:25:03 +000010876static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010877conv_confname(PyObject *arg, int *valuep, struct constdef *table,
Guido van Rossum7d5baac2007-08-27 23:24:46 +000010878 size_t tablesize)
Fred Drake12c6e2d1999-12-14 21:25:03 +000010879{
Christian Heimes217cfd12007-12-02 14:31:20 +000010880 if (PyLong_Check(arg)) {
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010881 int value = _PyLong_AsInt(arg);
10882 if (value == -1 && PyErr_Occurred())
10883 return 0;
10884 *valuep = value;
Stefan Krah0e803b32010-11-26 16:16:47 +000010885 return 1;
Fred Drake12c6e2d1999-12-14 21:25:03 +000010886 }
Guido van Rossumbce56a62007-05-10 18:04:33 +000010887 else {
Stefan Krah0e803b32010-11-26 16:16:47 +000010888 /* look up the value in the table using a binary search */
10889 size_t lo = 0;
10890 size_t mid;
10891 size_t hi = tablesize;
10892 int cmp;
10893 const char *confname;
10894 if (!PyUnicode_Check(arg)) {
10895 PyErr_SetString(PyExc_TypeError,
10896 "configuration names must be strings or integers");
10897 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010898 }
Serhiy Storchaka06515832016-11-20 09:13:07 +020010899 confname = PyUnicode_AsUTF8(arg);
Stefan Krah0e803b32010-11-26 16:16:47 +000010900 if (confname == NULL)
10901 return 0;
10902 while (lo < hi) {
10903 mid = (lo + hi) / 2;
10904 cmp = strcmp(confname, table[mid].name);
10905 if (cmp < 0)
10906 hi = mid;
10907 else if (cmp > 0)
10908 lo = mid + 1;
10909 else {
10910 *valuep = table[mid].value;
10911 return 1;
10912 }
10913 }
10914 PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
10915 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010916 }
Fred Drake12c6e2d1999-12-14 21:25:03 +000010917}
10918
10919
10920#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
10921static struct constdef posix_constants_pathconf[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010922#ifdef _PC_ABI_AIO_XFER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010923 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000010924#endif
10925#ifdef _PC_ABI_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010926 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010927#endif
Fred Drakec9680921999-12-13 16:37:25 +000010928#ifdef _PC_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010929 {"PC_ASYNC_IO", _PC_ASYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010930#endif
10931#ifdef _PC_CHOWN_RESTRICTED
Victor Stinner8c62be82010-05-06 00:08:46 +000010932 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
Fred Drakec9680921999-12-13 16:37:25 +000010933#endif
10934#ifdef _PC_FILESIZEBITS
Victor Stinner8c62be82010-05-06 00:08:46 +000010935 {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
Fred Drakec9680921999-12-13 16:37:25 +000010936#endif
10937#ifdef _PC_LAST
Victor Stinner8c62be82010-05-06 00:08:46 +000010938 {"PC_LAST", _PC_LAST},
Fred Drakec9680921999-12-13 16:37:25 +000010939#endif
10940#ifdef _PC_LINK_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010941 {"PC_LINK_MAX", _PC_LINK_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010942#endif
10943#ifdef _PC_MAX_CANON
Victor Stinner8c62be82010-05-06 00:08:46 +000010944 {"PC_MAX_CANON", _PC_MAX_CANON},
Fred Drakec9680921999-12-13 16:37:25 +000010945#endif
10946#ifdef _PC_MAX_INPUT
Victor Stinner8c62be82010-05-06 00:08:46 +000010947 {"PC_MAX_INPUT", _PC_MAX_INPUT},
Fred Drakec9680921999-12-13 16:37:25 +000010948#endif
10949#ifdef _PC_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010950 {"PC_NAME_MAX", _PC_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010951#endif
10952#ifdef _PC_NO_TRUNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010953 {"PC_NO_TRUNC", _PC_NO_TRUNC},
Fred Drakec9680921999-12-13 16:37:25 +000010954#endif
10955#ifdef _PC_PATH_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010956 {"PC_PATH_MAX", _PC_PATH_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010957#endif
10958#ifdef _PC_PIPE_BUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010959 {"PC_PIPE_BUF", _PC_PIPE_BUF},
Fred Drakec9680921999-12-13 16:37:25 +000010960#endif
10961#ifdef _PC_PRIO_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010962 {"PC_PRIO_IO", _PC_PRIO_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010963#endif
10964#ifdef _PC_SOCK_MAXBUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010965 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
Fred Drakec9680921999-12-13 16:37:25 +000010966#endif
10967#ifdef _PC_SYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010968 {"PC_SYNC_IO", _PC_SYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010969#endif
10970#ifdef _PC_VDISABLE
Victor Stinner8c62be82010-05-06 00:08:46 +000010971 {"PC_VDISABLE", _PC_VDISABLE},
Fred Drakec9680921999-12-13 16:37:25 +000010972#endif
Jesus Cea7e9065c2010-10-25 13:02:04 +000010973#ifdef _PC_ACL_ENABLED
10974 {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
10975#endif
10976#ifdef _PC_MIN_HOLE_SIZE
10977 {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
10978#endif
10979#ifdef _PC_ALLOC_SIZE_MIN
10980 {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
10981#endif
10982#ifdef _PC_REC_INCR_XFER_SIZE
10983 {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
10984#endif
10985#ifdef _PC_REC_MAX_XFER_SIZE
10986 {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
10987#endif
10988#ifdef _PC_REC_MIN_XFER_SIZE
10989 {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
10990#endif
10991#ifdef _PC_REC_XFER_ALIGN
10992 {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
10993#endif
10994#ifdef _PC_SYMLINK_MAX
10995 {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
10996#endif
10997#ifdef _PC_XATTR_ENABLED
10998 {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
10999#endif
11000#ifdef _PC_XATTR_EXISTS
11001 {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
11002#endif
11003#ifdef _PC_TIMESTAMP_RESOLUTION
11004 {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
11005#endif
Fred Drakec9680921999-12-13 16:37:25 +000011006};
11007
Fred Drakec9680921999-12-13 16:37:25 +000011008static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011009conv_path_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011010{
11011 return conv_confname(arg, valuep, posix_constants_pathconf,
11012 sizeof(posix_constants_pathconf)
11013 / sizeof(struct constdef));
11014}
11015#endif
11016
Larry Hastings2f936352014-08-05 14:04:04 +100011017
Fred Drakec9680921999-12-13 16:37:25 +000011018#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100011019/*[clinic input]
11020os.fpathconf -> long
11021
Gregory P. Smith3ccb96c2020-06-20 15:06:48 -070011022 fd: fildes
Larry Hastings2f936352014-08-05 14:04:04 +100011023 name: path_confname
11024 /
11025
11026Return the configuration limit name for the file descriptor fd.
11027
11028If there is no limit, return -1.
11029[clinic start generated code]*/
11030
Larry Hastings2f936352014-08-05 14:04:04 +100011031static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011032os_fpathconf_impl(PyObject *module, int fd, int name)
Gregory P. Smith3ccb96c2020-06-20 15:06:48 -070011033/*[clinic end generated code: output=d5b7042425fc3e21 input=5b8d2471cfaae186]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011034{
11035 long limit;
11036
11037 errno = 0;
11038 limit = fpathconf(fd, name);
11039 if (limit == -1 && errno != 0)
11040 posix_error();
11041
11042 return limit;
11043}
11044#endif /* HAVE_FPATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011045
11046
11047#ifdef HAVE_PATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100011048/*[clinic input]
11049os.pathconf -> long
11050 path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
11051 name: path_confname
11052
11053Return the configuration limit name for the file or directory path.
11054
11055If there is no limit, return -1.
11056On some platforms, path may also be specified as an open file descriptor.
11057 If this functionality is unavailable, using it raises an exception.
11058[clinic start generated code]*/
11059
Larry Hastings2f936352014-08-05 14:04:04 +100011060static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011061os_pathconf_impl(PyObject *module, path_t *path, int name)
11062/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011063{
Victor Stinner8c62be82010-05-06 00:08:46 +000011064 long limit;
Fred Drakec9680921999-12-13 16:37:25 +000011065
Victor Stinner8c62be82010-05-06 00:08:46 +000011066 errno = 0;
Georg Brandl306336b2012-06-24 12:55:33 +020011067#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100011068 if (path->fd != -1)
11069 limit = fpathconf(path->fd, name);
Georg Brandl306336b2012-06-24 12:55:33 +020011070 else
11071#endif
Larry Hastings2f936352014-08-05 14:04:04 +100011072 limit = pathconf(path->narrow, name);
Victor Stinner8c62be82010-05-06 00:08:46 +000011073 if (limit == -1 && errno != 0) {
11074 if (errno == EINVAL)
Stefan Krah99439262010-11-26 12:58:05 +000011075 /* could be a path or name problem */
11076 posix_error();
Fred Drakec9680921999-12-13 16:37:25 +000011077 else
Larry Hastings2f936352014-08-05 14:04:04 +100011078 path_error(path);
Victor Stinner8c62be82010-05-06 00:08:46 +000011079 }
Larry Hastings2f936352014-08-05 14:04:04 +100011080
11081 return limit;
Fred Drakec9680921999-12-13 16:37:25 +000011082}
Larry Hastings2f936352014-08-05 14:04:04 +100011083#endif /* HAVE_PATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011084
11085#ifdef HAVE_CONFSTR
11086static struct constdef posix_constants_confstr[] = {
Fred Draked86ed291999-12-15 15:34:33 +000011087#ifdef _CS_ARCHITECTURE
Victor Stinner8c62be82010-05-06 00:08:46 +000011088 {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
Fred Draked86ed291999-12-15 15:34:33 +000011089#endif
Mark Dickinson876d7c82010-04-16 12:47:52 +000011090#ifdef _CS_GNU_LIBC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011091 {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000011092#endif
11093#ifdef _CS_GNU_LIBPTHREAD_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011094 {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000011095#endif
Fred Draked86ed291999-12-15 15:34:33 +000011096#ifdef _CS_HOSTNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011097 {"CS_HOSTNAME", _CS_HOSTNAME},
Fred Draked86ed291999-12-15 15:34:33 +000011098#endif
11099#ifdef _CS_HW_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000011100 {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000011101#endif
11102#ifdef _CS_HW_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000011103 {"CS_HW_SERIAL", _CS_HW_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000011104#endif
11105#ifdef _CS_INITTAB_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011106 {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000011107#endif
Fred Drakec9680921999-12-13 16:37:25 +000011108#ifdef _CS_LFS64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011109 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011110#endif
11111#ifdef _CS_LFS64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011112 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011113#endif
11114#ifdef _CS_LFS64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011115 {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011116#endif
11117#ifdef _CS_LFS64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011118 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011119#endif
11120#ifdef _CS_LFS_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011121 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011122#endif
11123#ifdef _CS_LFS_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011124 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011125#endif
11126#ifdef _CS_LFS_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011127 {"CS_LFS_LIBS", _CS_LFS_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011128#endif
11129#ifdef _CS_LFS_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011130 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011131#endif
Fred Draked86ed291999-12-15 15:34:33 +000011132#ifdef _CS_MACHINE
Victor Stinner8c62be82010-05-06 00:08:46 +000011133 {"CS_MACHINE", _CS_MACHINE},
Fred Draked86ed291999-12-15 15:34:33 +000011134#endif
Fred Drakec9680921999-12-13 16:37:25 +000011135#ifdef _CS_PATH
Victor Stinner8c62be82010-05-06 00:08:46 +000011136 {"CS_PATH", _CS_PATH},
Fred Drakec9680921999-12-13 16:37:25 +000011137#endif
Fred Draked86ed291999-12-15 15:34:33 +000011138#ifdef _CS_RELEASE
Victor Stinner8c62be82010-05-06 00:08:46 +000011139 {"CS_RELEASE", _CS_RELEASE},
Fred Draked86ed291999-12-15 15:34:33 +000011140#endif
11141#ifdef _CS_SRPC_DOMAIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011142 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
Fred Draked86ed291999-12-15 15:34:33 +000011143#endif
11144#ifdef _CS_SYSNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011145 {"CS_SYSNAME", _CS_SYSNAME},
Fred Draked86ed291999-12-15 15:34:33 +000011146#endif
11147#ifdef _CS_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011148 {"CS_VERSION", _CS_VERSION},
Fred Draked86ed291999-12-15 15:34:33 +000011149#endif
Fred Drakec9680921999-12-13 16:37:25 +000011150#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011151 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011152#endif
11153#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011154 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011155#endif
11156#ifdef _CS_XBS5_ILP32_OFF32_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011157 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011158#endif
11159#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011160 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011161#endif
11162#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011163 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011164#endif
11165#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011166 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011167#endif
11168#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011169 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011170#endif
11171#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011172 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011173#endif
11174#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011175 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011176#endif
11177#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011178 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011179#endif
11180#ifdef _CS_XBS5_LP64_OFF64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011181 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011182#endif
11183#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011184 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011185#endif
11186#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011187 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011188#endif
11189#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011190 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011191#endif
11192#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011193 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011194#endif
11195#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011196 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011197#endif
Fred Draked86ed291999-12-15 15:34:33 +000011198#ifdef _MIPS_CS_AVAIL_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000011199 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000011200#endif
11201#ifdef _MIPS_CS_BASE
Victor Stinner8c62be82010-05-06 00:08:46 +000011202 {"MIPS_CS_BASE", _MIPS_CS_BASE},
Fred Draked86ed291999-12-15 15:34:33 +000011203#endif
11204#ifdef _MIPS_CS_HOSTID
Victor Stinner8c62be82010-05-06 00:08:46 +000011205 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
Fred Draked86ed291999-12-15 15:34:33 +000011206#endif
11207#ifdef _MIPS_CS_HW_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011208 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000011209#endif
11210#ifdef _MIPS_CS_NUM_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000011211 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000011212#endif
11213#ifdef _MIPS_CS_OSREL_MAJ
Victor Stinner8c62be82010-05-06 00:08:46 +000011214 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
Fred Draked86ed291999-12-15 15:34:33 +000011215#endif
11216#ifdef _MIPS_CS_OSREL_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011217 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
Fred Draked86ed291999-12-15 15:34:33 +000011218#endif
11219#ifdef _MIPS_CS_OSREL_PATCH
Victor Stinner8c62be82010-05-06 00:08:46 +000011220 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
Fred Draked86ed291999-12-15 15:34:33 +000011221#endif
11222#ifdef _MIPS_CS_OS_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011223 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000011224#endif
11225#ifdef _MIPS_CS_OS_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000011226 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000011227#endif
11228#ifdef _MIPS_CS_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000011229 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000011230#endif
11231#ifdef _MIPS_CS_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000011232 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000011233#endif
11234#ifdef _MIPS_CS_VENDOR
Victor Stinner8c62be82010-05-06 00:08:46 +000011235 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
Fred Draked86ed291999-12-15 15:34:33 +000011236#endif
Fred Drakec9680921999-12-13 16:37:25 +000011237};
11238
11239static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011240conv_confstr_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011241{
11242 return conv_confname(arg, valuep, posix_constants_confstr,
11243 sizeof(posix_constants_confstr)
11244 / sizeof(struct constdef));
11245}
11246
Larry Hastings2f936352014-08-05 14:04:04 +100011247
11248/*[clinic input]
11249os.confstr
11250
11251 name: confstr_confname
11252 /
11253
11254Return a string-valued system configuration variable.
11255[clinic start generated code]*/
11256
Larry Hastings2f936352014-08-05 14:04:04 +100011257static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011258os_confstr_impl(PyObject *module, int name)
11259/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
Fred Drakec9680921999-12-13 16:37:25 +000011260{
11261 PyObject *result = NULL;
Victor Stinnercb043522010-09-10 23:49:04 +000011262 char buffer[255];
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011263 size_t len;
Fred Drakec9680921999-12-13 16:37:25 +000011264
Victor Stinnercb043522010-09-10 23:49:04 +000011265 errno = 0;
11266 len = confstr(name, buffer, sizeof(buffer));
11267 if (len == 0) {
11268 if (errno) {
11269 posix_error();
11270 return NULL;
Fred Drakec9680921999-12-13 16:37:25 +000011271 }
11272 else {
Victor Stinnercb043522010-09-10 23:49:04 +000011273 Py_RETURN_NONE;
Fred Drakec9680921999-12-13 16:37:25 +000011274 }
11275 }
Victor Stinnercb043522010-09-10 23:49:04 +000011276
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011277 if (len >= sizeof(buffer)) {
Victor Stinnercbc18f32014-12-05 22:51:51 +010011278 size_t len2;
Victor Stinnercb043522010-09-10 23:49:04 +000011279 char *buf = PyMem_Malloc(len);
11280 if (buf == NULL)
11281 return PyErr_NoMemory();
Victor Stinnercbc18f32014-12-05 22:51:51 +010011282 len2 = confstr(name, buf, len);
11283 assert(len == len2);
Christian Heimes8714cfd2015-04-21 10:57:41 +020011284 result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
Victor Stinnercb043522010-09-10 23:49:04 +000011285 PyMem_Free(buf);
11286 }
11287 else
11288 result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
Fred Drakec9680921999-12-13 16:37:25 +000011289 return result;
11290}
Larry Hastings2f936352014-08-05 14:04:04 +100011291#endif /* HAVE_CONFSTR */
Fred Drakec9680921999-12-13 16:37:25 +000011292
11293
11294#ifdef HAVE_SYSCONF
11295static struct constdef posix_constants_sysconf[] = {
11296#ifdef _SC_2_CHAR_TERM
Victor Stinner8c62be82010-05-06 00:08:46 +000011297 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
Fred Drakec9680921999-12-13 16:37:25 +000011298#endif
11299#ifdef _SC_2_C_BIND
Victor Stinner8c62be82010-05-06 00:08:46 +000011300 {"SC_2_C_BIND", _SC_2_C_BIND},
Fred Drakec9680921999-12-13 16:37:25 +000011301#endif
11302#ifdef _SC_2_C_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011303 {"SC_2_C_DEV", _SC_2_C_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011304#endif
11305#ifdef _SC_2_C_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011306 {"SC_2_C_VERSION", _SC_2_C_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011307#endif
11308#ifdef _SC_2_FORT_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011309 {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011310#endif
11311#ifdef _SC_2_FORT_RUN
Victor Stinner8c62be82010-05-06 00:08:46 +000011312 {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
Fred Drakec9680921999-12-13 16:37:25 +000011313#endif
11314#ifdef _SC_2_LOCALEDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000011315 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
Fred Drakec9680921999-12-13 16:37:25 +000011316#endif
11317#ifdef _SC_2_SW_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011318 {"SC_2_SW_DEV", _SC_2_SW_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011319#endif
11320#ifdef _SC_2_UPE
Victor Stinner8c62be82010-05-06 00:08:46 +000011321 {"SC_2_UPE", _SC_2_UPE},
Fred Drakec9680921999-12-13 16:37:25 +000011322#endif
11323#ifdef _SC_2_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011324 {"SC_2_VERSION", _SC_2_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011325#endif
Fred Draked86ed291999-12-15 15:34:33 +000011326#ifdef _SC_ABI_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011327 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
Fred Draked86ed291999-12-15 15:34:33 +000011328#endif
11329#ifdef _SC_ACL
Victor Stinner8c62be82010-05-06 00:08:46 +000011330 {"SC_ACL", _SC_ACL},
Fred Draked86ed291999-12-15 15:34:33 +000011331#endif
Fred Drakec9680921999-12-13 16:37:25 +000011332#ifdef _SC_AIO_LISTIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011333 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011334#endif
Fred Drakec9680921999-12-13 16:37:25 +000011335#ifdef _SC_AIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011336 {"SC_AIO_MAX", _SC_AIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011337#endif
11338#ifdef _SC_AIO_PRIO_DELTA_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011339 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011340#endif
11341#ifdef _SC_ARG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011342 {"SC_ARG_MAX", _SC_ARG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011343#endif
11344#ifdef _SC_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011345 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011346#endif
11347#ifdef _SC_ATEXIT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011348 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011349#endif
Fred Draked86ed291999-12-15 15:34:33 +000011350#ifdef _SC_AUDIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011351 {"SC_AUDIT", _SC_AUDIT},
Fred Draked86ed291999-12-15 15:34:33 +000011352#endif
Fred Drakec9680921999-12-13 16:37:25 +000011353#ifdef _SC_AVPHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011354 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011355#endif
11356#ifdef _SC_BC_BASE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011357 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011358#endif
11359#ifdef _SC_BC_DIM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011360 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011361#endif
11362#ifdef _SC_BC_SCALE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011363 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011364#endif
11365#ifdef _SC_BC_STRING_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011366 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011367#endif
Fred Draked86ed291999-12-15 15:34:33 +000011368#ifdef _SC_CAP
Victor Stinner8c62be82010-05-06 00:08:46 +000011369 {"SC_CAP", _SC_CAP},
Fred Draked86ed291999-12-15 15:34:33 +000011370#endif
Fred Drakec9680921999-12-13 16:37:25 +000011371#ifdef _SC_CHARCLASS_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011372 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011373#endif
11374#ifdef _SC_CHAR_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011375 {"SC_CHAR_BIT", _SC_CHAR_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011376#endif
11377#ifdef _SC_CHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011378 {"SC_CHAR_MAX", _SC_CHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011379#endif
11380#ifdef _SC_CHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011381 {"SC_CHAR_MIN", _SC_CHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011382#endif
11383#ifdef _SC_CHILD_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011384 {"SC_CHILD_MAX", _SC_CHILD_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011385#endif
11386#ifdef _SC_CLK_TCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011387 {"SC_CLK_TCK", _SC_CLK_TCK},
Fred Drakec9680921999-12-13 16:37:25 +000011388#endif
11389#ifdef _SC_COHER_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011390 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011391#endif
11392#ifdef _SC_COLL_WEIGHTS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011393 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011394#endif
11395#ifdef _SC_DCACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011396 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011397#endif
11398#ifdef _SC_DCACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011399 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011400#endif
11401#ifdef _SC_DCACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011402 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011403#endif
11404#ifdef _SC_DCACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011405 {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011406#endif
11407#ifdef _SC_DCACHE_TBLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011408 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011409#endif
11410#ifdef _SC_DELAYTIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011411 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011412#endif
11413#ifdef _SC_EQUIV_CLASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011414 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011415#endif
11416#ifdef _SC_EXPR_NEST_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011417 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011418#endif
11419#ifdef _SC_FSYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000011420 {"SC_FSYNC", _SC_FSYNC},
Fred Drakec9680921999-12-13 16:37:25 +000011421#endif
11422#ifdef _SC_GETGR_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011423 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011424#endif
11425#ifdef _SC_GETPW_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011426 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011427#endif
11428#ifdef _SC_ICACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011429 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011430#endif
11431#ifdef _SC_ICACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011432 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011433#endif
11434#ifdef _SC_ICACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011435 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011436#endif
11437#ifdef _SC_ICACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011438 {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011439#endif
Fred Draked86ed291999-12-15 15:34:33 +000011440#ifdef _SC_INF
Victor Stinner8c62be82010-05-06 00:08:46 +000011441 {"SC_INF", _SC_INF},
Fred Draked86ed291999-12-15 15:34:33 +000011442#endif
Fred Drakec9680921999-12-13 16:37:25 +000011443#ifdef _SC_INT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011444 {"SC_INT_MAX", _SC_INT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011445#endif
11446#ifdef _SC_INT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011447 {"SC_INT_MIN", _SC_INT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011448#endif
11449#ifdef _SC_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011450 {"SC_IOV_MAX", _SC_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011451#endif
Fred Draked86ed291999-12-15 15:34:33 +000011452#ifdef _SC_IP_SECOPTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011453 {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
Fred Draked86ed291999-12-15 15:34:33 +000011454#endif
Fred Drakec9680921999-12-13 16:37:25 +000011455#ifdef _SC_JOB_CONTROL
Victor Stinner8c62be82010-05-06 00:08:46 +000011456 {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
Fred Drakec9680921999-12-13 16:37:25 +000011457#endif
Fred Draked86ed291999-12-15 15:34:33 +000011458#ifdef _SC_KERN_POINTERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011459 {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
Fred Draked86ed291999-12-15 15:34:33 +000011460#endif
11461#ifdef _SC_KERN_SIM
Victor Stinner8c62be82010-05-06 00:08:46 +000011462 {"SC_KERN_SIM", _SC_KERN_SIM},
Fred Draked86ed291999-12-15 15:34:33 +000011463#endif
Fred Drakec9680921999-12-13 16:37:25 +000011464#ifdef _SC_LINE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011465 {"SC_LINE_MAX", _SC_LINE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011466#endif
11467#ifdef _SC_LOGIN_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011468 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011469#endif
11470#ifdef _SC_LOGNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011471 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011472#endif
11473#ifdef _SC_LONG_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011474 {"SC_LONG_BIT", _SC_LONG_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011475#endif
Fred Draked86ed291999-12-15 15:34:33 +000011476#ifdef _SC_MAC
Victor Stinner8c62be82010-05-06 00:08:46 +000011477 {"SC_MAC", _SC_MAC},
Fred Draked86ed291999-12-15 15:34:33 +000011478#endif
Fred Drakec9680921999-12-13 16:37:25 +000011479#ifdef _SC_MAPPED_FILES
Victor Stinner8c62be82010-05-06 00:08:46 +000011480 {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
Fred Drakec9680921999-12-13 16:37:25 +000011481#endif
11482#ifdef _SC_MAXPID
Victor Stinner8c62be82010-05-06 00:08:46 +000011483 {"SC_MAXPID", _SC_MAXPID},
Fred Drakec9680921999-12-13 16:37:25 +000011484#endif
11485#ifdef _SC_MB_LEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011486 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011487#endif
11488#ifdef _SC_MEMLOCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011489 {"SC_MEMLOCK", _SC_MEMLOCK},
Fred Drakec9680921999-12-13 16:37:25 +000011490#endif
11491#ifdef _SC_MEMLOCK_RANGE
Victor Stinner8c62be82010-05-06 00:08:46 +000011492 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
Fred Drakec9680921999-12-13 16:37:25 +000011493#endif
11494#ifdef _SC_MEMORY_PROTECTION
Victor Stinner8c62be82010-05-06 00:08:46 +000011495 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
Fred Drakec9680921999-12-13 16:37:25 +000011496#endif
11497#ifdef _SC_MESSAGE_PASSING
Victor Stinner8c62be82010-05-06 00:08:46 +000011498 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
Fred Drakec9680921999-12-13 16:37:25 +000011499#endif
Fred Draked86ed291999-12-15 15:34:33 +000011500#ifdef _SC_MMAP_FIXED_ALIGNMENT
Victor Stinner8c62be82010-05-06 00:08:46 +000011501 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
Fred Draked86ed291999-12-15 15:34:33 +000011502#endif
Fred Drakec9680921999-12-13 16:37:25 +000011503#ifdef _SC_MQ_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011504 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011505#endif
11506#ifdef _SC_MQ_PRIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011507 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011508#endif
Fred Draked86ed291999-12-15 15:34:33 +000011509#ifdef _SC_NACLS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011510 {"SC_NACLS_MAX", _SC_NACLS_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000011511#endif
Fred Drakec9680921999-12-13 16:37:25 +000011512#ifdef _SC_NGROUPS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011513 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011514#endif
11515#ifdef _SC_NL_ARGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011516 {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011517#endif
11518#ifdef _SC_NL_LANGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011519 {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011520#endif
11521#ifdef _SC_NL_MSGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011522 {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011523#endif
11524#ifdef _SC_NL_NMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011525 {"SC_NL_NMAX", _SC_NL_NMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011526#endif
11527#ifdef _SC_NL_SETMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011528 {"SC_NL_SETMAX", _SC_NL_SETMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011529#endif
11530#ifdef _SC_NL_TEXTMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011531 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011532#endif
11533#ifdef _SC_NPROCESSORS_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011534 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
Fred Drakec9680921999-12-13 16:37:25 +000011535#endif
11536#ifdef _SC_NPROCESSORS_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011537 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
Fred Drakec9680921999-12-13 16:37:25 +000011538#endif
Fred Draked86ed291999-12-15 15:34:33 +000011539#ifdef _SC_NPROC_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011540 {"SC_NPROC_CONF", _SC_NPROC_CONF},
Fred Draked86ed291999-12-15 15:34:33 +000011541#endif
11542#ifdef _SC_NPROC_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011543 {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
Fred Draked86ed291999-12-15 15:34:33 +000011544#endif
Fred Drakec9680921999-12-13 16:37:25 +000011545#ifdef _SC_NZERO
Victor Stinner8c62be82010-05-06 00:08:46 +000011546 {"SC_NZERO", _SC_NZERO},
Fred Drakec9680921999-12-13 16:37:25 +000011547#endif
11548#ifdef _SC_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011549 {"SC_OPEN_MAX", _SC_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011550#endif
11551#ifdef _SC_PAGESIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011552 {"SC_PAGESIZE", _SC_PAGESIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011553#endif
11554#ifdef _SC_PAGE_SIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011555 {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011556#endif
Batuhan Taşkaya909f4a32020-04-05 03:40:49 +030011557#ifdef _SC_AIX_REALMEM
11558 {"SC_AIX_REALMEM", _SC_AIX_REALMEM},
11559#endif
Fred Drakec9680921999-12-13 16:37:25 +000011560#ifdef _SC_PASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011561 {"SC_PASS_MAX", _SC_PASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011562#endif
11563#ifdef _SC_PHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011564 {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011565#endif
11566#ifdef _SC_PII
Victor Stinner8c62be82010-05-06 00:08:46 +000011567 {"SC_PII", _SC_PII},
Fred Drakec9680921999-12-13 16:37:25 +000011568#endif
11569#ifdef _SC_PII_INTERNET
Victor Stinner8c62be82010-05-06 00:08:46 +000011570 {"SC_PII_INTERNET", _SC_PII_INTERNET},
Fred Drakec9680921999-12-13 16:37:25 +000011571#endif
11572#ifdef _SC_PII_INTERNET_DGRAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011573 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
Fred Drakec9680921999-12-13 16:37:25 +000011574#endif
11575#ifdef _SC_PII_INTERNET_STREAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011576 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
Fred Drakec9680921999-12-13 16:37:25 +000011577#endif
11578#ifdef _SC_PII_OSI
Victor Stinner8c62be82010-05-06 00:08:46 +000011579 {"SC_PII_OSI", _SC_PII_OSI},
Fred Drakec9680921999-12-13 16:37:25 +000011580#endif
11581#ifdef _SC_PII_OSI_CLTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011582 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
Fred Drakec9680921999-12-13 16:37:25 +000011583#endif
11584#ifdef _SC_PII_OSI_COTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011585 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
Fred Drakec9680921999-12-13 16:37:25 +000011586#endif
11587#ifdef _SC_PII_OSI_M
Victor Stinner8c62be82010-05-06 00:08:46 +000011588 {"SC_PII_OSI_M", _SC_PII_OSI_M},
Fred Drakec9680921999-12-13 16:37:25 +000011589#endif
11590#ifdef _SC_PII_SOCKET
Victor Stinner8c62be82010-05-06 00:08:46 +000011591 {"SC_PII_SOCKET", _SC_PII_SOCKET},
Fred Drakec9680921999-12-13 16:37:25 +000011592#endif
11593#ifdef _SC_PII_XTI
Victor Stinner8c62be82010-05-06 00:08:46 +000011594 {"SC_PII_XTI", _SC_PII_XTI},
Fred Drakec9680921999-12-13 16:37:25 +000011595#endif
11596#ifdef _SC_POLL
Victor Stinner8c62be82010-05-06 00:08:46 +000011597 {"SC_POLL", _SC_POLL},
Fred Drakec9680921999-12-13 16:37:25 +000011598#endif
11599#ifdef _SC_PRIORITIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011600 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011601#endif
11602#ifdef _SC_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011603 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011604#endif
11605#ifdef _SC_REALTIME_SIGNALS
Victor Stinner8c62be82010-05-06 00:08:46 +000011606 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
Fred Drakec9680921999-12-13 16:37:25 +000011607#endif
11608#ifdef _SC_RE_DUP_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011609 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011610#endif
11611#ifdef _SC_RTSIG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011612 {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011613#endif
11614#ifdef _SC_SAVED_IDS
Victor Stinner8c62be82010-05-06 00:08:46 +000011615 {"SC_SAVED_IDS", _SC_SAVED_IDS},
Fred Drakec9680921999-12-13 16:37:25 +000011616#endif
11617#ifdef _SC_SCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011618 {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011619#endif
11620#ifdef _SC_SCHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011621 {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011622#endif
11623#ifdef _SC_SELECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011624 {"SC_SELECT", _SC_SELECT},
Fred Drakec9680921999-12-13 16:37:25 +000011625#endif
11626#ifdef _SC_SEMAPHORES
Victor Stinner8c62be82010-05-06 00:08:46 +000011627 {"SC_SEMAPHORES", _SC_SEMAPHORES},
Fred Drakec9680921999-12-13 16:37:25 +000011628#endif
11629#ifdef _SC_SEM_NSEMS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011630 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011631#endif
11632#ifdef _SC_SEM_VALUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011633 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011634#endif
11635#ifdef _SC_SHARED_MEMORY_OBJECTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011636 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
Fred Drakec9680921999-12-13 16:37:25 +000011637#endif
11638#ifdef _SC_SHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011639 {"SC_SHRT_MAX", _SC_SHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011640#endif
11641#ifdef _SC_SHRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011642 {"SC_SHRT_MIN", _SC_SHRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011643#endif
11644#ifdef _SC_SIGQUEUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011645 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011646#endif
11647#ifdef _SC_SIGRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011648 {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011649#endif
11650#ifdef _SC_SIGRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011651 {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011652#endif
Fred Draked86ed291999-12-15 15:34:33 +000011653#ifdef _SC_SOFTPOWER
Victor Stinner8c62be82010-05-06 00:08:46 +000011654 {"SC_SOFTPOWER", _SC_SOFTPOWER},
Fred Draked86ed291999-12-15 15:34:33 +000011655#endif
Fred Drakec9680921999-12-13 16:37:25 +000011656#ifdef _SC_SPLIT_CACHE
Victor Stinner8c62be82010-05-06 00:08:46 +000011657 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
Fred Drakec9680921999-12-13 16:37:25 +000011658#endif
11659#ifdef _SC_SSIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011660 {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011661#endif
11662#ifdef _SC_STACK_PROT
Victor Stinner8c62be82010-05-06 00:08:46 +000011663 {"SC_STACK_PROT", _SC_STACK_PROT},
Fred Drakec9680921999-12-13 16:37:25 +000011664#endif
11665#ifdef _SC_STREAM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011666 {"SC_STREAM_MAX", _SC_STREAM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011667#endif
11668#ifdef _SC_SYNCHRONIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011669 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011670#endif
11671#ifdef _SC_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011672 {"SC_THREADS", _SC_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011673#endif
11674#ifdef _SC_THREAD_ATTR_STACKADDR
Victor Stinner8c62be82010-05-06 00:08:46 +000011675 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
Fred Drakec9680921999-12-13 16:37:25 +000011676#endif
11677#ifdef _SC_THREAD_ATTR_STACKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011678 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011679#endif
11680#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011681 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011682#endif
11683#ifdef _SC_THREAD_KEYS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011684 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011685#endif
11686#ifdef _SC_THREAD_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011687 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011688#endif
11689#ifdef _SC_THREAD_PRIO_INHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011690 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
Fred Drakec9680921999-12-13 16:37:25 +000011691#endif
11692#ifdef _SC_THREAD_PRIO_PROTECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011693 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
Fred Drakec9680921999-12-13 16:37:25 +000011694#endif
11695#ifdef _SC_THREAD_PROCESS_SHARED
Victor Stinner8c62be82010-05-06 00:08:46 +000011696 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
Fred Drakec9680921999-12-13 16:37:25 +000011697#endif
11698#ifdef _SC_THREAD_SAFE_FUNCTIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011699 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011700#endif
11701#ifdef _SC_THREAD_STACK_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011702 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011703#endif
11704#ifdef _SC_THREAD_THREADS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011705 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011706#endif
11707#ifdef _SC_TIMERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011708 {"SC_TIMERS", _SC_TIMERS},
Fred Drakec9680921999-12-13 16:37:25 +000011709#endif
11710#ifdef _SC_TIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011711 {"SC_TIMER_MAX", _SC_TIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011712#endif
11713#ifdef _SC_TTY_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011714 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011715#endif
11716#ifdef _SC_TZNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011717 {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011718#endif
11719#ifdef _SC_T_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011720 {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011721#endif
11722#ifdef _SC_UCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011723 {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011724#endif
11725#ifdef _SC_UINT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011726 {"SC_UINT_MAX", _SC_UINT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011727#endif
11728#ifdef _SC_UIO_MAXIOV
Victor Stinner8c62be82010-05-06 00:08:46 +000011729 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
Fred Drakec9680921999-12-13 16:37:25 +000011730#endif
11731#ifdef _SC_ULONG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011732 {"SC_ULONG_MAX", _SC_ULONG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011733#endif
11734#ifdef _SC_USHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011735 {"SC_USHRT_MAX", _SC_USHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011736#endif
11737#ifdef _SC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011738 {"SC_VERSION", _SC_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011739#endif
11740#ifdef _SC_WORD_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011741 {"SC_WORD_BIT", _SC_WORD_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011742#endif
11743#ifdef _SC_XBS5_ILP32_OFF32
Victor Stinner8c62be82010-05-06 00:08:46 +000011744 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
Fred Drakec9680921999-12-13 16:37:25 +000011745#endif
11746#ifdef _SC_XBS5_ILP32_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011747 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011748#endif
11749#ifdef _SC_XBS5_LP64_OFF64
Victor Stinner8c62be82010-05-06 00:08:46 +000011750 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
Fred Drakec9680921999-12-13 16:37:25 +000011751#endif
11752#ifdef _SC_XBS5_LPBIG_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011753 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011754#endif
11755#ifdef _SC_XOPEN_CRYPT
Victor Stinner8c62be82010-05-06 00:08:46 +000011756 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
Fred Drakec9680921999-12-13 16:37:25 +000011757#endif
11758#ifdef _SC_XOPEN_ENH_I18N
Victor Stinner8c62be82010-05-06 00:08:46 +000011759 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
Fred Drakec9680921999-12-13 16:37:25 +000011760#endif
11761#ifdef _SC_XOPEN_LEGACY
Victor Stinner8c62be82010-05-06 00:08:46 +000011762 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
Fred Drakec9680921999-12-13 16:37:25 +000011763#endif
11764#ifdef _SC_XOPEN_REALTIME
Victor Stinner8c62be82010-05-06 00:08:46 +000011765 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
Fred Drakec9680921999-12-13 16:37:25 +000011766#endif
11767#ifdef _SC_XOPEN_REALTIME_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011768 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011769#endif
11770#ifdef _SC_XOPEN_SHM
Victor Stinner8c62be82010-05-06 00:08:46 +000011771 {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
Fred Drakec9680921999-12-13 16:37:25 +000011772#endif
11773#ifdef _SC_XOPEN_UNIX
Victor Stinner8c62be82010-05-06 00:08:46 +000011774 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
Fred Drakec9680921999-12-13 16:37:25 +000011775#endif
11776#ifdef _SC_XOPEN_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011777 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011778#endif
11779#ifdef _SC_XOPEN_XCU_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011780 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011781#endif
11782#ifdef _SC_XOPEN_XPG2
Victor Stinner8c62be82010-05-06 00:08:46 +000011783 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
Fred Drakec9680921999-12-13 16:37:25 +000011784#endif
11785#ifdef _SC_XOPEN_XPG3
Victor Stinner8c62be82010-05-06 00:08:46 +000011786 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
Fred Drakec9680921999-12-13 16:37:25 +000011787#endif
11788#ifdef _SC_XOPEN_XPG4
Victor Stinner8c62be82010-05-06 00:08:46 +000011789 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
Fred Drakec9680921999-12-13 16:37:25 +000011790#endif
11791};
11792
11793static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011794conv_sysconf_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011795{
11796 return conv_confname(arg, valuep, posix_constants_sysconf,
11797 sizeof(posix_constants_sysconf)
11798 / sizeof(struct constdef));
11799}
11800
Larry Hastings2f936352014-08-05 14:04:04 +100011801
11802/*[clinic input]
11803os.sysconf -> long
11804 name: sysconf_confname
11805 /
11806
11807Return an integer-valued system configuration variable.
11808[clinic start generated code]*/
11809
Larry Hastings2f936352014-08-05 14:04:04 +100011810static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011811os_sysconf_impl(PyObject *module, int name)
11812/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011813{
11814 long value;
11815
11816 errno = 0;
11817 value = sysconf(name);
11818 if (value == -1 && errno != 0)
11819 posix_error();
11820 return value;
11821}
11822#endif /* HAVE_SYSCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011823
11824
Fred Drakebec628d1999-12-15 18:31:10 +000011825/* This code is used to ensure that the tables of configuration value names
Serhiy Storchaka56a6d852014-12-01 18:28:43 +020011826 * are in sorted order as required by conv_confname(), and also to build
Fred Drakebec628d1999-12-15 18:31:10 +000011827 * the exported dictionaries that are used to publish information about the
11828 * names available on the host platform.
11829 *
11830 * Sorting the table at runtime ensures that the table is properly ordered
11831 * when used, even for platforms we're not able to test on. It also makes
11832 * it easier to add additional entries to the tables.
Fred Draked86ed291999-12-15 15:34:33 +000011833 */
Fred Drakebec628d1999-12-15 18:31:10 +000011834
11835static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011836cmp_constdefs(const void *v1, const void *v2)
Fred Drakebec628d1999-12-15 18:31:10 +000011837{
11838 const struct constdef *c1 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011839 (const struct constdef *) v1;
Fred Drakebec628d1999-12-15 18:31:10 +000011840 const struct constdef *c2 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011841 (const struct constdef *) v2;
Fred Drakebec628d1999-12-15 18:31:10 +000011842
11843 return strcmp(c1->name, c2->name);
11844}
11845
11846static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011847setup_confname_table(struct constdef *table, size_t tablesize,
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011848 const char *tablename, PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011849{
Fred Drakebec628d1999-12-15 18:31:10 +000011850 PyObject *d = NULL;
Barry Warsaw3155db32000-04-13 15:20:40 +000011851 size_t i;
Fred Drakebec628d1999-12-15 18:31:10 +000011852
11853 qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
11854 d = PyDict_New();
Barry Warsaw3155db32000-04-13 15:20:40 +000011855 if (d == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +000011856 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011857
Barry Warsaw3155db32000-04-13 15:20:40 +000011858 for (i=0; i < tablesize; ++i) {
Victor Stinner8c62be82010-05-06 00:08:46 +000011859 PyObject *o = PyLong_FromLong(table[i].value);
11860 if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
11861 Py_XDECREF(o);
11862 Py_DECREF(d);
11863 return -1;
11864 }
11865 Py_DECREF(o);
Fred Draked86ed291999-12-15 15:34:33 +000011866 }
Fred Drake4d1e64b2002-04-15 19:40:07 +000011867 return PyModule_AddObject(module, tablename, d);
Fred Draked86ed291999-12-15 15:34:33 +000011868}
11869
Fred Drakebec628d1999-12-15 18:31:10 +000011870/* Return -1 on failure, 0 on success. */
11871static int
Fred Drake4d1e64b2002-04-15 19:40:07 +000011872setup_confname_tables(PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011873{
11874#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
Fred Drakebec628d1999-12-15 18:31:10 +000011875 if (setup_confname_table(posix_constants_pathconf,
Fred Draked86ed291999-12-15 15:34:33 +000011876 sizeof(posix_constants_pathconf)
11877 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011878 "pathconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011879 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011880#endif
11881#ifdef HAVE_CONFSTR
Fred Drakebec628d1999-12-15 18:31:10 +000011882 if (setup_confname_table(posix_constants_confstr,
Fred Draked86ed291999-12-15 15:34:33 +000011883 sizeof(posix_constants_confstr)
11884 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011885 "confstr_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011886 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011887#endif
11888#ifdef HAVE_SYSCONF
Fred Drakebec628d1999-12-15 18:31:10 +000011889 if (setup_confname_table(posix_constants_sysconf,
Fred Draked86ed291999-12-15 15:34:33 +000011890 sizeof(posix_constants_sysconf)
11891 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011892 "sysconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011893 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011894#endif
Fred Drakebec628d1999-12-15 18:31:10 +000011895 return 0;
Fred Draked86ed291999-12-15 15:34:33 +000011896}
Fred Draked86ed291999-12-15 15:34:33 +000011897
11898
Larry Hastings2f936352014-08-05 14:04:04 +100011899/*[clinic input]
11900os.abort
11901
11902Abort the interpreter immediately.
11903
11904This function 'dumps core' or otherwise fails in the hardest way possible
11905on the hosting operating system. This function never returns.
11906[clinic start generated code]*/
11907
Larry Hastings2f936352014-08-05 14:04:04 +100011908static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011909os_abort_impl(PyObject *module)
11910/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011911{
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011912 abort();
11913 /*NOTREACHED*/
Victor Stinner9a2329f2016-12-05 17:56:36 +010011914#ifndef __clang__
11915 /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
11916 GCC emits a warning without "return NULL;" (compiler bug?), but Clang
11917 is smarter and emits a warning on the return. */
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011918 Py_FatalError("abort() called from Python code didn't abort!");
11919 return NULL;
Victor Stinner9a2329f2016-12-05 17:56:36 +010011920#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011921}
Fred Drakebec628d1999-12-15 18:31:10 +000011922
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011923#ifdef MS_WINDOWS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011924/* Grab ShellExecute dynamically from shell32 */
11925static int has_ShellExecute = -1;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011926static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
11927 LPCWSTR, INT);
11928static int
11929check_ShellExecute()
11930{
11931 HINSTANCE hShell32;
11932
11933 /* only recheck */
11934 if (-1 == has_ShellExecute) {
11935 Py_BEGIN_ALLOW_THREADS
Victor Stinnera9912152017-10-13 13:46:57 -070011936 /* Security note: this call is not vulnerable to "DLL hijacking".
11937 SHELL32 is part of "KnownDLLs" and so Windows always load
11938 the system SHELL32.DLL, even if there is another SHELL32.DLL
11939 in the DLL search path. */
Steve Dower7d0e0c92015-01-24 08:18:24 -080011940 hShell32 = LoadLibraryW(L"SHELL32");
Steve Dower7d0e0c92015-01-24 08:18:24 -080011941 if (hShell32) {
Steve Dower7d0e0c92015-01-24 08:18:24 -080011942 *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
11943 "ShellExecuteW");
Steve Dowercc16be82016-09-08 10:35:16 -070011944 has_ShellExecute = Py_ShellExecuteW != NULL;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011945 } else {
11946 has_ShellExecute = 0;
11947 }
Tony Roberts4860f012019-02-02 18:16:42 +010011948 Py_END_ALLOW_THREADS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011949 }
11950 return has_ShellExecute;
11951}
11952
11953
Steve Dowercc16be82016-09-08 10:35:16 -070011954/*[clinic input]
11955os.startfile
11956 filepath: path_t
11957 operation: Py_UNICODE = NULL
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +000011958
Steve Dowercc16be82016-09-08 10:35:16 -070011959Start a file with its associated application.
11960
11961When "operation" is not specified or "open", this acts like
11962double-clicking the file in Explorer, or giving the file name as an
11963argument to the DOS "start" command: the file is opened with whatever
11964application (if any) its extension is associated.
11965When another "operation" is given, it specifies what should be done with
11966the file. A typical operation is "print".
11967
11968startfile returns as soon as the associated application is launched.
11969There is no option to wait for the application to close, and no way
11970to retrieve the application's exit status.
11971
11972The filepath is relative to the current directory. If you want to use
11973an absolute path, make sure the first character is not a slash ("/");
11974the underlying Win32 ShellExecute function doesn't work if it is.
11975[clinic start generated code]*/
11976
11977static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +020011978os_startfile_impl(PyObject *module, path_t *filepath,
11979 const Py_UNICODE *operation)
Serhiy Storchaka279f4462019-09-14 12:24:05 +030011980/*[clinic end generated code: output=66dc311c94d50797 input=c940888a5390f039]*/
Steve Dowercc16be82016-09-08 10:35:16 -070011981{
11982 HINSTANCE rc;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011983
11984 if(!check_ShellExecute()) {
11985 /* If the OS doesn't have ShellExecute, return a
11986 NotImplementedError. */
11987 return PyErr_Format(PyExc_NotImplementedError,
11988 "startfile not available on this platform");
11989 }
11990
Saiyang Gou7514f4f2020-02-12 23:47:42 -080011991 if (PySys_Audit("os.startfile", "Ou", filepath->object, operation) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -080011992 return NULL;
11993 }
11994
Victor Stinner8c62be82010-05-06 00:08:46 +000011995 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -070011996 rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
Steve Dower7d0e0c92015-01-24 08:18:24 -080011997 NULL, NULL, SW_SHOWNORMAL);
Victor Stinner8c62be82010-05-06 00:08:46 +000011998 Py_END_ALLOW_THREADS
11999
Victor Stinner8c62be82010-05-06 00:08:46 +000012000 if (rc <= (HINSTANCE)32) {
Steve Dowercc16be82016-09-08 10:35:16 -070012001 win32_error_object("startfile", filepath->object);
Victor Stinnereb5657a2011-09-30 01:44:27 +020012002 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000012003 }
Steve Dowercc16be82016-09-08 10:35:16 -070012004 Py_RETURN_NONE;
Tim Petersf58a7aa2000-09-22 10:05:54 +000012005}
Larry Hastings2f936352014-08-05 14:04:04 +100012006#endif /* MS_WINDOWS */
12007
Fred Drake5ab8eaf1999-12-09 21:13:07 +000012008
Martin v. Löwis438b5342002-12-27 10:16:42 +000012009#ifdef HAVE_GETLOADAVG
Larry Hastings2f936352014-08-05 14:04:04 +100012010/*[clinic input]
12011os.getloadavg
12012
12013Return average recent system load information.
12014
12015Return the number of processes in the system run queue averaged over
12016the last 1, 5, and 15 minutes as a tuple of three floats.
12017Raises OSError if the load average was unobtainable.
12018[clinic start generated code]*/
12019
Larry Hastings2f936352014-08-05 14:04:04 +100012020static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012021os_getloadavg_impl(PyObject *module)
12022/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
Martin v. Löwis438b5342002-12-27 10:16:42 +000012023{
12024 double loadavg[3];
Martin v. Löwis438b5342002-12-27 10:16:42 +000012025 if (getloadavg(loadavg, 3)!=3) {
Stefan Krah0e803b32010-11-26 16:16:47 +000012026 PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
12027 return NULL;
Martin v. Löwis438b5342002-12-27 10:16:42 +000012028 } else
Stefan Krah0e803b32010-11-26 16:16:47 +000012029 return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
Martin v. Löwis438b5342002-12-27 10:16:42 +000012030}
Larry Hastings2f936352014-08-05 14:04:04 +100012031#endif /* HAVE_GETLOADAVG */
Martin v. Löwis438b5342002-12-27 10:16:42 +000012032
Larry Hastings2f936352014-08-05 14:04:04 +100012033
12034/*[clinic input]
12035os.device_encoding
12036 fd: int
12037
12038Return a string describing the encoding of a terminal's file descriptor.
12039
12040The file descriptor must be attached to a terminal.
12041If the device is not a terminal, return None.
12042[clinic start generated code]*/
12043
Larry Hastings2f936352014-08-05 14:04:04 +100012044static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012045os_device_encoding_impl(PyObject *module, int fd)
12046/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012047{
Brett Cannonefb00c02012-02-29 18:31:31 -050012048 return _Py_device_encoding(fd);
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +000012049}
12050
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012051
Larry Hastings2f936352014-08-05 14:04:04 +100012052#ifdef HAVE_SETRESUID
12053/*[clinic input]
12054os.setresuid
12055
12056 ruid: uid_t
12057 euid: uid_t
12058 suid: uid_t
12059 /
12060
12061Set the current process's real, effective, and saved user ids.
12062[clinic start generated code]*/
12063
Larry Hastings2f936352014-08-05 14:04:04 +100012064static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012065os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
12066/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012067{
Victor Stinner8c62be82010-05-06 00:08:46 +000012068 if (setresuid(ruid, euid, suid) < 0)
12069 return posix_error();
12070 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012071}
Larry Hastings2f936352014-08-05 14:04:04 +100012072#endif /* HAVE_SETRESUID */
12073
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012074
12075#ifdef HAVE_SETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100012076/*[clinic input]
12077os.setresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012078
Larry Hastings2f936352014-08-05 14:04:04 +100012079 rgid: gid_t
12080 egid: gid_t
12081 sgid: gid_t
12082 /
12083
12084Set the current process's real, effective, and saved group ids.
12085[clinic start generated code]*/
12086
Larry Hastings2f936352014-08-05 14:04:04 +100012087static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012088os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
12089/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012090{
Victor Stinner8c62be82010-05-06 00:08:46 +000012091 if (setresgid(rgid, egid, sgid) < 0)
12092 return posix_error();
12093 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012094}
Larry Hastings2f936352014-08-05 14:04:04 +100012095#endif /* HAVE_SETRESGID */
12096
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012097
12098#ifdef HAVE_GETRESUID
Larry Hastings2f936352014-08-05 14:04:04 +100012099/*[clinic input]
12100os.getresuid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012101
Larry Hastings2f936352014-08-05 14:04:04 +100012102Return a tuple of the current process's real, effective, and saved user ids.
12103[clinic start generated code]*/
12104
Larry Hastings2f936352014-08-05 14:04:04 +100012105static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012106os_getresuid_impl(PyObject *module)
12107/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012108{
Victor Stinner8c62be82010-05-06 00:08:46 +000012109 uid_t ruid, euid, suid;
Victor Stinner8c62be82010-05-06 00:08:46 +000012110 if (getresuid(&ruid, &euid, &suid) < 0)
12111 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020012112 return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
12113 _PyLong_FromUid(euid),
12114 _PyLong_FromUid(suid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012115}
Larry Hastings2f936352014-08-05 14:04:04 +100012116#endif /* HAVE_GETRESUID */
12117
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012118
12119#ifdef HAVE_GETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100012120/*[clinic input]
12121os.getresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012122
Larry Hastings2f936352014-08-05 14:04:04 +100012123Return a tuple of the current process's real, effective, and saved group ids.
12124[clinic start generated code]*/
12125
Larry Hastings2f936352014-08-05 14:04:04 +100012126static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012127os_getresgid_impl(PyObject *module)
12128/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012129{
12130 gid_t rgid, egid, sgid;
Victor Stinner8c62be82010-05-06 00:08:46 +000012131 if (getresgid(&rgid, &egid, &sgid) < 0)
12132 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020012133 return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
12134 _PyLong_FromGid(egid),
12135 _PyLong_FromGid(sgid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012136}
Larry Hastings2f936352014-08-05 14:04:04 +100012137#endif /* HAVE_GETRESGID */
12138
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012139
Benjamin Peterson9428d532011-09-14 11:45:52 -040012140#ifdef USE_XATTRS
Larry Hastings2f936352014-08-05 14:04:04 +100012141/*[clinic input]
12142os.getxattr
Benjamin Peterson799bd802011-08-31 22:15:17 -040012143
Larry Hastings2f936352014-08-05 14:04:04 +100012144 path: path_t(allow_fd=True)
12145 attribute: path_t
12146 *
12147 follow_symlinks: bool = True
12148
12149Return the value of extended attribute attribute on path.
12150
BNMetricsb9427072018-11-02 15:20:19 +000012151path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012152If follow_symlinks is False, and the last element of the path is a symbolic
12153 link, getxattr will examine the symbolic link itself instead of the file
12154 the link points to.
12155
12156[clinic start generated code]*/
12157
Larry Hastings2f936352014-08-05 14:04:04 +100012158static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012159os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012160 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012161/*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012162{
12163 Py_ssize_t i;
12164 PyObject *buffer = NULL;
12165
12166 if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
12167 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012168
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012169 if (PySys_Audit("os.getxattr", "OO", path->object, attribute->object) < 0) {
12170 return NULL;
12171 }
12172
Larry Hastings9cf065c2012-06-22 16:30:09 -070012173 for (i = 0; ; i++) {
12174 void *ptr;
12175 ssize_t result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012176 static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
Larry Hastings9cf065c2012-06-22 16:30:09 -070012177 Py_ssize_t buffer_size = buffer_sizes[i];
12178 if (!buffer_size) {
Larry Hastings2f936352014-08-05 14:04:04 +100012179 path_error(path);
12180 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012181 }
12182 buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
12183 if (!buffer)
Larry Hastings2f936352014-08-05 14:04:04 +100012184 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012185 ptr = PyBytes_AS_STRING(buffer);
Benjamin Peterson799bd802011-08-31 22:15:17 -040012186
Larry Hastings9cf065c2012-06-22 16:30:09 -070012187 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012188 if (path->fd >= 0)
12189 result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012190 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100012191 result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012192 else
Larry Hastings2f936352014-08-05 14:04:04 +100012193 result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012194 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012195
Larry Hastings9cf065c2012-06-22 16:30:09 -070012196 if (result < 0) {
12197 Py_DECREF(buffer);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012198 if (errno == ERANGE)
12199 continue;
Larry Hastings2f936352014-08-05 14:04:04 +100012200 path_error(path);
12201 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012202 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012203
Larry Hastings9cf065c2012-06-22 16:30:09 -070012204 if (result != buffer_size) {
12205 /* Can only shrink. */
12206 _PyBytes_Resize(&buffer, result);
12207 }
12208 break;
12209 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012210
Larry Hastings9cf065c2012-06-22 16:30:09 -070012211 return buffer;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012212}
12213
Larry Hastings2f936352014-08-05 14:04:04 +100012214
12215/*[clinic input]
12216os.setxattr
12217
12218 path: path_t(allow_fd=True)
12219 attribute: path_t
12220 value: Py_buffer
12221 flags: int = 0
12222 *
12223 follow_symlinks: bool = True
12224
12225Set extended attribute attribute on path to value.
12226
BNMetricsb9427072018-11-02 15:20:19 +000012227path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012228If follow_symlinks is False, and the last element of the path is a symbolic
12229 link, setxattr will modify the symbolic link itself instead of the file
12230 the link points to.
12231
12232[clinic start generated code]*/
12233
Benjamin Peterson799bd802011-08-31 22:15:17 -040012234static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012235os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012236 Py_buffer *value, int flags, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012237/*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
Benjamin Peterson799bd802011-08-31 22:15:17 -040012238{
Larry Hastings2f936352014-08-05 14:04:04 +100012239 ssize_t result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012240
Larry Hastings2f936352014-08-05 14:04:04 +100012241 if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
Benjamin Peterson799bd802011-08-31 22:15:17 -040012242 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012243
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012244 if (PySys_Audit("os.setxattr", "OOy#i", path->object, attribute->object,
12245 value->buf, value->len, flags) < 0) {
12246 return NULL;
12247 }
12248
Benjamin Peterson799bd802011-08-31 22:15:17 -040012249 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012250 if (path->fd > -1)
12251 result = fsetxattr(path->fd, attribute->narrow,
12252 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012253 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100012254 result = setxattr(path->narrow, attribute->narrow,
12255 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012256 else
Larry Hastings2f936352014-08-05 14:04:04 +100012257 result = lsetxattr(path->narrow, attribute->narrow,
12258 value->buf, value->len, flags);
Benjamin Peterson799bd802011-08-31 22:15:17 -040012259 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012260
Larry Hastings9cf065c2012-06-22 16:30:09 -070012261 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100012262 path_error(path);
12263 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012264 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012265
Larry Hastings2f936352014-08-05 14:04:04 +100012266 Py_RETURN_NONE;
12267}
12268
12269
12270/*[clinic input]
12271os.removexattr
12272
12273 path: path_t(allow_fd=True)
12274 attribute: path_t
12275 *
12276 follow_symlinks: bool = True
12277
12278Remove extended attribute attribute on path.
12279
BNMetricsb9427072018-11-02 15:20:19 +000012280path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012281If follow_symlinks is False, and the last element of the path is a symbolic
12282 link, removexattr will modify the symbolic link itself instead of the file
12283 the link points to.
12284
12285[clinic start generated code]*/
12286
Larry Hastings2f936352014-08-05 14:04:04 +100012287static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012288os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012289 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012290/*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012291{
12292 ssize_t result;
12293
12294 if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
12295 return NULL;
12296
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012297 if (PySys_Audit("os.removexattr", "OO", path->object, attribute->object) < 0) {
12298 return NULL;
12299 }
12300
Larry Hastings2f936352014-08-05 14:04:04 +100012301 Py_BEGIN_ALLOW_THREADS;
12302 if (path->fd > -1)
12303 result = fremovexattr(path->fd, attribute->narrow);
12304 else if (follow_symlinks)
12305 result = removexattr(path->narrow, attribute->narrow);
12306 else
12307 result = lremovexattr(path->narrow, attribute->narrow);
12308 Py_END_ALLOW_THREADS;
12309
12310 if (result) {
12311 return path_error(path);
12312 }
12313
12314 Py_RETURN_NONE;
12315}
12316
12317
12318/*[clinic input]
12319os.listxattr
12320
12321 path: path_t(allow_fd=True, nullable=True) = None
12322 *
12323 follow_symlinks: bool = True
12324
12325Return a list of extended attributes on path.
12326
BNMetricsb9427072018-11-02 15:20:19 +000012327path may be either None, a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012328if path is None, listxattr will examine the current directory.
12329If follow_symlinks is False, and the last element of the path is a symbolic
12330 link, listxattr will examine the symbolic link itself instead of the file
12331 the link points to.
12332[clinic start generated code]*/
12333
Larry Hastings2f936352014-08-05 14:04:04 +100012334static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012335os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012336/*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012337{
Larry Hastings9cf065c2012-06-22 16:30:09 -070012338 Py_ssize_t i;
12339 PyObject *result = NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100012340 const char *name;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012341 char *buffer = NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012342
Larry Hastings2f936352014-08-05 14:04:04 +100012343 if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
Larry Hastings9cf065c2012-06-22 16:30:09 -070012344 goto exit;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012345
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012346 if (PySys_Audit("os.listxattr", "(O)",
12347 path->object ? path->object : Py_None) < 0) {
12348 return NULL;
12349 }
12350
Larry Hastings2f936352014-08-05 14:04:04 +100012351 name = path->narrow ? path->narrow : ".";
12352
Larry Hastings9cf065c2012-06-22 16:30:09 -070012353 for (i = 0; ; i++) {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012354 const char *start, *trace, *end;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012355 ssize_t length;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012356 static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
Larry Hastings9cf065c2012-06-22 16:30:09 -070012357 Py_ssize_t buffer_size = buffer_sizes[i];
12358 if (!buffer_size) {
Christian Heimes3b9493b2012-09-23 16:11:15 +020012359 /* ERANGE */
Larry Hastings2f936352014-08-05 14:04:04 +100012360 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012361 break;
12362 }
12363 buffer = PyMem_MALLOC(buffer_size);
12364 if (!buffer) {
12365 PyErr_NoMemory();
12366 break;
12367 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012368
Larry Hastings9cf065c2012-06-22 16:30:09 -070012369 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012370 if (path->fd > -1)
12371 length = flistxattr(path->fd, buffer, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012372 else if (follow_symlinks)
12373 length = listxattr(name, buffer, buffer_size);
12374 else
12375 length = llistxattr(name, buffer, buffer_size);
12376 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012377
Larry Hastings9cf065c2012-06-22 16:30:09 -070012378 if (length < 0) {
Antoine Pitrou7f987392013-05-13 19:46:29 +020012379 if (errno == ERANGE) {
12380 PyMem_FREE(buffer);
Benjamin Petersondedac522013-05-13 19:55:40 -050012381 buffer = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012382 continue;
Antoine Pitrou7f987392013-05-13 19:46:29 +020012383 }
Larry Hastings2f936352014-08-05 14:04:04 +100012384 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012385 break;
12386 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012387
Larry Hastings9cf065c2012-06-22 16:30:09 -070012388 result = PyList_New(0);
12389 if (!result) {
12390 goto exit;
12391 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012392
Larry Hastings9cf065c2012-06-22 16:30:09 -070012393 end = buffer + length;
12394 for (trace = start = buffer; trace != end; trace++) {
12395 if (!*trace) {
12396 int error;
12397 PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
12398 trace - start);
12399 if (!attribute) {
12400 Py_DECREF(result);
12401 result = NULL;
12402 goto exit;
12403 }
12404 error = PyList_Append(result, attribute);
12405 Py_DECREF(attribute);
12406 if (error) {
12407 Py_DECREF(result);
12408 result = NULL;
12409 goto exit;
12410 }
12411 start = trace + 1;
12412 }
12413 }
12414 break;
12415 }
12416exit:
Larry Hastings9cf065c2012-06-22 16:30:09 -070012417 if (buffer)
12418 PyMem_FREE(buffer);
12419 return result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012420}
Benjamin Peterson9428d532011-09-14 11:45:52 -040012421#endif /* USE_XATTRS */
Benjamin Peterson799bd802011-08-31 22:15:17 -040012422
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012423
Larry Hastings2f936352014-08-05 14:04:04 +100012424/*[clinic input]
12425os.urandom
12426
12427 size: Py_ssize_t
12428 /
12429
12430Return a bytes object containing random bytes suitable for cryptographic use.
12431[clinic start generated code]*/
12432
Larry Hastings2f936352014-08-05 14:04:04 +100012433static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012434os_urandom_impl(PyObject *module, Py_ssize_t size)
12435/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012436{
12437 PyObject *bytes;
12438 int result;
12439
Georg Brandl2fb477c2012-02-21 00:33:36 +010012440 if (size < 0)
12441 return PyErr_Format(PyExc_ValueError,
12442 "negative argument not allowed");
Larry Hastings2f936352014-08-05 14:04:04 +100012443 bytes = PyBytes_FromStringAndSize(NULL, size);
12444 if (bytes == NULL)
Georg Brandl2fb477c2012-02-21 00:33:36 +010012445 return NULL;
12446
Victor Stinnere66987e2016-09-06 16:33:52 -070012447 result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
Larry Hastings2f936352014-08-05 14:04:04 +100012448 if (result == -1) {
12449 Py_DECREF(bytes);
Georg Brandl2fb477c2012-02-21 00:33:36 +010012450 return NULL;
12451 }
Larry Hastings2f936352014-08-05 14:04:04 +100012452 return bytes;
Georg Brandl2fb477c2012-02-21 00:33:36 +010012453}
12454
Zackery Spytz43fdbd22019-05-29 13:57:07 -060012455#ifdef HAVE_MEMFD_CREATE
12456/*[clinic input]
12457os.memfd_create
12458
12459 name: FSConverter
12460 flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
12461
12462[clinic start generated code]*/
12463
12464static PyObject *
12465os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
12466/*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
12467{
12468 int fd;
12469 const char *bytes = PyBytes_AS_STRING(name);
12470 Py_BEGIN_ALLOW_THREADS
12471 fd = memfd_create(bytes, flags);
12472 Py_END_ALLOW_THREADS
12473 if (fd == -1) {
12474 return PyErr_SetFromErrno(PyExc_OSError);
12475 }
12476 return PyLong_FromLong(fd);
12477}
12478#endif
12479
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012480/* Terminal size querying */
12481
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012482PyDoc_STRVAR(TerminalSize_docstring,
12483 "A tuple of (columns, lines) for holding terminal window size");
12484
12485static PyStructSequence_Field TerminalSize_fields[] = {
12486 {"columns", "width of the terminal window in characters"},
12487 {"lines", "height of the terminal window in characters"},
12488 {NULL, NULL}
12489};
12490
12491static PyStructSequence_Desc TerminalSize_desc = {
12492 "os.terminal_size",
12493 TerminalSize_docstring,
12494 TerminalSize_fields,
12495 2,
12496};
12497
12498#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
Serhiy Storchaka2b560312020-04-18 19:14:10 +030012499/*[clinic input]
12500os.get_terminal_size
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012501
Serhiy Storchaka2b560312020-04-18 19:14:10 +030012502 fd: int(c_default="fileno(stdout)", py_default="<unrepresentable>") = -1
12503 /
12504
12505Return the size of the terminal window as (columns, lines).
12506
12507The optional argument fd (default standard output) specifies
12508which file descriptor should be queried.
12509
12510If the file descriptor is not connected to a terminal, an OSError
12511is thrown.
12512
12513This function will only be defined if an implementation is
12514available for this system.
12515
12516shutil.get_terminal_size is the high-level function which should
12517normally be used, os.get_terminal_size is the low-level implementation.
12518[clinic start generated code]*/
12519
12520static PyObject *
12521os_get_terminal_size_impl(PyObject *module, int fd)
12522/*[clinic end generated code: output=fbab93acef980508 input=ead5679b82ddb920]*/
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012523{
12524 int columns, lines;
12525 PyObject *termsize;
12526
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012527 /* Under some conditions stdout may not be connected and
12528 * fileno(stdout) may point to an invalid file descriptor. For example
12529 * GUI apps don't have valid standard streams by default.
12530 *
12531 * If this happens, and the optional fd argument is not present,
12532 * the ioctl below will fail returning EBADF. This is what we want.
12533 */
12534
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012535#ifdef TERMSIZE_USE_IOCTL
12536 {
12537 struct winsize w;
12538 if (ioctl(fd, TIOCGWINSZ, &w))
12539 return PyErr_SetFromErrno(PyExc_OSError);
12540 columns = w.ws_col;
12541 lines = w.ws_row;
12542 }
12543#endif /* TERMSIZE_USE_IOCTL */
12544
12545#ifdef TERMSIZE_USE_CONIO
12546 {
12547 DWORD nhandle;
12548 HANDLE handle;
12549 CONSOLE_SCREEN_BUFFER_INFO csbi;
12550 switch (fd) {
12551 case 0: nhandle = STD_INPUT_HANDLE;
12552 break;
12553 case 1: nhandle = STD_OUTPUT_HANDLE;
12554 break;
12555 case 2: nhandle = STD_ERROR_HANDLE;
12556 break;
12557 default:
12558 return PyErr_Format(PyExc_ValueError, "bad file descriptor");
12559 }
12560 handle = GetStdHandle(nhandle);
12561 if (handle == NULL)
12562 return PyErr_Format(PyExc_OSError, "handle cannot be retrieved");
12563 if (handle == INVALID_HANDLE_VALUE)
12564 return PyErr_SetFromWindowsErr(0);
12565
12566 if (!GetConsoleScreenBufferInfo(handle, &csbi))
12567 return PyErr_SetFromWindowsErr(0);
12568
12569 columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
12570 lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
12571 }
12572#endif /* TERMSIZE_USE_CONIO */
12573
Serhiy Storchaka2b560312020-04-18 19:14:10 +030012574 PyObject *TerminalSizeType = get_posix_state(module)->TerminalSizeType;
Eddie Elizondob3966632019-11-05 07:16:14 -080012575 termsize = PyStructSequence_New((PyTypeObject *)TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012576 if (termsize == NULL)
12577 return NULL;
12578 PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
12579 PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
12580 if (PyErr_Occurred()) {
12581 Py_DECREF(termsize);
12582 return NULL;
12583 }
12584 return termsize;
12585}
12586#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
12587
Larry Hastings2f936352014-08-05 14:04:04 +100012588
12589/*[clinic input]
12590os.cpu_count
12591
Charles-François Natali80d62e62015-08-13 20:37:08 +010012592Return the number of CPUs in the system; return None if indeterminable.
12593
12594This number is not equivalent to the number of CPUs the current process can
12595use. The number of usable CPUs can be obtained with
12596``len(os.sched_getaffinity(0))``
Larry Hastings2f936352014-08-05 14:04:04 +100012597[clinic start generated code]*/
12598
Larry Hastings2f936352014-08-05 14:04:04 +100012599static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012600os_cpu_count_impl(PyObject *module)
Serhiy Storchaka2954f832016-07-07 18:20:03 +030012601/*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012602{
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012603 int ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012604#ifdef MS_WINDOWS
Steve Doweraa929272019-09-11 16:15:39 +010012605 ncpu = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012606#elif defined(__hpux)
12607 ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
12608#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
12609 ncpu = sysconf(_SC_NPROCESSORS_ONLN);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012610#elif defined(__DragonFly__) || \
12611 defined(__OpenBSD__) || \
12612 defined(__FreeBSD__) || \
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012613 defined(__NetBSD__) || \
12614 defined(__APPLE__)
Charles-Francois Natali7c4f8da2013-05-20 17:40:32 +020012615 int mib[2];
12616 size_t len = sizeof(ncpu);
12617 mib[0] = CTL_HW;
12618 mib[1] = HW_NCPU;
12619 if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
12620 ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012621#endif
12622 if (ncpu >= 1)
12623 return PyLong_FromLong(ncpu);
12624 else
12625 Py_RETURN_NONE;
12626}
12627
Victor Stinnerdaf45552013-08-28 00:53:59 +020012628
Larry Hastings2f936352014-08-05 14:04:04 +100012629/*[clinic input]
12630os.get_inheritable -> bool
12631
12632 fd: int
12633 /
12634
12635Get the close-on-exe flag of the specified file descriptor.
12636[clinic start generated code]*/
12637
Larry Hastings2f936352014-08-05 14:04:04 +100012638static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012639os_get_inheritable_impl(PyObject *module, int fd)
12640/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012641{
Steve Dower8fc89802015-04-12 00:26:27 -040012642 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -040012643 _Py_BEGIN_SUPPRESS_IPH
12644 return_value = _Py_get_inheritable(fd);
12645 _Py_END_SUPPRESS_IPH
12646 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +100012647}
12648
12649
12650/*[clinic input]
12651os.set_inheritable
12652 fd: int
12653 inheritable: int
12654 /
12655
12656Set the inheritable flag of the specified file descriptor.
12657[clinic start generated code]*/
12658
Larry Hastings2f936352014-08-05 14:04:04 +100012659static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012660os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
12661/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
Victor Stinnerdaf45552013-08-28 00:53:59 +020012662{
Steve Dower8fc89802015-04-12 00:26:27 -040012663 int result;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012664
Steve Dower8fc89802015-04-12 00:26:27 -040012665 _Py_BEGIN_SUPPRESS_IPH
12666 result = _Py_set_inheritable(fd, inheritable, NULL);
12667 _Py_END_SUPPRESS_IPH
12668 if (result < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +020012669 return NULL;
12670 Py_RETURN_NONE;
12671}
12672
12673
12674#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100012675/*[clinic input]
12676os.get_handle_inheritable -> bool
Benjamin Petersonca470632016-09-06 13:47:26 -070012677 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012678 /
Victor Stinnerdaf45552013-08-28 00:53:59 +020012679
Larry Hastings2f936352014-08-05 14:04:04 +100012680Get the close-on-exe flag of the specified file descriptor.
12681[clinic start generated code]*/
12682
Larry Hastings2f936352014-08-05 14:04:04 +100012683static int
Benjamin Petersonca470632016-09-06 13:47:26 -070012684os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
Victor Stinner581139c2016-09-06 15:54:20 -070012685/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012686{
12687 DWORD flags;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012688
12689 if (!GetHandleInformation((HANDLE)handle, &flags)) {
12690 PyErr_SetFromWindowsErr(0);
Larry Hastings2f936352014-08-05 14:04:04 +100012691 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012692 }
12693
Larry Hastings2f936352014-08-05 14:04:04 +100012694 return flags & HANDLE_FLAG_INHERIT;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012695}
12696
Victor Stinnerdaf45552013-08-28 00:53:59 +020012697
Larry Hastings2f936352014-08-05 14:04:04 +100012698/*[clinic input]
12699os.set_handle_inheritable
Benjamin Petersonca470632016-09-06 13:47:26 -070012700 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012701 inheritable: bool
12702 /
12703
12704Set the inheritable flag of the specified handle.
12705[clinic start generated code]*/
12706
Larry Hastings2f936352014-08-05 14:04:04 +100012707static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -070012708os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
Larry Hastings89964c42015-04-14 18:07:59 -040012709 int inheritable)
Victor Stinner581139c2016-09-06 15:54:20 -070012710/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012711{
12712 DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012713 if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
12714 PyErr_SetFromWindowsErr(0);
12715 return NULL;
12716 }
12717 Py_RETURN_NONE;
12718}
Larry Hastings2f936352014-08-05 14:04:04 +100012719#endif /* MS_WINDOWS */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012720
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012721#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012722/*[clinic input]
12723os.get_blocking -> bool
12724 fd: int
12725 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012726
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012727Get the blocking mode of the file descriptor.
12728
12729Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
12730[clinic start generated code]*/
12731
12732static int
12733os_get_blocking_impl(PyObject *module, int fd)
12734/*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012735{
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012736 int blocking;
12737
Steve Dower8fc89802015-04-12 00:26:27 -040012738 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012739 blocking = _Py_get_blocking(fd);
Steve Dower8fc89802015-04-12 00:26:27 -040012740 _Py_END_SUPPRESS_IPH
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012741 return blocking;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012742}
12743
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012744/*[clinic input]
12745os.set_blocking
12746 fd: int
12747 blocking: bool(accept={int})
12748 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012749
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012750Set the blocking mode of the specified file descriptor.
12751
12752Set the O_NONBLOCK flag if blocking is False,
12753clear the O_NONBLOCK flag otherwise.
12754[clinic start generated code]*/
12755
12756static PyObject *
12757os_set_blocking_impl(PyObject *module, int fd, int blocking)
12758/*[clinic end generated code: output=384eb43aa0762a9d input=bf5c8efdc5860ff3]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012759{
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012760 int result;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012761
Steve Dower8fc89802015-04-12 00:26:27 -040012762 _Py_BEGIN_SUPPRESS_IPH
12763 result = _Py_set_blocking(fd, blocking);
12764 _Py_END_SUPPRESS_IPH
12765 if (result < 0)
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012766 return NULL;
12767 Py_RETURN_NONE;
12768}
12769#endif /* !MS_WINDOWS */
12770
12771
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012772/*[clinic input]
Eddie Elizondob3966632019-11-05 07:16:14 -080012773class os.DirEntry "DirEntry *" "DirEntryType"
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012774[clinic start generated code]*/
Eddie Elizondob3966632019-11-05 07:16:14 -080012775/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3c18c7a448247980]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012776
12777typedef struct {
12778 PyObject_HEAD
12779 PyObject *name;
12780 PyObject *path;
12781 PyObject *stat;
12782 PyObject *lstat;
12783#ifdef MS_WINDOWS
12784 struct _Py_stat_struct win32_lstat;
Victor Stinner0f6d7332017-03-09 17:34:28 +010012785 uint64_t win32_file_index;
Victor Stinner6036e442015-03-08 01:58:04 +010012786 int got_file_index;
12787#else /* POSIX */
Victor Stinner35a97c02015-03-08 02:59:09 +010012788#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012789 unsigned char d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012790#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012791 ino_t d_ino;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012792 int dir_fd;
Victor Stinner6036e442015-03-08 01:58:04 +010012793#endif
12794} DirEntry;
12795
Eddie Elizondob3966632019-11-05 07:16:14 -080012796static PyObject *
12797_disabled_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
12798{
12799 PyErr_Format(PyExc_TypeError,
12800 "cannot create '%.100s' instances", _PyType_Name(type));
12801 return NULL;
12802}
12803
Victor Stinner6036e442015-03-08 01:58:04 +010012804static void
12805DirEntry_dealloc(DirEntry *entry)
12806{
Eddie Elizondob3966632019-11-05 07:16:14 -080012807 PyTypeObject *tp = Py_TYPE(entry);
Victor Stinner6036e442015-03-08 01:58:04 +010012808 Py_XDECREF(entry->name);
12809 Py_XDECREF(entry->path);
12810 Py_XDECREF(entry->stat);
12811 Py_XDECREF(entry->lstat);
Eddie Elizondob3966632019-11-05 07:16:14 -080012812 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
12813 free_func(entry);
12814 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010012815}
12816
12817/* Forward reference */
12818static int
Victor Stinner97f33c32020-05-14 18:05:58 +020012819DirEntry_test_mode(PyTypeObject *defining_class, DirEntry *self,
12820 int follow_symlinks, unsigned short mode_bits);
Victor Stinner6036e442015-03-08 01:58:04 +010012821
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012822/*[clinic input]
12823os.DirEntry.is_symlink -> bool
Victor Stinner97f33c32020-05-14 18:05:58 +020012824 defining_class: defining_class
12825 /
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012826
12827Return True if the entry is a symbolic link; cached per entry.
12828[clinic start generated code]*/
12829
Victor Stinner6036e442015-03-08 01:58:04 +010012830static int
Victor Stinner97f33c32020-05-14 18:05:58 +020012831os_DirEntry_is_symlink_impl(DirEntry *self, PyTypeObject *defining_class)
12832/*[clinic end generated code: output=293096d589b6d47c input=e9acc5ee4d511113]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012833{
12834#ifdef MS_WINDOWS
12835 return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
Victor Stinner35a97c02015-03-08 02:59:09 +010012836#elif defined(HAVE_DIRENT_D_TYPE)
12837 /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010012838 if (self->d_type != DT_UNKNOWN)
12839 return self->d_type == DT_LNK;
12840 else
Victor Stinner97f33c32020-05-14 18:05:58 +020012841 return DirEntry_test_mode(defining_class, self, 0, S_IFLNK);
Victor Stinner35a97c02015-03-08 02:59:09 +010012842#else
12843 /* POSIX without d_type */
Victor Stinner97f33c32020-05-14 18:05:58 +020012844 return DirEntry_test_mode(defining_class, self, 0, S_IFLNK);
Victor Stinner6036e442015-03-08 01:58:04 +010012845#endif
12846}
12847
12848static PyObject *
Victor Stinner97f33c32020-05-14 18:05:58 +020012849DirEntry_fetch_stat(PyObject *module, DirEntry *self, int follow_symlinks)
Victor Stinner6036e442015-03-08 01:58:04 +010012850{
12851 int result;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012852 STRUCT_STAT st;
12853 PyObject *ub;
Victor Stinner6036e442015-03-08 01:58:04 +010012854
12855#ifdef MS_WINDOWS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012856 if (!PyUnicode_FSDecoder(self->path, &ub))
12857 return NULL;
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030012858#if USE_UNICODE_WCHAR_CACHE
12859_Py_COMP_DIAG_PUSH
12860_Py_COMP_DIAG_IGNORE_DEPR_DECLS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012861 const wchar_t *path = PyUnicode_AsUnicode(ub);
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030012862_Py_COMP_DIAG_POP
12863#else /* USE_UNICODE_WCHAR_CACHE */
12864 wchar_t *path = PyUnicode_AsWideCharString(ub, NULL);
12865 Py_DECREF(ub);
12866#endif /* USE_UNICODE_WCHAR_CACHE */
Victor Stinner6036e442015-03-08 01:58:04 +010012867#else /* POSIX */
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012868 if (!PyUnicode_FSConverter(self->path, &ub))
12869 return NULL;
12870 const char *path = PyBytes_AS_STRING(ub);
12871 if (self->dir_fd != DEFAULT_DIR_FD) {
12872#ifdef HAVE_FSTATAT
12873 result = fstatat(self->dir_fd, path, &st,
12874 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
12875#else
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030012876 Py_DECREF(ub);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012877 PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
12878 return NULL;
12879#endif /* HAVE_FSTATAT */
12880 }
12881 else
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012882#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012883 {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012884 if (follow_symlinks)
12885 result = STAT(path, &st);
12886 else
12887 result = LSTAT(path, &st);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012888 }
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030012889#if defined(MS_WINDOWS) && !USE_UNICODE_WCHAR_CACHE
12890 PyMem_Free(path);
12891#else /* USE_UNICODE_WCHAR_CACHE */
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012892 Py_DECREF(ub);
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030012893#endif /* USE_UNICODE_WCHAR_CACHE */
Victor Stinner6036e442015-03-08 01:58:04 +010012894
12895 if (result != 0)
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012896 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012897
Victor Stinner97f33c32020-05-14 18:05:58 +020012898 return _pystat_fromstructstat(module, &st);
Victor Stinner6036e442015-03-08 01:58:04 +010012899}
12900
12901static PyObject *
Victor Stinner97f33c32020-05-14 18:05:58 +020012902DirEntry_get_lstat(PyTypeObject *defining_class, DirEntry *self)
Victor Stinner6036e442015-03-08 01:58:04 +010012903{
12904 if (!self->lstat) {
Victor Stinner97f33c32020-05-14 18:05:58 +020012905 PyObject *module = PyType_GetModule(defining_class);
Victor Stinner6036e442015-03-08 01:58:04 +010012906#ifdef MS_WINDOWS
Victor Stinner97f33c32020-05-14 18:05:58 +020012907 self->lstat = _pystat_fromstructstat(module, &self->win32_lstat);
Victor Stinner6036e442015-03-08 01:58:04 +010012908#else /* POSIX */
Victor Stinner97f33c32020-05-14 18:05:58 +020012909 self->lstat = DirEntry_fetch_stat(module, self, 0);
Victor Stinner6036e442015-03-08 01:58:04 +010012910#endif
12911 }
12912 Py_XINCREF(self->lstat);
12913 return self->lstat;
12914}
12915
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012916/*[clinic input]
12917os.DirEntry.stat
Victor Stinner97f33c32020-05-14 18:05:58 +020012918 defining_class: defining_class
12919 /
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012920 *
12921 follow_symlinks: bool = True
12922
12923Return stat_result object for the entry; cached per entry.
12924[clinic start generated code]*/
12925
Victor Stinner6036e442015-03-08 01:58:04 +010012926static PyObject *
Victor Stinner97f33c32020-05-14 18:05:58 +020012927os_DirEntry_stat_impl(DirEntry *self, PyTypeObject *defining_class,
12928 int follow_symlinks)
12929/*[clinic end generated code: output=23f803e19c3e780e input=e816273c4e67ee98]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012930{
Victor Stinner97f33c32020-05-14 18:05:58 +020012931 if (!follow_symlinks) {
12932 return DirEntry_get_lstat(defining_class, self);
12933 }
Victor Stinner6036e442015-03-08 01:58:04 +010012934
12935 if (!self->stat) {
Victor Stinner97f33c32020-05-14 18:05:58 +020012936 int result = os_DirEntry_is_symlink_impl(self, defining_class);
12937 if (result == -1) {
Victor Stinner6036e442015-03-08 01:58:04 +010012938 return NULL;
Victor Stinner97f33c32020-05-14 18:05:58 +020012939 }
12940 if (result) {
12941 PyObject *module = PyType_GetModule(defining_class);
12942 self->stat = DirEntry_fetch_stat(module, self, 1);
12943 }
12944 else {
12945 self->stat = DirEntry_get_lstat(defining_class, self);
12946 }
Victor Stinner6036e442015-03-08 01:58:04 +010012947 }
12948
12949 Py_XINCREF(self->stat);
12950 return self->stat;
12951}
12952
Victor Stinner6036e442015-03-08 01:58:04 +010012953/* Set exception and return -1 on error, 0 for False, 1 for True */
12954static int
Victor Stinner97f33c32020-05-14 18:05:58 +020012955DirEntry_test_mode(PyTypeObject *defining_class, DirEntry *self,
12956 int follow_symlinks, unsigned short mode_bits)
Victor Stinner6036e442015-03-08 01:58:04 +010012957{
12958 PyObject *stat = NULL;
12959 PyObject *st_mode = NULL;
12960 long mode;
12961 int result;
Victor Stinner35a97c02015-03-08 02:59:09 +010012962#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012963 int is_symlink;
12964 int need_stat;
Victor Stinner35a97c02015-03-08 02:59:09 +010012965#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012966#ifdef MS_WINDOWS
12967 unsigned long dir_bits;
12968#endif
12969
12970#ifdef MS_WINDOWS
12971 is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
12972 need_stat = follow_symlinks && is_symlink;
Victor Stinner35a97c02015-03-08 02:59:09 +010012973#elif defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012974 is_symlink = self->d_type == DT_LNK;
12975 need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
12976#endif
12977
Victor Stinner35a97c02015-03-08 02:59:09 +010012978#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012979 if (need_stat) {
Victor Stinner35a97c02015-03-08 02:59:09 +010012980#endif
Victor Stinner97f33c32020-05-14 18:05:58 +020012981 stat = os_DirEntry_stat_impl(self, defining_class, follow_symlinks);
Victor Stinner6036e442015-03-08 01:58:04 +010012982 if (!stat) {
12983 if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
12984 /* If file doesn't exist (anymore), then return False
12985 (i.e., say it's not a file/directory) */
12986 PyErr_Clear();
12987 return 0;
12988 }
12989 goto error;
12990 }
Victor Stinner97f33c32020-05-14 18:05:58 +020012991 _posixstate* state = get_posix_state(PyType_GetModule(defining_class));
12992 st_mode = PyObject_GetAttr(stat, state->st_mode);
Victor Stinner6036e442015-03-08 01:58:04 +010012993 if (!st_mode)
12994 goto error;
12995
12996 mode = PyLong_AsLong(st_mode);
12997 if (mode == -1 && PyErr_Occurred())
12998 goto error;
12999 Py_CLEAR(st_mode);
13000 Py_CLEAR(stat);
13001 result = (mode & S_IFMT) == mode_bits;
Victor Stinner35a97c02015-03-08 02:59:09 +010013002#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010013003 }
13004 else if (is_symlink) {
13005 assert(mode_bits != S_IFLNK);
13006 result = 0;
13007 }
13008 else {
13009 assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
13010#ifdef MS_WINDOWS
13011 dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
13012 if (mode_bits == S_IFDIR)
13013 result = dir_bits != 0;
13014 else
13015 result = dir_bits == 0;
13016#else /* POSIX */
13017 if (mode_bits == S_IFDIR)
13018 result = self->d_type == DT_DIR;
13019 else
13020 result = self->d_type == DT_REG;
13021#endif
13022 }
Victor Stinner35a97c02015-03-08 02:59:09 +010013023#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013024
13025 return result;
13026
13027error:
13028 Py_XDECREF(st_mode);
13029 Py_XDECREF(stat);
13030 return -1;
13031}
13032
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013033/*[clinic input]
13034os.DirEntry.is_dir -> bool
Victor Stinner97f33c32020-05-14 18:05:58 +020013035 defining_class: defining_class
13036 /
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013037 *
13038 follow_symlinks: bool = True
Victor Stinner6036e442015-03-08 01:58:04 +010013039
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013040Return True if the entry is a directory; cached per entry.
13041[clinic start generated code]*/
13042
13043static int
Victor Stinner97f33c32020-05-14 18:05:58 +020013044os_DirEntry_is_dir_impl(DirEntry *self, PyTypeObject *defining_class,
13045 int follow_symlinks)
13046/*[clinic end generated code: output=0cd453b9c0987fdf input=1a4ffd6dec9920cb]*/
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013047{
Victor Stinner97f33c32020-05-14 18:05:58 +020013048 return DirEntry_test_mode(defining_class, self, follow_symlinks, S_IFDIR);
Victor Stinner6036e442015-03-08 01:58:04 +010013049}
13050
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013051/*[clinic input]
13052os.DirEntry.is_file -> bool
Victor Stinner97f33c32020-05-14 18:05:58 +020013053 defining_class: defining_class
13054 /
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013055 *
13056 follow_symlinks: bool = True
13057
13058Return True if the entry is a file; cached per entry.
13059[clinic start generated code]*/
13060
13061static int
Victor Stinner97f33c32020-05-14 18:05:58 +020013062os_DirEntry_is_file_impl(DirEntry *self, PyTypeObject *defining_class,
13063 int follow_symlinks)
13064/*[clinic end generated code: output=f7c277ab5ba80908 input=0a64c5a12e802e3b]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013065{
Victor Stinner97f33c32020-05-14 18:05:58 +020013066 return DirEntry_test_mode(defining_class, self, follow_symlinks, S_IFREG);
Victor Stinner6036e442015-03-08 01:58:04 +010013067}
13068
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013069/*[clinic input]
13070os.DirEntry.inode
Victor Stinner6036e442015-03-08 01:58:04 +010013071
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013072Return inode of the entry; cached per entry.
13073[clinic start generated code]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013074
13075static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013076os_DirEntry_inode_impl(DirEntry *self)
13077/*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013078{
13079#ifdef MS_WINDOWS
13080 if (!self->got_file_index) {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030013081 PyObject *unicode;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030013082 STRUCT_STAT stat;
13083 int result;
Victor Stinner6036e442015-03-08 01:58:04 +010013084
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030013085 if (!PyUnicode_FSDecoder(self->path, &unicode))
Victor Stinner6036e442015-03-08 01:58:04 +010013086 return NULL;
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030013087#if USE_UNICODE_WCHAR_CACHE
13088_Py_COMP_DIAG_PUSH
13089_Py_COMP_DIAG_IGNORE_DEPR_DECLS
13090 const wchar_t *path = PyUnicode_AsUnicode(unicode);
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030013091 result = LSTAT(path, &stat);
13092 Py_DECREF(unicode);
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030013093_Py_COMP_DIAG_POP
13094#else /* USE_UNICODE_WCHAR_CACHE */
13095 wchar_t *path = PyUnicode_AsWideCharString(unicode, NULL);
13096 Py_DECREF(unicode);
13097 result = LSTAT(path, &stat);
13098 PyMem_Free(path);
13099#endif /* USE_UNICODE_WCHAR_CACHE */
Victor Stinner6036e442015-03-08 01:58:04 +010013100
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030013101 if (result != 0)
13102 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013103
13104 self->win32_file_index = stat.st_ino;
13105 self->got_file_index = 1;
13106 }
Victor Stinner0f6d7332017-03-09 17:34:28 +010013107 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->win32_file_index));
13108 return PyLong_FromUnsignedLongLong(self->win32_file_index);
Victor Stinner6036e442015-03-08 01:58:04 +010013109#else /* POSIX */
xdegaye50e86032017-05-22 11:15:08 +020013110 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->d_ino));
13111 return PyLong_FromUnsignedLongLong(self->d_ino);
Victor Stinner6036e442015-03-08 01:58:04 +010013112#endif
13113}
13114
13115static PyObject *
13116DirEntry_repr(DirEntry *self)
13117{
13118 return PyUnicode_FromFormat("<DirEntry %R>", self->name);
13119}
13120
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013121/*[clinic input]
13122os.DirEntry.__fspath__
13123
13124Returns the path for the entry.
13125[clinic start generated code]*/
13126
Brett Cannon96881cd2016-06-10 14:37:21 -070013127static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013128os_DirEntry___fspath___impl(DirEntry *self)
13129/*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
Brett Cannon96881cd2016-06-10 14:37:21 -070013130{
13131 Py_INCREF(self->path);
13132 return self->path;
13133}
13134
Victor Stinner6036e442015-03-08 01:58:04 +010013135static PyMemberDef DirEntry_members[] = {
13136 {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
13137 "the entry's base filename, relative to scandir() \"path\" argument"},
13138 {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
13139 "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
13140 {NULL}
13141};
13142
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013143#include "clinic/posixmodule.c.h"
13144
Victor Stinner6036e442015-03-08 01:58:04 +010013145static PyMethodDef DirEntry_methods[] = {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013146 OS_DIRENTRY_IS_DIR_METHODDEF
13147 OS_DIRENTRY_IS_FILE_METHODDEF
13148 OS_DIRENTRY_IS_SYMLINK_METHODDEF
13149 OS_DIRENTRY_STAT_METHODDEF
13150 OS_DIRENTRY_INODE_METHODDEF
13151 OS_DIRENTRY___FSPATH___METHODDEF
Batuhan Taşkayaf9dd51e2020-04-08 00:37:19 +030013152 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
13153 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Victor Stinner6036e442015-03-08 01:58:04 +010013154 {NULL}
13155};
13156
Eddie Elizondob3966632019-11-05 07:16:14 -080013157static PyType_Slot DirEntryType_slots[] = {
13158 {Py_tp_new, _disabled_new},
13159 {Py_tp_dealloc, DirEntry_dealloc},
13160 {Py_tp_repr, DirEntry_repr},
13161 {Py_tp_methods, DirEntry_methods},
13162 {Py_tp_members, DirEntry_members},
13163 {0, 0},
Victor Stinner6036e442015-03-08 01:58:04 +010013164};
13165
Eddie Elizondob3966632019-11-05 07:16:14 -080013166static PyType_Spec DirEntryType_spec = {
13167 MODNAME ".DirEntry",
13168 sizeof(DirEntry),
13169 0,
13170 Py_TPFLAGS_DEFAULT,
13171 DirEntryType_slots
13172};
13173
13174
Victor Stinner6036e442015-03-08 01:58:04 +010013175#ifdef MS_WINDOWS
13176
13177static wchar_t *
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030013178join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
Victor Stinner6036e442015-03-08 01:58:04 +010013179{
13180 Py_ssize_t path_len;
13181 Py_ssize_t size;
13182 wchar_t *result;
13183 wchar_t ch;
13184
13185 if (!path_wide) { /* Default arg: "." */
13186 path_wide = L".";
13187 path_len = 1;
13188 }
13189 else {
13190 path_len = wcslen(path_wide);
13191 }
13192
13193 /* The +1's are for the path separator and the NUL */
13194 size = path_len + 1 + wcslen(filename) + 1;
13195 result = PyMem_New(wchar_t, size);
13196 if (!result) {
13197 PyErr_NoMemory();
13198 return NULL;
13199 }
13200 wcscpy(result, path_wide);
13201 if (path_len > 0) {
13202 ch = result[path_len - 1];
13203 if (ch != SEP && ch != ALTSEP && ch != L':')
13204 result[path_len++] = SEP;
13205 wcscpy(result + path_len, filename);
13206 }
13207 return result;
13208}
13209
13210static PyObject *
Victor Stinner1c2fa782020-05-10 11:05:29 +020013211DirEntry_from_find_data(PyObject *module, path_t *path, WIN32_FIND_DATAW *dataW)
Victor Stinner6036e442015-03-08 01:58:04 +010013212{
13213 DirEntry *entry;
13214 BY_HANDLE_FILE_INFORMATION file_info;
13215 ULONG reparse_tag;
13216 wchar_t *joined_path;
13217
Victor Stinner1c2fa782020-05-10 11:05:29 +020013218 PyObject *DirEntryType = get_posix_state(module)->DirEntryType;
Eddie Elizondob3966632019-11-05 07:16:14 -080013219 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010013220 if (!entry)
13221 return NULL;
13222 entry->name = NULL;
13223 entry->path = NULL;
13224 entry->stat = NULL;
13225 entry->lstat = NULL;
13226 entry->got_file_index = 0;
13227
13228 entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
13229 if (!entry->name)
13230 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070013231 if (path->narrow) {
13232 Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
13233 if (!entry->name)
13234 goto error;
13235 }
Victor Stinner6036e442015-03-08 01:58:04 +010013236
13237 joined_path = join_path_filenameW(path->wide, dataW->cFileName);
13238 if (!joined_path)
13239 goto error;
13240
13241 entry->path = PyUnicode_FromWideChar(joined_path, -1);
13242 PyMem_Free(joined_path);
13243 if (!entry->path)
13244 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070013245 if (path->narrow) {
13246 Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
13247 if (!entry->path)
13248 goto error;
13249 }
Victor Stinner6036e442015-03-08 01:58:04 +010013250
Steve Dowercc16be82016-09-08 10:35:16 -070013251 find_data_to_file_info(dataW, &file_info, &reparse_tag);
Victor Stinner6036e442015-03-08 01:58:04 +010013252 _Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
13253
13254 return (PyObject *)entry;
13255
13256error:
13257 Py_DECREF(entry);
13258 return NULL;
13259}
13260
13261#else /* POSIX */
13262
13263static char *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020013264join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
Victor Stinner6036e442015-03-08 01:58:04 +010013265{
13266 Py_ssize_t path_len;
13267 Py_ssize_t size;
13268 char *result;
13269
13270 if (!path_narrow) { /* Default arg: "." */
13271 path_narrow = ".";
13272 path_len = 1;
13273 }
13274 else {
13275 path_len = strlen(path_narrow);
13276 }
13277
13278 if (filename_len == -1)
13279 filename_len = strlen(filename);
13280
13281 /* The +1's are for the path separator and the NUL */
13282 size = path_len + 1 + filename_len + 1;
13283 result = PyMem_New(char, size);
13284 if (!result) {
13285 PyErr_NoMemory();
13286 return NULL;
13287 }
13288 strcpy(result, path_narrow);
13289 if (path_len > 0 && result[path_len - 1] != '/')
13290 result[path_len++] = '/';
13291 strcpy(result + path_len, filename);
13292 return result;
13293}
13294
13295static PyObject *
Victor Stinner1c2fa782020-05-10 11:05:29 +020013296DirEntry_from_posix_info(PyObject *module, path_t *path, const char *name,
13297 Py_ssize_t name_len, ino_t d_ino
Victor Stinner35a97c02015-03-08 02:59:09 +010013298#ifdef HAVE_DIRENT_D_TYPE
13299 , unsigned char d_type
13300#endif
13301 )
Victor Stinner6036e442015-03-08 01:58:04 +010013302{
13303 DirEntry *entry;
13304 char *joined_path;
13305
Victor Stinner1c2fa782020-05-10 11:05:29 +020013306 PyObject *DirEntryType = get_posix_state(module)->DirEntryType;
Eddie Elizondob3966632019-11-05 07:16:14 -080013307 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010013308 if (!entry)
13309 return NULL;
13310 entry->name = NULL;
13311 entry->path = NULL;
13312 entry->stat = NULL;
13313 entry->lstat = NULL;
13314
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013315 if (path->fd != -1) {
13316 entry->dir_fd = path->fd;
13317 joined_path = NULL;
13318 }
13319 else {
13320 entry->dir_fd = DEFAULT_DIR_FD;
13321 joined_path = join_path_filename(path->narrow, name, name_len);
13322 if (!joined_path)
13323 goto error;
13324 }
Victor Stinner6036e442015-03-08 01:58:04 +010013325
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +030013326 if (!path->narrow || !PyObject_CheckBuffer(path->object)) {
Victor Stinner6036e442015-03-08 01:58:04 +010013327 entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013328 if (joined_path)
13329 entry->path = PyUnicode_DecodeFSDefault(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013330 }
13331 else {
13332 entry->name = PyBytes_FromStringAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013333 if (joined_path)
13334 entry->path = PyBytes_FromString(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013335 }
13336 PyMem_Free(joined_path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013337 if (!entry->name)
13338 goto error;
13339
13340 if (path->fd != -1) {
13341 entry->path = entry->name;
13342 Py_INCREF(entry->path);
13343 }
13344 else if (!entry->path)
Victor Stinner6036e442015-03-08 01:58:04 +010013345 goto error;
13346
Victor Stinner35a97c02015-03-08 02:59:09 +010013347#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010013348 entry->d_type = d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010013349#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013350 entry->d_ino = d_ino;
13351
13352 return (PyObject *)entry;
13353
13354error:
13355 Py_XDECREF(entry);
13356 return NULL;
13357}
13358
13359#endif
13360
13361
13362typedef struct {
13363 PyObject_HEAD
13364 path_t path;
13365#ifdef MS_WINDOWS
13366 HANDLE handle;
13367 WIN32_FIND_DATAW file_data;
13368 int first_time;
13369#else /* POSIX */
13370 DIR *dirp;
13371#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013372#ifdef HAVE_FDOPENDIR
13373 int fd;
13374#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013375} ScandirIterator;
13376
13377#ifdef MS_WINDOWS
13378
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013379static int
13380ScandirIterator_is_closed(ScandirIterator *iterator)
13381{
13382 return iterator->handle == INVALID_HANDLE_VALUE;
13383}
13384
Victor Stinner6036e442015-03-08 01:58:04 +010013385static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013386ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013387{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013388 HANDLE handle = iterator->handle;
13389
13390 if (handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013391 return;
13392
Victor Stinner6036e442015-03-08 01:58:04 +010013393 iterator->handle = INVALID_HANDLE_VALUE;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013394 Py_BEGIN_ALLOW_THREADS
13395 FindClose(handle);
13396 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013397}
13398
13399static PyObject *
13400ScandirIterator_iternext(ScandirIterator *iterator)
13401{
13402 WIN32_FIND_DATAW *file_data = &iterator->file_data;
13403 BOOL success;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013404 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013405
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013406 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013407 if (iterator->handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013408 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013409
13410 while (1) {
13411 if (!iterator->first_time) {
13412 Py_BEGIN_ALLOW_THREADS
13413 success = FindNextFileW(iterator->handle, file_data);
13414 Py_END_ALLOW_THREADS
13415 if (!success) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013416 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013417 if (GetLastError() != ERROR_NO_MORE_FILES)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013418 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013419 break;
13420 }
13421 }
13422 iterator->first_time = 0;
13423
13424 /* Skip over . and .. */
13425 if (wcscmp(file_data->cFileName, L".") != 0 &&
Victor Stinner1c2fa782020-05-10 11:05:29 +020013426 wcscmp(file_data->cFileName, L"..") != 0)
13427 {
13428 PyObject *module = PyType_GetModule(Py_TYPE(iterator));
13429 entry = DirEntry_from_find_data(module, &iterator->path, file_data);
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013430 if (!entry)
13431 break;
13432 return entry;
13433 }
Victor Stinner6036e442015-03-08 01:58:04 +010013434
13435 /* Loop till we get a non-dot directory or finish iterating */
13436 }
13437
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013438 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013439 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013440 return NULL;
13441}
13442
13443#else /* POSIX */
13444
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013445static int
13446ScandirIterator_is_closed(ScandirIterator *iterator)
13447{
13448 return !iterator->dirp;
13449}
13450
Victor Stinner6036e442015-03-08 01:58:04 +010013451static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013452ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013453{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013454 DIR *dirp = iterator->dirp;
13455
13456 if (!dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013457 return;
13458
Victor Stinner6036e442015-03-08 01:58:04 +010013459 iterator->dirp = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013460 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013461#ifdef HAVE_FDOPENDIR
13462 if (iterator->path.fd != -1)
13463 rewinddir(dirp);
13464#endif
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013465 closedir(dirp);
13466 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013467 return;
13468}
13469
13470static PyObject *
13471ScandirIterator_iternext(ScandirIterator *iterator)
13472{
13473 struct dirent *direntp;
13474 Py_ssize_t name_len;
13475 int is_dot;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013476 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013477
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013478 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013479 if (!iterator->dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013480 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013481
13482 while (1) {
13483 errno = 0;
13484 Py_BEGIN_ALLOW_THREADS
13485 direntp = readdir(iterator->dirp);
13486 Py_END_ALLOW_THREADS
13487
13488 if (!direntp) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013489 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013490 if (errno != 0)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013491 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013492 break;
13493 }
13494
13495 /* Skip over . and .. */
13496 name_len = NAMLEN(direntp);
13497 is_dot = direntp->d_name[0] == '.' &&
13498 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
13499 if (!is_dot) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020013500 PyObject *module = PyType_GetModule(Py_TYPE(iterator));
13501 entry = DirEntry_from_posix_info(module,
13502 &iterator->path, direntp->d_name,
13503 name_len, direntp->d_ino
Victor Stinner35a97c02015-03-08 02:59:09 +010013504#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner1c2fa782020-05-10 11:05:29 +020013505 , direntp->d_type
Victor Stinner35a97c02015-03-08 02:59:09 +010013506#endif
13507 );
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013508 if (!entry)
13509 break;
13510 return entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013511 }
13512
13513 /* Loop till we get a non-dot directory or finish iterating */
13514 }
13515
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013516 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013517 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013518 return NULL;
13519}
13520
13521#endif
13522
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013523static PyObject *
13524ScandirIterator_close(ScandirIterator *self, PyObject *args)
13525{
13526 ScandirIterator_closedir(self);
13527 Py_RETURN_NONE;
13528}
13529
13530static PyObject *
13531ScandirIterator_enter(PyObject *self, PyObject *args)
13532{
13533 Py_INCREF(self);
13534 return self;
13535}
13536
13537static PyObject *
13538ScandirIterator_exit(ScandirIterator *self, PyObject *args)
13539{
13540 ScandirIterator_closedir(self);
13541 Py_RETURN_NONE;
13542}
13543
Victor Stinner6036e442015-03-08 01:58:04 +010013544static void
Victor Stinner7bfa4092016-03-23 00:43:54 +010013545ScandirIterator_finalize(ScandirIterator *iterator)
13546{
13547 PyObject *error_type, *error_value, *error_traceback;
13548
13549 /* Save the current exception, if any. */
13550 PyErr_Fetch(&error_type, &error_value, &error_traceback);
13551
13552 if (!ScandirIterator_is_closed(iterator)) {
13553 ScandirIterator_closedir(iterator);
13554
13555 if (PyErr_ResourceWarning((PyObject *)iterator, 1,
13556 "unclosed scandir iterator %R", iterator)) {
13557 /* Spurious errors can appear at shutdown */
13558 if (PyErr_ExceptionMatches(PyExc_Warning)) {
13559 PyErr_WriteUnraisable((PyObject *) iterator);
13560 }
13561 }
13562 }
13563
Victor Stinner7bfa4092016-03-23 00:43:54 +010013564 path_cleanup(&iterator->path);
13565
13566 /* Restore the saved exception. */
13567 PyErr_Restore(error_type, error_value, error_traceback);
13568}
13569
13570static void
Victor Stinner6036e442015-03-08 01:58:04 +010013571ScandirIterator_dealloc(ScandirIterator *iterator)
13572{
Eddie Elizondob3966632019-11-05 07:16:14 -080013573 PyTypeObject *tp = Py_TYPE(iterator);
Victor Stinner7bfa4092016-03-23 00:43:54 +010013574 if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
13575 return;
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013576
Eddie Elizondob3966632019-11-05 07:16:14 -080013577 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
13578 free_func(iterator);
13579 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010013580}
13581
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013582static PyMethodDef ScandirIterator_methods[] = {
13583 {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
13584 {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
13585 {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
13586 {NULL}
13587};
13588
Eddie Elizondob3966632019-11-05 07:16:14 -080013589static PyType_Slot ScandirIteratorType_slots[] = {
13590 {Py_tp_new, _disabled_new},
13591 {Py_tp_dealloc, ScandirIterator_dealloc},
13592 {Py_tp_finalize, ScandirIterator_finalize},
13593 {Py_tp_iter, PyObject_SelfIter},
13594 {Py_tp_iternext, ScandirIterator_iternext},
13595 {Py_tp_methods, ScandirIterator_methods},
13596 {0, 0},
13597};
13598
13599static PyType_Spec ScandirIteratorType_spec = {
13600 MODNAME ".ScandirIterator",
13601 sizeof(ScandirIterator),
13602 0,
Victor Stinner97f33c32020-05-14 18:05:58 +020013603 // bpo-40549: Py_TPFLAGS_BASETYPE should not be used, since
13604 // PyType_GetModule(Py_TYPE(self)) doesn't work on a subclass instance.
Eddie Elizondob3966632019-11-05 07:16:14 -080013605 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE,
13606 ScandirIteratorType_slots
Victor Stinner6036e442015-03-08 01:58:04 +010013607};
13608
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013609/*[clinic input]
13610os.scandir
13611
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013612 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013613
13614Return an iterator of DirEntry objects for given path.
13615
BNMetricsb9427072018-11-02 15:20:19 +000013616path can be specified as either str, bytes, or a path-like object. If path
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013617is bytes, the names of yielded DirEntry objects will also be bytes; in
13618all other circumstances they will be str.
13619
13620If path is None, uses the path='.'.
13621[clinic start generated code]*/
13622
Victor Stinner6036e442015-03-08 01:58:04 +010013623static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013624os_scandir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +000013625/*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013626{
13627 ScandirIterator *iterator;
Victor Stinner6036e442015-03-08 01:58:04 +010013628#ifdef MS_WINDOWS
13629 wchar_t *path_strW;
13630#else
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013631 const char *path_str;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013632#ifdef HAVE_FDOPENDIR
13633 int fd = -1;
13634#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013635#endif
13636
Steve Dower60419a72019-06-24 08:42:54 -070013637 if (PySys_Audit("os.scandir", "O",
13638 path->object ? path->object : Py_None) < 0) {
13639 return NULL;
13640 }
13641
Hai Shif707d942020-03-16 21:15:01 +080013642 PyObject *ScandirIteratorType = get_posix_state(module)->ScandirIteratorType;
Eddie Elizondob3966632019-11-05 07:16:14 -080013643 iterator = PyObject_New(ScandirIterator, (PyTypeObject *)ScandirIteratorType);
Victor Stinner6036e442015-03-08 01:58:04 +010013644 if (!iterator)
13645 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013646
13647#ifdef MS_WINDOWS
13648 iterator->handle = INVALID_HANDLE_VALUE;
13649#else
13650 iterator->dirp = NULL;
13651#endif
13652
Serhiy Storchaka095ef732017-02-09 20:05:51 +020013653 /* Move the ownership to iterator->path */
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030013654 memcpy(&iterator->path, path, sizeof(path_t));
13655 memset(path, 0, sizeof(path_t));
Victor Stinner6036e442015-03-08 01:58:04 +010013656
13657#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +010013658 iterator->first_time = 1;
13659
13660 path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
13661 if (!path_strW)
13662 goto error;
13663
13664 Py_BEGIN_ALLOW_THREADS
13665 iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
13666 Py_END_ALLOW_THREADS
13667
13668 PyMem_Free(path_strW);
13669
13670 if (iterator->handle == INVALID_HANDLE_VALUE) {
13671 path_error(&iterator->path);
13672 goto error;
13673 }
13674#else /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010013675 errno = 0;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013676#ifdef HAVE_FDOPENDIR
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030013677 if (iterator->path.fd != -1) {
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013678 /* closedir() closes the FD, so we duplicate it */
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030013679 fd = _Py_dup(iterator->path.fd);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013680 if (fd == -1)
13681 goto error;
13682
13683 Py_BEGIN_ALLOW_THREADS
13684 iterator->dirp = fdopendir(fd);
13685 Py_END_ALLOW_THREADS
13686 }
13687 else
13688#endif
13689 {
13690 if (iterator->path.narrow)
13691 path_str = iterator->path.narrow;
13692 else
13693 path_str = ".";
13694
13695 Py_BEGIN_ALLOW_THREADS
13696 iterator->dirp = opendir(path_str);
13697 Py_END_ALLOW_THREADS
13698 }
Victor Stinner6036e442015-03-08 01:58:04 +010013699
13700 if (!iterator->dirp) {
13701 path_error(&iterator->path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013702#ifdef HAVE_FDOPENDIR
13703 if (fd != -1) {
13704 Py_BEGIN_ALLOW_THREADS
13705 close(fd);
13706 Py_END_ALLOW_THREADS
13707 }
13708#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013709 goto error;
13710 }
13711#endif
13712
13713 return (PyObject *)iterator;
13714
13715error:
13716 Py_DECREF(iterator);
13717 return NULL;
13718}
13719
Ethan Furman410ef8e2016-06-04 12:06:26 -070013720/*
13721 Return the file system path representation of the object.
13722
13723 If the object is str or bytes, then allow it to pass through with
13724 an incremented refcount. If the object defines __fspath__(), then
13725 return the result of that method. All other types raise a TypeError.
13726*/
13727PyObject *
13728PyOS_FSPath(PyObject *path)
13729{
Brett Cannon3f9183b2016-08-26 14:44:48 -070013730 /* For error message reasons, this function is manually inlined in
13731 path_converter(). */
Ethan Furman410ef8e2016-06-04 12:06:26 -070013732 PyObject *func = NULL;
13733 PyObject *path_repr = NULL;
13734
13735 if (PyUnicode_Check(path) || PyBytes_Check(path)) {
13736 Py_INCREF(path);
13737 return path;
13738 }
13739
13740 func = _PyObject_LookupSpecial(path, &PyId___fspath__);
13741 if (NULL == func) {
13742 return PyErr_Format(PyExc_TypeError,
13743 "expected str, bytes or os.PathLike object, "
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013744 "not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -080013745 _PyType_Name(Py_TYPE(path)));
Ethan Furman410ef8e2016-06-04 12:06:26 -070013746 }
13747
Victor Stinnerf17c3de2016-12-06 18:46:19 +010013748 path_repr = _PyObject_CallNoArg(func);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013749 Py_DECREF(func);
Brett Cannon044283a2016-07-15 10:41:49 -070013750 if (NULL == path_repr) {
13751 return NULL;
13752 }
13753
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013754 if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
13755 PyErr_Format(PyExc_TypeError,
13756 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -080013757 "not %.200s", _PyType_Name(Py_TYPE(path)),
13758 _PyType_Name(Py_TYPE(path_repr)));
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013759 Py_DECREF(path_repr);
13760 return NULL;
13761 }
13762
Ethan Furman410ef8e2016-06-04 12:06:26 -070013763 return path_repr;
13764}
13765
13766/*[clinic input]
13767os.fspath
13768
13769 path: object
13770
13771Return the file system path representation of the object.
13772
Brett Cannonb4f43e92016-06-09 14:32:08 -070013773If the object is str or bytes, then allow it to pass through as-is. If the
13774object defines __fspath__(), then return the result of that method. All other
13775types raise a TypeError.
Ethan Furman410ef8e2016-06-04 12:06:26 -070013776[clinic start generated code]*/
13777
13778static PyObject *
Serhiy Storchaka2954f832016-07-07 18:20:03 +030013779os_fspath_impl(PyObject *module, PyObject *path)
13780/*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
Ethan Furman410ef8e2016-06-04 12:06:26 -070013781{
13782 return PyOS_FSPath(path);
13783}
Victor Stinner6036e442015-03-08 01:58:04 +010013784
Victor Stinner9b1f4742016-09-06 16:18:52 -070013785#ifdef HAVE_GETRANDOM_SYSCALL
13786/*[clinic input]
13787os.getrandom
13788
13789 size: Py_ssize_t
13790 flags: int=0
13791
13792Obtain a series of random bytes.
13793[clinic start generated code]*/
13794
13795static PyObject *
13796os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
13797/*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
13798{
Victor Stinner9b1f4742016-09-06 16:18:52 -070013799 PyObject *bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013800 Py_ssize_t n;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013801
13802 if (size < 0) {
13803 errno = EINVAL;
13804 return posix_error();
13805 }
13806
Victor Stinnerec2319c2016-09-20 23:00:59 +020013807 bytes = PyBytes_FromStringAndSize(NULL, size);
13808 if (bytes == NULL) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013809 PyErr_NoMemory();
13810 return NULL;
13811 }
13812
13813 while (1) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013814 n = syscall(SYS_getrandom,
13815 PyBytes_AS_STRING(bytes),
13816 PyBytes_GET_SIZE(bytes),
13817 flags);
Victor Stinner9b1f4742016-09-06 16:18:52 -070013818 if (n < 0 && errno == EINTR) {
13819 if (PyErr_CheckSignals() < 0) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013820 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013821 }
Victor Stinnerec2319c2016-09-20 23:00:59 +020013822
13823 /* getrandom() was interrupted by a signal: retry */
Victor Stinner9b1f4742016-09-06 16:18:52 -070013824 continue;
13825 }
13826 break;
13827 }
13828
13829 if (n < 0) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013830 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerec2319c2016-09-20 23:00:59 +020013831 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013832 }
13833
Victor Stinnerec2319c2016-09-20 23:00:59 +020013834 if (n != size) {
13835 _PyBytes_Resize(&bytes, n);
13836 }
Victor Stinner9b1f4742016-09-06 16:18:52 -070013837
13838 return bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013839
13840error:
13841 Py_DECREF(bytes);
13842 return NULL;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013843}
13844#endif /* HAVE_GETRANDOM_SYSCALL */
13845
Steve Dower2438cdf2019-03-29 16:37:16 -070013846#ifdef MS_WINDOWS
13847/* bpo-36085: Helper functions for managing DLL search directories
13848 * on win32
13849 */
13850
13851typedef DLL_DIRECTORY_COOKIE (WINAPI *PAddDllDirectory)(PCWSTR newDirectory);
13852typedef BOOL (WINAPI *PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE cookie);
13853
13854/*[clinic input]
13855os._add_dll_directory
13856
13857 path: path_t
13858
13859Add a path to the DLL search path.
13860
13861This search path is used when resolving dependencies for imported
13862extension modules (the module itself is resolved through sys.path),
13863and also by ctypes.
13864
13865Returns an opaque value that may be passed to os.remove_dll_directory
13866to remove this directory from the search path.
13867[clinic start generated code]*/
13868
13869static PyObject *
13870os__add_dll_directory_impl(PyObject *module, path_t *path)
13871/*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
13872{
13873 HMODULE hKernel32;
13874 PAddDllDirectory AddDllDirectory;
13875 DLL_DIRECTORY_COOKIE cookie = 0;
13876 DWORD err = 0;
13877
Saiyang Gou7514f4f2020-02-12 23:47:42 -080013878 if (PySys_Audit("os.add_dll_directory", "(O)", path->object) < 0) {
13879 return NULL;
13880 }
13881
Steve Dower2438cdf2019-03-29 16:37:16 -070013882 /* For Windows 7, we have to load this. As this will be a fairly
13883 infrequent operation, just do it each time. Kernel32 is always
13884 loaded. */
13885 Py_BEGIN_ALLOW_THREADS
13886 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13887 !(AddDllDirectory = (PAddDllDirectory)GetProcAddress(
13888 hKernel32, "AddDllDirectory")) ||
13889 !(cookie = (*AddDllDirectory)(path->wide))) {
13890 err = GetLastError();
13891 }
13892 Py_END_ALLOW_THREADS
13893
13894 if (err) {
13895 return win32_error_object_err("add_dll_directory",
13896 path->object, err);
13897 }
13898
13899 return PyCapsule_New(cookie, "DLL directory cookie", NULL);
13900}
13901
13902/*[clinic input]
13903os._remove_dll_directory
13904
13905 cookie: object
13906
13907Removes a path from the DLL search path.
13908
13909The parameter is an opaque value that was returned from
13910os.add_dll_directory. You can only remove directories that you added
13911yourself.
13912[clinic start generated code]*/
13913
13914static PyObject *
13915os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
13916/*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
13917{
13918 HMODULE hKernel32;
13919 PRemoveDllDirectory RemoveDllDirectory;
13920 DLL_DIRECTORY_COOKIE cookieValue;
13921 DWORD err = 0;
13922
13923 if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
13924 PyErr_SetString(PyExc_TypeError,
13925 "Provided cookie was not returned from os.add_dll_directory");
13926 return NULL;
13927 }
13928
13929 cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
13930 cookie, "DLL directory cookie");
13931
13932 /* For Windows 7, we have to load this. As this will be a fairly
13933 infrequent operation, just do it each time. Kernel32 is always
13934 loaded. */
13935 Py_BEGIN_ALLOW_THREADS
13936 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13937 !(RemoveDllDirectory = (PRemoveDllDirectory)GetProcAddress(
13938 hKernel32, "RemoveDllDirectory")) ||
13939 !(*RemoveDllDirectory)(cookieValue)) {
13940 err = GetLastError();
13941 }
13942 Py_END_ALLOW_THREADS
13943
13944 if (err) {
13945 return win32_error_object_err("remove_dll_directory",
13946 NULL, err);
13947 }
13948
13949 if (PyCapsule_SetName(cookie, NULL)) {
13950 return NULL;
13951 }
13952
13953 Py_RETURN_NONE;
13954}
13955
13956#endif
Larry Hastings31826802013-10-19 00:09:25 -070013957
Victor Stinner65a796e2020-04-01 18:49:29 +020013958
13959/* Only check if WIFEXITED is available: expect that it comes
13960 with WEXITSTATUS, WIFSIGNALED, etc.
13961
13962 os.waitstatus_to_exitcode() is implemented in C and not in Python, so
13963 subprocess can safely call it during late Python finalization without
13964 risking that used os attributes were set to None by _PyImport_Cleanup(). */
13965#if defined(WIFEXITED) || defined(MS_WINDOWS)
13966/*[clinic input]
13967os.waitstatus_to_exitcode
13968
Victor Stinner9bee32b2020-04-22 16:30:35 +020013969 status as status_obj: object
Victor Stinner65a796e2020-04-01 18:49:29 +020013970
13971Convert a wait status to an exit code.
13972
13973On Unix:
13974
13975* If WIFEXITED(status) is true, return WEXITSTATUS(status).
13976* If WIFSIGNALED(status) is true, return -WTERMSIG(status).
13977* Otherwise, raise a ValueError.
13978
13979On Windows, return status shifted right by 8 bits.
13980
13981On Unix, if the process is being traced or if waitpid() was called with
13982WUNTRACED option, the caller must first check if WIFSTOPPED(status) is true.
13983This function must not be called if WIFSTOPPED(status) is true.
13984[clinic start generated code]*/
13985
13986static PyObject *
Victor Stinner9bee32b2020-04-22 16:30:35 +020013987os_waitstatus_to_exitcode_impl(PyObject *module, PyObject *status_obj)
13988/*[clinic end generated code: output=db50b1b0ba3c7153 input=7fe2d7fdaea3db42]*/
Victor Stinner65a796e2020-04-01 18:49:29 +020013989{
13990#ifndef MS_WINDOWS
Victor Stinner9bee32b2020-04-22 16:30:35 +020013991 int status = _PyLong_AsInt(status_obj);
13992 if (status == -1 && PyErr_Occurred()) {
13993 return NULL;
13994 }
13995
Victor Stinner65a796e2020-04-01 18:49:29 +020013996 WAIT_TYPE wait_status;
13997 WAIT_STATUS_INT(wait_status) = status;
13998 int exitcode;
13999 if (WIFEXITED(wait_status)) {
14000 exitcode = WEXITSTATUS(wait_status);
14001 /* Sanity check to provide warranty on the function behavior.
14002 It should not occur in practice */
14003 if (exitcode < 0) {
14004 PyErr_Format(PyExc_ValueError, "invalid WEXITSTATUS: %i", exitcode);
14005 return NULL;
14006 }
14007 }
14008 else if (WIFSIGNALED(wait_status)) {
14009 int signum = WTERMSIG(wait_status);
14010 /* Sanity check to provide warranty on the function behavior.
14011 It should not occurs in practice */
14012 if (signum <= 0) {
14013 PyErr_Format(PyExc_ValueError, "invalid WTERMSIG: %i", signum);
14014 return NULL;
14015 }
14016 exitcode = -signum;
14017 } else if (WIFSTOPPED(wait_status)) {
14018 /* Status only received if the process is being traced
14019 or if waitpid() was called with WUNTRACED option. */
14020 int signum = WSTOPSIG(wait_status);
14021 PyErr_Format(PyExc_ValueError,
14022 "process stopped by delivery of signal %i",
14023 signum);
14024 return NULL;
14025 }
14026 else {
14027 PyErr_Format(PyExc_ValueError, "invalid wait status: %i", status);
14028 return NULL;
14029 }
14030 return PyLong_FromLong(exitcode);
14031#else
14032 /* Windows implementation: see os.waitpid() implementation
14033 which uses _cwait(). */
Victor Stinner9bee32b2020-04-22 16:30:35 +020014034 unsigned long long status = PyLong_AsUnsignedLongLong(status_obj);
14035 if (status == (unsigned long long)-1 && PyErr_Occurred()) {
14036 return NULL;
14037 }
14038
14039 unsigned long long exitcode = (status >> 8);
14040 /* ExitProcess() accepts an UINT type:
14041 reject exit code which doesn't fit in an UINT */
14042 if (exitcode > UINT_MAX) {
14043 PyErr_Format(PyExc_ValueError, "invalid exit code: %llu", exitcode);
14044 return NULL;
14045 }
14046 return PyLong_FromUnsignedLong((unsigned long)exitcode);
Victor Stinner65a796e2020-04-01 18:49:29 +020014047#endif
14048}
14049#endif
14050
14051
Fred Drake5ab8eaf1999-12-09 21:13:07 +000014052static PyMethodDef posix_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -070014053
14054 OS_STAT_METHODDEF
14055 OS_ACCESS_METHODDEF
14056 OS_TTYNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014057 OS_CHDIR_METHODDEF
14058 OS_CHFLAGS_METHODDEF
14059 OS_CHMOD_METHODDEF
14060 OS_FCHMOD_METHODDEF
14061 OS_LCHMOD_METHODDEF
14062 OS_CHOWN_METHODDEF
14063 OS_FCHOWN_METHODDEF
14064 OS_LCHOWN_METHODDEF
14065 OS_LCHFLAGS_METHODDEF
14066 OS_CHROOT_METHODDEF
14067 OS_CTERMID_METHODDEF
14068 OS_GETCWD_METHODDEF
14069 OS_GETCWDB_METHODDEF
14070 OS_LINK_METHODDEF
14071 OS_LISTDIR_METHODDEF
14072 OS_LSTAT_METHODDEF
14073 OS_MKDIR_METHODDEF
14074 OS_NICE_METHODDEF
14075 OS_GETPRIORITY_METHODDEF
14076 OS_SETPRIORITY_METHODDEF
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000014077 OS_POSIX_SPAWN_METHODDEF
Joannah Nanjekye92b83222019-01-16 16:29:26 +030014078 OS_POSIX_SPAWNP_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030014079 OS_READLINK_METHODDEF
Pablo Galindoaac4d032019-05-31 19:39:47 +010014080 OS_COPY_FILE_RANGE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014081 OS_RENAME_METHODDEF
14082 OS_REPLACE_METHODDEF
14083 OS_RMDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014084 OS_SYMLINK_METHODDEF
14085 OS_SYSTEM_METHODDEF
14086 OS_UMASK_METHODDEF
14087 OS_UNAME_METHODDEF
14088 OS_UNLINK_METHODDEF
14089 OS_REMOVE_METHODDEF
14090 OS_UTIME_METHODDEF
14091 OS_TIMES_METHODDEF
14092 OS__EXIT_METHODDEF
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020014093 OS__FCOPYFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014094 OS_EXECV_METHODDEF
14095 OS_EXECVE_METHODDEF
14096 OS_SPAWNV_METHODDEF
14097 OS_SPAWNVE_METHODDEF
14098 OS_FORK1_METHODDEF
14099 OS_FORK_METHODDEF
Antoine Pitrou346cbd32017-05-27 17:50:54 +020014100 OS_REGISTER_AT_FORK_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014101 OS_SCHED_GET_PRIORITY_MAX_METHODDEF
14102 OS_SCHED_GET_PRIORITY_MIN_METHODDEF
14103 OS_SCHED_GETPARAM_METHODDEF
14104 OS_SCHED_GETSCHEDULER_METHODDEF
14105 OS_SCHED_RR_GET_INTERVAL_METHODDEF
14106 OS_SCHED_SETPARAM_METHODDEF
14107 OS_SCHED_SETSCHEDULER_METHODDEF
14108 OS_SCHED_YIELD_METHODDEF
14109 OS_SCHED_SETAFFINITY_METHODDEF
14110 OS_SCHED_GETAFFINITY_METHODDEF
14111 OS_OPENPTY_METHODDEF
14112 OS_FORKPTY_METHODDEF
14113 OS_GETEGID_METHODDEF
14114 OS_GETEUID_METHODDEF
14115 OS_GETGID_METHODDEF
Serhiy Storchaka2b560312020-04-18 19:14:10 +030014116 OS_GETGROUPLIST_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014117 OS_GETGROUPS_METHODDEF
14118 OS_GETPID_METHODDEF
14119 OS_GETPGRP_METHODDEF
14120 OS_GETPPID_METHODDEF
14121 OS_GETUID_METHODDEF
14122 OS_GETLOGIN_METHODDEF
14123 OS_KILL_METHODDEF
14124 OS_KILLPG_METHODDEF
14125 OS_PLOCK_METHODDEF
Steve Dowercc16be82016-09-08 10:35:16 -070014126 OS_STARTFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014127 OS_SETUID_METHODDEF
14128 OS_SETEUID_METHODDEF
14129 OS_SETREUID_METHODDEF
14130 OS_SETGID_METHODDEF
14131 OS_SETEGID_METHODDEF
14132 OS_SETREGID_METHODDEF
14133 OS_SETGROUPS_METHODDEF
Serhiy Storchaka2b560312020-04-18 19:14:10 +030014134 OS_INITGROUPS_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014135 OS_GETPGID_METHODDEF
14136 OS_SETPGRP_METHODDEF
14137 OS_WAIT_METHODDEF
14138 OS_WAIT3_METHODDEF
14139 OS_WAIT4_METHODDEF
14140 OS_WAITID_METHODDEF
14141 OS_WAITPID_METHODDEF
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -080014142 OS_PIDFD_OPEN_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014143 OS_GETSID_METHODDEF
14144 OS_SETSID_METHODDEF
14145 OS_SETPGID_METHODDEF
14146 OS_TCGETPGRP_METHODDEF
14147 OS_TCSETPGRP_METHODDEF
14148 OS_OPEN_METHODDEF
14149 OS_CLOSE_METHODDEF
14150 OS_CLOSERANGE_METHODDEF
14151 OS_DEVICE_ENCODING_METHODDEF
14152 OS_DUP_METHODDEF
14153 OS_DUP2_METHODDEF
14154 OS_LOCKF_METHODDEF
14155 OS_LSEEK_METHODDEF
14156 OS_READ_METHODDEF
14157 OS_READV_METHODDEF
14158 OS_PREAD_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000014159 OS_PREADV_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014160 OS_WRITE_METHODDEF
14161 OS_WRITEV_METHODDEF
14162 OS_PWRITE_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000014163 OS_PWRITEV_METHODDEF
Serhiy Storchaka2b560312020-04-18 19:14:10 +030014164 OS_SENDFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014165 OS_FSTAT_METHODDEF
14166 OS_ISATTY_METHODDEF
14167 OS_PIPE_METHODDEF
14168 OS_PIPE2_METHODDEF
14169 OS_MKFIFO_METHODDEF
14170 OS_MKNOD_METHODDEF
14171 OS_MAJOR_METHODDEF
14172 OS_MINOR_METHODDEF
14173 OS_MAKEDEV_METHODDEF
14174 OS_FTRUNCATE_METHODDEF
14175 OS_TRUNCATE_METHODDEF
14176 OS_POSIX_FALLOCATE_METHODDEF
14177 OS_POSIX_FADVISE_METHODDEF
14178 OS_PUTENV_METHODDEF
14179 OS_UNSETENV_METHODDEF
14180 OS_STRERROR_METHODDEF
14181 OS_FCHDIR_METHODDEF
14182 OS_FSYNC_METHODDEF
14183 OS_SYNC_METHODDEF
14184 OS_FDATASYNC_METHODDEF
14185 OS_WCOREDUMP_METHODDEF
14186 OS_WIFCONTINUED_METHODDEF
14187 OS_WIFSTOPPED_METHODDEF
14188 OS_WIFSIGNALED_METHODDEF
14189 OS_WIFEXITED_METHODDEF
14190 OS_WEXITSTATUS_METHODDEF
14191 OS_WTERMSIG_METHODDEF
14192 OS_WSTOPSIG_METHODDEF
14193 OS_FSTATVFS_METHODDEF
14194 OS_STATVFS_METHODDEF
14195 OS_CONFSTR_METHODDEF
14196 OS_SYSCONF_METHODDEF
14197 OS_FPATHCONF_METHODDEF
14198 OS_PATHCONF_METHODDEF
14199 OS_ABORT_METHODDEF
Serhiy Storchakaf0b50152015-05-13 00:52:39 +030014200 OS__GETFULLPATHNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014201 OS__GETDISKUSAGE_METHODDEF
14202 OS__GETFINALPATHNAME_METHODDEF
14203 OS__GETVOLUMEPATHNAME_METHODDEF
14204 OS_GETLOADAVG_METHODDEF
14205 OS_URANDOM_METHODDEF
14206 OS_SETRESUID_METHODDEF
14207 OS_SETRESGID_METHODDEF
14208 OS_GETRESUID_METHODDEF
14209 OS_GETRESGID_METHODDEF
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000014210
Larry Hastings2f936352014-08-05 14:04:04 +100014211 OS_GETXATTR_METHODDEF
14212 OS_SETXATTR_METHODDEF
14213 OS_REMOVEXATTR_METHODDEF
14214 OS_LISTXATTR_METHODDEF
14215
Serhiy Storchaka2b560312020-04-18 19:14:10 +030014216 OS_GET_TERMINAL_SIZE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014217 OS_CPU_COUNT_METHODDEF
14218 OS_GET_INHERITABLE_METHODDEF
14219 OS_SET_INHERITABLE_METHODDEF
14220 OS_GET_HANDLE_INHERITABLE_METHODDEF
14221 OS_SET_HANDLE_INHERITABLE_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030014222 OS_GET_BLOCKING_METHODDEF
14223 OS_SET_BLOCKING_METHODDEF
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020014224 OS_SCANDIR_METHODDEF
Ethan Furman410ef8e2016-06-04 12:06:26 -070014225 OS_FSPATH_METHODDEF
Victor Stinner9b1f4742016-09-06 16:18:52 -070014226 OS_GETRANDOM_METHODDEF
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014227 OS_MEMFD_CREATE_METHODDEF
Steve Dower2438cdf2019-03-29 16:37:16 -070014228 OS__ADD_DLL_DIRECTORY_METHODDEF
14229 OS__REMOVE_DLL_DIRECTORY_METHODDEF
Victor Stinner65a796e2020-04-01 18:49:29 +020014230 OS_WAITSTATUS_TO_EXITCODE_METHODDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000014231 {NULL, NULL} /* Sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000014232};
14233
Barry Warsaw4a342091996-12-19 23:50:02 +000014234static int
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014235all_ins(PyObject *m)
Barry Warsaw4a342091996-12-19 23:50:02 +000014236{
Guido van Rossum94f6f721999-01-06 18:42:14 +000014237#ifdef F_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014238 if (PyModule_AddIntMacro(m, F_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014239#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000014240#ifdef R_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014241 if (PyModule_AddIntMacro(m, R_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014242#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000014243#ifdef W_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014244 if (PyModule_AddIntMacro(m, W_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014245#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000014246#ifdef X_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014247 if (PyModule_AddIntMacro(m, X_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014248#endif
Fred Drakec9680921999-12-13 16:37:25 +000014249#ifdef NGROUPS_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014250 if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
Fred Drakec9680921999-12-13 16:37:25 +000014251#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000014252#ifdef TMP_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014253 if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
Fred Drake5ab8eaf1999-12-09 21:13:07 +000014254#endif
Fred Drake106c1a02002-04-23 15:58:02 +000014255#ifdef WCONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014256 if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000014257#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000014258#ifdef WNOHANG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014259 if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014260#endif
Fred Drake106c1a02002-04-23 15:58:02 +000014261#ifdef WUNTRACED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014262 if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000014263#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000014264#ifdef O_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014265 if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014266#endif
14267#ifdef O_WRONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014268 if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014269#endif
14270#ifdef O_RDWR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014271 if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014272#endif
14273#ifdef O_NDELAY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014274 if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014275#endif
14276#ifdef O_NONBLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014277 if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014278#endif
14279#ifdef O_APPEND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014280 if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014281#endif
14282#ifdef O_DSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014283 if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014284#endif
14285#ifdef O_RSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014286 if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014287#endif
14288#ifdef O_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014289 if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014290#endif
14291#ifdef O_NOCTTY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014292 if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014293#endif
14294#ifdef O_CREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014295 if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014296#endif
14297#ifdef O_EXCL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014298 if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014299#endif
14300#ifdef O_TRUNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014301 if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014302#endif
Guido van Rossum98d9d091997-08-08 21:48:51 +000014303#ifdef O_BINARY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014304 if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000014305#endif
14306#ifdef O_TEXT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014307 if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000014308#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020014309#ifdef O_XATTR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014310 if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020014311#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014312#ifdef O_LARGEFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014313 if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014314#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020014315#ifndef __GNU__
Skip Montanaro5ff14922005-05-16 02:42:22 +000014316#ifdef O_SHLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014317 if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000014318#endif
14319#ifdef O_EXLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014320 if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000014321#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020014322#endif
Jesus Ceacf381202012-04-24 20:44:40 +020014323#ifdef O_EXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014324 if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020014325#endif
14326#ifdef O_SEARCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014327 if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020014328#endif
Benjamin Peterson3b965a22013-03-13 10:27:41 -050014329#ifdef O_PATH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014330 if (PyModule_AddIntMacro(m, O_PATH)) return -1;
Benjamin Peterson3b965a22013-03-13 10:27:41 -050014331#endif
Jesus Ceacf381202012-04-24 20:44:40 +020014332#ifdef O_TTY_INIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014333 if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020014334#endif
Christian Heimes177b3f92013-08-16 14:35:09 +020014335#ifdef O_TMPFILE
14336 if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
14337#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014338#ifdef PRIO_PROCESS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014339 if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014340#endif
14341#ifdef PRIO_PGRP
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014342 if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014343#endif
14344#ifdef PRIO_USER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014345 if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014346#endif
Charles-François Natali1e045b12011-05-22 20:42:32 +020014347#ifdef O_CLOEXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014348 if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
Charles-François Natali1e045b12011-05-22 20:42:32 +020014349#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020014350#ifdef O_ACCMODE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014351 if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020014352#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014353
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014354
Jesus Cea94363612012-06-22 18:32:07 +020014355#ifdef SEEK_HOLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014356 if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020014357#endif
14358#ifdef SEEK_DATA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014359 if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020014360#endif
14361
Tim Peters5aa91602002-01-30 05:46:57 +000014362/* MS Windows */
14363#ifdef O_NOINHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000014364 /* Don't inherit in child processes. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014365 if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014366#endif
14367#ifdef _O_SHORT_LIVED
Victor Stinner8c62be82010-05-06 00:08:46 +000014368 /* Optimize for short life (keep in memory). */
14369 /* MS forgot to define this one with a non-underscore form too. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014370 if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014371#endif
14372#ifdef O_TEMPORARY
Victor Stinner8c62be82010-05-06 00:08:46 +000014373 /* Automatically delete when last handle is closed. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014374 if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014375#endif
14376#ifdef O_RANDOM
Victor Stinner8c62be82010-05-06 00:08:46 +000014377 /* Optimize for random access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014378 if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014379#endif
14380#ifdef O_SEQUENTIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000014381 /* Optimize for sequential access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014382 if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014383#endif
14384
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014385/* GNU extensions. */
Alexandre Vassalottibee32532008-05-16 18:15:12 +000014386#ifdef O_ASYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000014387 /* Send a SIGIO signal whenever input or output
14388 becomes available on file descriptor */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014389 if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
Alexandre Vassalottibee32532008-05-16 18:15:12 +000014390#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014391#ifdef O_DIRECT
Victor Stinner8c62be82010-05-06 00:08:46 +000014392 /* Direct disk access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014393 if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014394#endif
14395#ifdef O_DIRECTORY
Victor Stinner8c62be82010-05-06 00:08:46 +000014396 /* Must be a directory. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014397 if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014398#endif
14399#ifdef O_NOFOLLOW
Victor Stinner8c62be82010-05-06 00:08:46 +000014400 /* Do not follow links. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014401 if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014402#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020014403#ifdef O_NOLINKS
14404 /* Fails if link count of the named file is greater than 1 */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014405 if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020014406#endif
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000014407#ifdef O_NOATIME
Victor Stinner8c62be82010-05-06 00:08:46 +000014408 /* Do not update the access time. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014409 if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000014410#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +000014411
Victor Stinner8c62be82010-05-06 00:08:46 +000014412 /* These come from sysexits.h */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014413#ifdef EX_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014414 if (PyModule_AddIntMacro(m, EX_OK)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014415#endif /* EX_OK */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014416#ifdef EX_USAGE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014417 if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014418#endif /* EX_USAGE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014419#ifdef EX_DATAERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014420 if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014421#endif /* EX_DATAERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014422#ifdef EX_NOINPUT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014423 if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014424#endif /* EX_NOINPUT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014425#ifdef EX_NOUSER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014426 if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014427#endif /* EX_NOUSER */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014428#ifdef EX_NOHOST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014429 if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014430#endif /* EX_NOHOST */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014431#ifdef EX_UNAVAILABLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014432 if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014433#endif /* EX_UNAVAILABLE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014434#ifdef EX_SOFTWARE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014435 if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014436#endif /* EX_SOFTWARE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014437#ifdef EX_OSERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014438 if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014439#endif /* EX_OSERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014440#ifdef EX_OSFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014441 if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014442#endif /* EX_OSFILE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014443#ifdef EX_CANTCREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014444 if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014445#endif /* EX_CANTCREAT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014446#ifdef EX_IOERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014447 if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014448#endif /* EX_IOERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014449#ifdef EX_TEMPFAIL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014450 if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014451#endif /* EX_TEMPFAIL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014452#ifdef EX_PROTOCOL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014453 if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014454#endif /* EX_PROTOCOL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014455#ifdef EX_NOPERM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014456 if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014457#endif /* EX_NOPERM */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014458#ifdef EX_CONFIG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014459 if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014460#endif /* EX_CONFIG */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014461#ifdef EX_NOTFOUND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014462 if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014463#endif /* EX_NOTFOUND */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014464
Amaury Forgeot d'Arc66d00ad2010-09-10 18:11:45 +000014465 /* statvfs */
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014466#ifdef ST_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014467 if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014468#endif /* ST_RDONLY */
14469#ifdef ST_NOSUID
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014470 if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014471#endif /* ST_NOSUID */
14472
doko@ubuntu.comca616a22013-12-08 15:23:07 +010014473 /* GNU extensions */
14474#ifdef ST_NODEV
14475 if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
14476#endif /* ST_NODEV */
14477#ifdef ST_NOEXEC
14478 if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
14479#endif /* ST_NOEXEC */
14480#ifdef ST_SYNCHRONOUS
14481 if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
14482#endif /* ST_SYNCHRONOUS */
14483#ifdef ST_MANDLOCK
14484 if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
14485#endif /* ST_MANDLOCK */
14486#ifdef ST_WRITE
14487 if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
14488#endif /* ST_WRITE */
14489#ifdef ST_APPEND
14490 if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
14491#endif /* ST_APPEND */
14492#ifdef ST_NOATIME
14493 if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
14494#endif /* ST_NOATIME */
14495#ifdef ST_NODIRATIME
14496 if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
14497#endif /* ST_NODIRATIME */
14498#ifdef ST_RELATIME
14499 if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
14500#endif /* ST_RELATIME */
14501
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014502 /* FreeBSD sendfile() constants */
14503#ifdef SF_NODISKIO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014504 if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014505#endif
14506#ifdef SF_MNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014507 if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014508#endif
14509#ifdef SF_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014510 if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014511#endif
14512
Ross Lagerwall7807c352011-03-17 20:20:30 +020014513 /* constants for posix_fadvise */
14514#ifdef POSIX_FADV_NORMAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014515 if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014516#endif
14517#ifdef POSIX_FADV_SEQUENTIAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014518 if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014519#endif
14520#ifdef POSIX_FADV_RANDOM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014521 if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014522#endif
14523#ifdef POSIX_FADV_NOREUSE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014524 if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014525#endif
14526#ifdef POSIX_FADV_WILLNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014527 if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014528#endif
14529#ifdef POSIX_FADV_DONTNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014530 if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014531#endif
14532
14533 /* constants for waitid */
14534#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014535 if (PyModule_AddIntMacro(m, P_PID)) return -1;
14536 if (PyModule_AddIntMacro(m, P_PGID)) return -1;
14537 if (PyModule_AddIntMacro(m, P_ALL)) return -1;
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080014538#ifdef P_PIDFD
14539 if (PyModule_AddIntMacro(m, P_PIDFD)) return -1;
14540#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014541#endif
14542#ifdef WEXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014543 if (PyModule_AddIntMacro(m, WEXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014544#endif
14545#ifdef WNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014546 if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014547#endif
14548#ifdef WSTOPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014549 if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014550#endif
14551#ifdef CLD_EXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014552 if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014553#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014554#ifdef CLD_KILLED
14555 if (PyModule_AddIntMacro(m, CLD_KILLED)) return -1;
14556#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014557#ifdef CLD_DUMPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014558 if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014559#endif
14560#ifdef CLD_TRAPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014561 if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014562#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014563#ifdef CLD_STOPPED
14564 if (PyModule_AddIntMacro(m, CLD_STOPPED)) return -1;
14565#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014566#ifdef CLD_CONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014567 if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014568#endif
14569
14570 /* constants for lockf */
14571#ifdef F_LOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014572 if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014573#endif
14574#ifdef F_TLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014575 if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014576#endif
14577#ifdef F_ULOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014578 if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014579#endif
14580#ifdef F_TEST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014581 if (PyModule_AddIntMacro(m, F_TEST)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014582#endif
14583
Pablo Galindo4defba32018-01-27 16:16:37 +000014584#ifdef RWF_DSYNC
14585 if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
14586#endif
14587#ifdef RWF_HIPRI
14588 if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
14589#endif
14590#ifdef RWF_SYNC
14591 if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
14592#endif
14593#ifdef RWF_NOWAIT
14594 if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
14595#endif
YoSTEALTH76ef2552020-05-27 15:32:22 -060014596#ifdef RWF_APPEND
14597 if (PyModule_AddIntConstant(m, "RWF_APPEND", RWF_APPEND)) return -1;
14598#endif
Pablo Galindo4defba32018-01-27 16:16:37 +000014599
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000014600/* constants for posix_spawn */
14601#ifdef HAVE_POSIX_SPAWN
14602 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
14603 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
14604 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
14605#endif
14606
pxinwrf2d7ac72019-05-21 18:46:37 +080014607#if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014608 if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
14609 if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014610 if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
pxinwrf2d7ac72019-05-21 18:46:37 +080014611#endif
14612#ifdef HAVE_SPAWNV
14613 if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014614 if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
Guido van Rossum246bc171999-02-01 23:54:31 +000014615#endif
14616
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014617#ifdef HAVE_SCHED_H
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014618#ifdef SCHED_OTHER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014619 if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014620#endif
14621#ifdef SCHED_FIFO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014622 if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014623#endif
14624#ifdef SCHED_RR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014625 if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014626#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014627#ifdef SCHED_SPORADIC
messi Liao0d322182017-06-13 22:30:43 +080014628 if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014629#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014630#ifdef SCHED_BATCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014631 if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014632#endif
14633#ifdef SCHED_IDLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014634 if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014635#endif
14636#ifdef SCHED_RESET_ON_FORK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014637 if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014638#endif
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014639#ifdef SCHED_SYS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014640 if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014641#endif
14642#ifdef SCHED_IA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014643 if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014644#endif
14645#ifdef SCHED_FSS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014646 if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014647#endif
14648#ifdef SCHED_FX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014649 if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014650#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014651#endif
14652
Benjamin Peterson9428d532011-09-14 11:45:52 -040014653#ifdef USE_XATTRS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014654 if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
14655 if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
14656 if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
Benjamin Peterson799bd802011-08-31 22:15:17 -040014657#endif
14658
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014659#if HAVE_DECL_RTLD_LAZY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014660 if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014661#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014662#if HAVE_DECL_RTLD_NOW
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014663 if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014664#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014665#if HAVE_DECL_RTLD_GLOBAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014666 if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014667#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014668#if HAVE_DECL_RTLD_LOCAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014669 if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014670#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014671#if HAVE_DECL_RTLD_NODELETE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014672 if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014673#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014674#if HAVE_DECL_RTLD_NOLOAD
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014675 if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014676#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014677#if HAVE_DECL_RTLD_DEEPBIND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014678 if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014679#endif
Michael Feltc5ae1692017-12-19 13:58:49 +010014680#if HAVE_DECL_RTLD_MEMBER
14681 if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
14682#endif
Victor Stinner8b905bd2011-10-25 13:34:04 +020014683
Victor Stinner9b1f4742016-09-06 16:18:52 -070014684#ifdef HAVE_GETRANDOM_SYSCALL
14685 if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
14686 if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
14687#endif
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014688#ifdef HAVE_MEMFD_CREATE
14689 if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
14690 if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
14691#ifdef MFD_HUGETLB
14692 if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014693#endif
14694#ifdef MFD_HUGE_SHIFT
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014695 if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014696#endif
14697#ifdef MFD_HUGE_MASK
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014698 if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014699#endif
14700#ifdef MFD_HUGE_64KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014701 if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014702#endif
14703#ifdef MFD_HUGE_512KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014704 if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014705#endif
14706#ifdef MFD_HUGE_1MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014707 if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014708#endif
14709#ifdef MFD_HUGE_2MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014710 if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014711#endif
14712#ifdef MFD_HUGE_8MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014713 if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014714#endif
14715#ifdef MFD_HUGE_16MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014716 if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014717#endif
14718#ifdef MFD_HUGE_32MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014719 if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014720#endif
14721#ifdef MFD_HUGE_256MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014722 if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014723#endif
14724#ifdef MFD_HUGE_512MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014725 if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014726#endif
14727#ifdef MFD_HUGE_1GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014728 if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014729#endif
14730#ifdef MFD_HUGE_2GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014731 if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014732#endif
14733#ifdef MFD_HUGE_16GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014734 if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
14735#endif
14736#endif
Victor Stinner9b1f4742016-09-06 16:18:52 -070014737
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020014738#if defined(__APPLE__)
14739 if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
14740#endif
14741
Steve Dower2438cdf2019-03-29 16:37:16 -070014742#ifdef MS_WINDOWS
14743 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
14744 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
14745 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
14746 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
14747 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
14748#endif
14749
Victor Stinner8c62be82010-05-06 00:08:46 +000014750 return 0;
Barry Warsaw4a342091996-12-19 23:50:02 +000014751}
14752
14753
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014754static const char * const have_functions[] = {
Larry Hastings9cf065c2012-06-22 16:30:09 -070014755
14756#ifdef HAVE_FACCESSAT
14757 "HAVE_FACCESSAT",
14758#endif
14759
14760#ifdef HAVE_FCHDIR
14761 "HAVE_FCHDIR",
14762#endif
14763
14764#ifdef HAVE_FCHMOD
14765 "HAVE_FCHMOD",
14766#endif
14767
14768#ifdef HAVE_FCHMODAT
14769 "HAVE_FCHMODAT",
14770#endif
14771
14772#ifdef HAVE_FCHOWN
14773 "HAVE_FCHOWN",
14774#endif
14775
Larry Hastings00964ed2013-08-12 13:49:30 -040014776#ifdef HAVE_FCHOWNAT
14777 "HAVE_FCHOWNAT",
14778#endif
14779
Larry Hastings9cf065c2012-06-22 16:30:09 -070014780#ifdef HAVE_FEXECVE
14781 "HAVE_FEXECVE",
14782#endif
14783
14784#ifdef HAVE_FDOPENDIR
14785 "HAVE_FDOPENDIR",
14786#endif
14787
Georg Brandl306336b2012-06-24 12:55:33 +020014788#ifdef HAVE_FPATHCONF
14789 "HAVE_FPATHCONF",
14790#endif
14791
Larry Hastings9cf065c2012-06-22 16:30:09 -070014792#ifdef HAVE_FSTATAT
14793 "HAVE_FSTATAT",
14794#endif
14795
14796#ifdef HAVE_FSTATVFS
14797 "HAVE_FSTATVFS",
14798#endif
14799
Steve Dowerfe0a41a2015-03-20 19:50:46 -070014800#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Georg Brandl306336b2012-06-24 12:55:33 +020014801 "HAVE_FTRUNCATE",
14802#endif
14803
Larry Hastings9cf065c2012-06-22 16:30:09 -070014804#ifdef HAVE_FUTIMENS
14805 "HAVE_FUTIMENS",
14806#endif
14807
14808#ifdef HAVE_FUTIMES
14809 "HAVE_FUTIMES",
14810#endif
14811
14812#ifdef HAVE_FUTIMESAT
14813 "HAVE_FUTIMESAT",
14814#endif
14815
14816#ifdef HAVE_LINKAT
14817 "HAVE_LINKAT",
14818#endif
14819
14820#ifdef HAVE_LCHFLAGS
14821 "HAVE_LCHFLAGS",
14822#endif
14823
14824#ifdef HAVE_LCHMOD
14825 "HAVE_LCHMOD",
14826#endif
14827
14828#ifdef HAVE_LCHOWN
14829 "HAVE_LCHOWN",
14830#endif
14831
14832#ifdef HAVE_LSTAT
14833 "HAVE_LSTAT",
14834#endif
14835
14836#ifdef HAVE_LUTIMES
14837 "HAVE_LUTIMES",
14838#endif
14839
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014840#ifdef HAVE_MEMFD_CREATE
14841 "HAVE_MEMFD_CREATE",
14842#endif
14843
Larry Hastings9cf065c2012-06-22 16:30:09 -070014844#ifdef HAVE_MKDIRAT
14845 "HAVE_MKDIRAT",
14846#endif
14847
14848#ifdef HAVE_MKFIFOAT
14849 "HAVE_MKFIFOAT",
14850#endif
14851
14852#ifdef HAVE_MKNODAT
14853 "HAVE_MKNODAT",
14854#endif
14855
14856#ifdef HAVE_OPENAT
14857 "HAVE_OPENAT",
14858#endif
14859
14860#ifdef HAVE_READLINKAT
14861 "HAVE_READLINKAT",
14862#endif
14863
14864#ifdef HAVE_RENAMEAT
14865 "HAVE_RENAMEAT",
14866#endif
14867
14868#ifdef HAVE_SYMLINKAT
14869 "HAVE_SYMLINKAT",
14870#endif
14871
14872#ifdef HAVE_UNLINKAT
14873 "HAVE_UNLINKAT",
14874#endif
14875
14876#ifdef HAVE_UTIMENSAT
14877 "HAVE_UTIMENSAT",
14878#endif
14879
14880#ifdef MS_WINDOWS
14881 "MS_WINDOWS",
14882#endif
14883
14884 NULL
14885};
14886
14887
Victor Stinner1c2fa782020-05-10 11:05:29 +020014888static int
14889posixmodule_exec(PyObject *m)
Guido van Rossumb6775db1994-08-01 11:34:53 +000014890{
Victor Stinner97f33c32020-05-14 18:05:58 +020014891 _posixstate *state = get_posix_state(m);
Tim Peters5aa91602002-01-30 05:46:57 +000014892
Victor Stinner8c62be82010-05-06 00:08:46 +000014893 /* Initialize environ dictionary */
Victor Stinner97f33c32020-05-14 18:05:58 +020014894 PyObject *v = convertenviron();
Victor Stinner8c62be82010-05-06 00:08:46 +000014895 Py_XINCREF(v);
14896 if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
Victor Stinner1c2fa782020-05-10 11:05:29 +020014897 return -1;
Victor Stinner8c62be82010-05-06 00:08:46 +000014898 Py_DECREF(v);
Fred Drakec9680921999-12-13 16:37:25 +000014899
Victor Stinner8c62be82010-05-06 00:08:46 +000014900 if (all_ins(m))
Victor Stinner1c2fa782020-05-10 11:05:29 +020014901 return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014902
Victor Stinner8c62be82010-05-06 00:08:46 +000014903 if (setup_confname_tables(m))
Victor Stinner1c2fa782020-05-10 11:05:29 +020014904 return -1;
Fred Drakebec628d1999-12-15 18:31:10 +000014905
Victor Stinner8c62be82010-05-06 00:08:46 +000014906 Py_INCREF(PyExc_OSError);
14907 PyModule_AddObject(m, "error", PyExc_OSError);
Fred Drake762e2061999-08-26 17:23:54 +000014908
Ross Lagerwall7807c352011-03-17 20:20:30 +020014909#if defined(HAVE_WAITID) && !defined(__APPLE__)
Eddie Elizondob3966632019-11-05 07:16:14 -080014910 waitid_result_desc.name = MODNAME ".waitid_result";
14911 PyObject *WaitidResultType = (PyObject *)PyStructSequence_NewType(&waitid_result_desc);
14912 if (WaitidResultType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020014913 return -1;
Eddie Elizondob3966632019-11-05 07:16:14 -080014914 }
14915 Py_INCREF(WaitidResultType);
14916 PyModule_AddObject(m, "waitid_result", WaitidResultType);
Victor Stinner97f33c32020-05-14 18:05:58 +020014917 state->WaitidResultType = WaitidResultType;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014918#endif
14919
Eddie Elizondob3966632019-11-05 07:16:14 -080014920 stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
14921 stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
14922 stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
14923 stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
14924 PyObject *StatResultType = (PyObject *)PyStructSequence_NewType(&stat_result_desc);
14925 if (StatResultType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020014926 return -1;
Eddie Elizondob3966632019-11-05 07:16:14 -080014927 }
14928 Py_INCREF(StatResultType);
14929 PyModule_AddObject(m, "stat_result", StatResultType);
Victor Stinner97f33c32020-05-14 18:05:58 +020014930 state->StatResultType = StatResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014931 structseq_new = ((PyTypeObject *)StatResultType)->tp_new;
14932 ((PyTypeObject *)StatResultType)->tp_new = statresult_new;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014933
Eddie Elizondob3966632019-11-05 07:16:14 -080014934 statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
14935 PyObject *StatVFSResultType = (PyObject *)PyStructSequence_NewType(&statvfs_result_desc);
14936 if (StatVFSResultType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020014937 return -1;
Eddie Elizondob3966632019-11-05 07:16:14 -080014938 }
14939 Py_INCREF(StatVFSResultType);
14940 PyModule_AddObject(m, "statvfs_result", StatVFSResultType);
Victor Stinner97f33c32020-05-14 18:05:58 +020014941 state->StatVFSResultType = StatVFSResultType;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014942#ifdef NEED_TICKS_PER_SECOND
14943# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Eddie Elizondob3966632019-11-05 07:16:14 -080014944 ticks_per_second = sysconf(_SC_CLK_TCK);
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014945# elif defined(HZ)
Eddie Elizondob3966632019-11-05 07:16:14 -080014946 ticks_per_second = HZ;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014947# else
Eddie Elizondob3966632019-11-05 07:16:14 -080014948 ticks_per_second = 60; /* magic fallback value; may be bogus */
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014949# endif
14950#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014951
William Orr81574b82018-10-01 22:19:56 -070014952#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Eddie Elizondob3966632019-11-05 07:16:14 -080014953 sched_param_desc.name = MODNAME ".sched_param";
14954 PyObject *SchedParamType = (PyObject *)PyStructSequence_NewType(&sched_param_desc);
14955 if (SchedParamType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020014956 return -1;
Victor Stinner8c62be82010-05-06 00:08:46 +000014957 }
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014958 Py_INCREF(SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -080014959 PyModule_AddObject(m, "sched_param", SchedParamType);
Victor Stinner97f33c32020-05-14 18:05:58 +020014960 state->SchedParamType = SchedParamType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014961 ((PyTypeObject *)SchedParamType)->tp_new = os_sched_param;
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014962#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +000014963
Eddie Elizondob3966632019-11-05 07:16:14 -080014964 /* initialize TerminalSize_info */
14965 PyObject *TerminalSizeType = (PyObject *)PyStructSequence_NewType(&TerminalSize_desc);
14966 if (TerminalSizeType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020014967 return -1;
Eddie Elizondob3966632019-11-05 07:16:14 -080014968 }
14969 Py_INCREF(TerminalSizeType);
14970 PyModule_AddObject(m, "terminal_size", TerminalSizeType);
Victor Stinner97f33c32020-05-14 18:05:58 +020014971 state->TerminalSizeType = TerminalSizeType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014972
14973 /* initialize scandir types */
Victor Stinner1c2fa782020-05-10 11:05:29 +020014974 PyObject *ScandirIteratorType = PyType_FromModuleAndSpec(m, &ScandirIteratorType_spec, NULL);
Eddie Elizondob3966632019-11-05 07:16:14 -080014975 if (ScandirIteratorType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020014976 return -1;
Eddie Elizondob3966632019-11-05 07:16:14 -080014977 }
Victor Stinner97f33c32020-05-14 18:05:58 +020014978 state->ScandirIteratorType = ScandirIteratorType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014979
Victor Stinner1c2fa782020-05-10 11:05:29 +020014980 PyObject *DirEntryType = PyType_FromModuleAndSpec(m, &DirEntryType_spec, NULL);
Eddie Elizondob3966632019-11-05 07:16:14 -080014981 if (DirEntryType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020014982 return -1;
Eddie Elizondob3966632019-11-05 07:16:14 -080014983 }
14984 Py_INCREF(DirEntryType);
14985 PyModule_AddObject(m, "DirEntry", DirEntryType);
Victor Stinner97f33c32020-05-14 18:05:58 +020014986 state->DirEntryType = DirEntryType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014987
Larry Hastings605a62d2012-06-24 04:33:36 -070014988 times_result_desc.name = MODNAME ".times_result";
Eddie Elizondob3966632019-11-05 07:16:14 -080014989 PyObject *TimesResultType = (PyObject *)PyStructSequence_NewType(&times_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014990 if (TimesResultType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020014991 return -1;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014992 }
Eddie Elizondob3966632019-11-05 07:16:14 -080014993 Py_INCREF(TimesResultType);
14994 PyModule_AddObject(m, "times_result", TimesResultType);
Victor Stinner97f33c32020-05-14 18:05:58 +020014995 state->TimesResultType = TimesResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070014996
Eddie Elizondob3966632019-11-05 07:16:14 -080014997 PyTypeObject *UnameResultType = PyStructSequence_NewType(&uname_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014998 if (UnameResultType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020014999 return -1;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080015000 }
Eddie Elizondob3966632019-11-05 07:16:14 -080015001 Py_INCREF(UnameResultType);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080015002 PyModule_AddObject(m, "uname_result", (PyObject *)UnameResultType);
Victor Stinner97f33c32020-05-14 18:05:58 +020015003 state->UnameResultType = (PyObject *)UnameResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070015004
Thomas Wouters477c8d52006-05-27 19:21:47 +000015005#ifdef __APPLE__
Victor Stinner8c62be82010-05-06 00:08:46 +000015006 /*
15007 * Step 2 of weak-linking support on Mac OS X.
15008 *
15009 * The code below removes functions that are not available on the
15010 * currently active platform.
15011 *
15012 * This block allow one to use a python binary that was build on
Larry Hastings9cf065c2012-06-22 16:30:09 -070015013 * OSX 10.4 on OSX 10.3, without losing access to new APIs on
Victor Stinner8c62be82010-05-06 00:08:46 +000015014 * OSX 10.4.
15015 */
Thomas Wouters477c8d52006-05-27 19:21:47 +000015016#ifdef HAVE_FSTATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000015017 if (fstatvfs == NULL) {
15018 if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020015019 return -1;
Victor Stinner8c62be82010-05-06 00:08:46 +000015020 }
15021 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000015022#endif /* HAVE_FSTATVFS */
15023
15024#ifdef HAVE_STATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000015025 if (statvfs == NULL) {
15026 if (PyObject_DelAttrString(m, "statvfs") == -1) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020015027 return -1;
Victor Stinner8c62be82010-05-06 00:08:46 +000015028 }
15029 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000015030#endif /* HAVE_STATVFS */
15031
15032# ifdef HAVE_LCHOWN
Victor Stinner8c62be82010-05-06 00:08:46 +000015033 if (lchown == NULL) {
15034 if (PyObject_DelAttrString(m, "lchown") == -1) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020015035 return -1;
Victor Stinner8c62be82010-05-06 00:08:46 +000015036 }
15037 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000015038#endif /* HAVE_LCHOWN */
15039
15040
15041#endif /* __APPLE__ */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010015042
Victor Stinner97f33c32020-05-14 18:05:58 +020015043 if ((state->billion = PyLong_FromLong(1000000000)) == NULL)
Victor Stinner1c2fa782020-05-10 11:05:29 +020015044 return -1;
Eddie Elizondob3966632019-11-05 07:16:14 -080015045#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
Victor Stinner97f33c32020-05-14 18:05:58 +020015046 state->struct_rusage = PyUnicode_InternFromString("struct_rusage");
15047 if (state->struct_rusage == NULL)
Victor Stinner1c2fa782020-05-10 11:05:29 +020015048 return -1;
Eddie Elizondob3966632019-11-05 07:16:14 -080015049#endif
Victor Stinner97f33c32020-05-14 18:05:58 +020015050 state->st_mode = PyUnicode_InternFromString("st_mode");
15051 if (state->st_mode == NULL)
Victor Stinner1c2fa782020-05-10 11:05:29 +020015052 return -1;
Larry Hastings6fe20b32012-04-19 15:07:49 -070015053
Larry Hastings9cf065c2012-06-22 16:30:09 -070015054 /* suppress "function not used" warnings */
15055 {
15056 int ignored;
15057 fd_specified("", -1);
15058 follow_symlinks_specified("", 1);
15059 dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
15060 dir_fd_converter(Py_None, &ignored);
15061 dir_fd_unavailable(Py_None, &ignored);
15062 }
15063
15064 /*
15065 * provide list of locally available functions
15066 * so os.py can populate support_* lists
15067 */
Victor Stinner97f33c32020-05-14 18:05:58 +020015068 PyObject *list = PyList_New(0);
15069 if (!list) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020015070 return -1;
Victor Stinner97f33c32020-05-14 18:05:58 +020015071 }
15072 for (const char * const *trace = have_functions; *trace; trace++) {
Larry Hastings9cf065c2012-06-22 16:30:09 -070015073 PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
15074 if (!unicode)
Victor Stinner1c2fa782020-05-10 11:05:29 +020015075 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -070015076 if (PyList_Append(list, unicode))
Victor Stinner1c2fa782020-05-10 11:05:29 +020015077 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -070015078 Py_DECREF(unicode);
15079 }
15080 PyModule_AddObject(m, "_have_functions", list);
Ned Deilyeb3be662016-08-15 14:40:38 -040015081
Victor Stinner1c2fa782020-05-10 11:05:29 +020015082 return 0;
15083}
15084
15085
15086static PyModuleDef_Slot posixmodile_slots[] = {
15087 {Py_mod_exec, posixmodule_exec},
15088 {0, NULL}
15089};
15090
15091static struct PyModuleDef posixmodule = {
15092 PyModuleDef_HEAD_INIT,
15093 .m_name = MODNAME,
15094 .m_doc = posix__doc__,
15095 .m_size = sizeof(_posixstate),
15096 .m_methods = posix_methods,
15097 .m_slots = posixmodile_slots,
15098 .m_traverse = _posix_traverse,
15099 .m_clear = _posix_clear,
15100 .m_free = _posix_free,
15101};
15102
15103PyMODINIT_FUNC
15104INITFUNC(void)
15105{
15106 return PyModuleDef_Init(&posixmodule);
Guido van Rossumb6775db1994-08-01 11:34:53 +000015107}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015108
15109#ifdef __cplusplus
15110}
15111#endif