blob: 00ba7580302bbab6638ae7ad613c36ab665db6e9 [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
pxinwr3405e052020-08-07 13:21:52 +080035#ifdef __VXWORKS__
36# include "pycore_bitutils.h" // _Py_popcount32()
37#endif
Victor Stinner4a21e572020-04-15 02:35:41 +020038#include "pycore_ceval.h" // _PyEval_ReInitThreads()
39#include "pycore_import.h" // _PyImport_ReInitLock()
Victor Stinner26881c82020-06-02 15:51:37 +020040#include "pycore_initconfig.h" // _PyStatus_EXCEPTION()
Victor Stinner4a21e572020-04-15 02:35:41 +020041#include "pycore_pystate.h" // _PyInterpreterState_GET()
42#include "structmember.h" // PyMemberDef
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020043#ifndef MS_WINDOWS
Victor Stinnerd5d9e812019-05-13 12:35:37 +020044# include "posixmodule.h"
Tim Golden0321cf22014-05-05 19:46:17 +010045#else
Victor Stinnerd5d9e812019-05-13 12:35:37 +020046# include "winreparse.h"
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020047#endif
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000048
Stefan Krahfb7c8ae2016-04-26 17:04:18 +020049/* On android API level 21, 'AT_EACCESS' is not declared although
50 * HAVE_FACCESSAT is defined. */
51#ifdef __ANDROID__
Victor Stinner5eca75d2020-04-15 15:07:31 +020052# undef HAVE_FACCESSAT
Stefan Krahfb7c8ae2016-04-26 17:04:18 +020053#endif
54
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)fa76eee2016-05-28 21:03:48 +000055#include <stdio.h> /* needed for ctermid() */
56
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057#ifdef __cplusplus
58extern "C" {
59#endif
60
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000061PyDoc_STRVAR(posix__doc__,
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000062"This module provides access to operating system functionality that is\n\
63standardized by the C Standard and the POSIX standard (a thinly\n\
64disguised Unix interface). Refer to the library manual and\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000065corresponding Unix manual entries for more information on calls.");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000066
Martin v. Löwis0073f2e2002-11-21 23:52:35 +000067
Ross Lagerwall4d076da2011-03-18 06:56:53 +020068#ifdef HAVE_SYS_UIO_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020069# include <sys/uio.h>
Ross Lagerwall4d076da2011-03-18 06:56:53 +020070#endif
71
Christian Heimes75b96182017-09-05 15:53:09 +020072#ifdef HAVE_SYS_SYSMACROS_H
73/* GNU C Library: major(), minor(), makedev() */
Victor Stinner5eca75d2020-04-15 15:07:31 +020074# include <sys/sysmacros.h>
Christian Heimes75b96182017-09-05 15:53:09 +020075#endif
76
Thomas Wouters0e3f5912006-08-11 14:57:12 +000077#ifdef HAVE_SYS_TYPES_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020078# include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000079#endif /* HAVE_SYS_TYPES_H */
80
81#ifdef HAVE_SYS_STAT_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020082# include <sys/stat.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000083#endif /* HAVE_SYS_STAT_H */
Guido van Rossuma6535fd2001-10-18 19:44:10 +000084
Guido van Rossum36bc6801995-06-14 22:54:23 +000085#ifdef HAVE_SYS_WAIT_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020086# include <sys/wait.h> // WNOHANG
Guido van Rossum36bc6801995-06-14 22:54:23 +000087#endif
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080088#ifdef HAVE_LINUX_WAIT_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020089# include <linux/wait.h> // P_PIDFD
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080090#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +000091
Thomas Wouters0e3f5912006-08-11 14:57:12 +000092#ifdef HAVE_SIGNAL_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020093# include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000094#endif
Guido van Rossuma376cc51996-12-05 23:43:35 +000095
Guido van Rossumb6775db1994-08-01 11:34:53 +000096#ifdef HAVE_FCNTL_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020097# include <fcntl.h>
98#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +000099
Guido van Rossuma6535fd2001-10-18 19:44:10 +0000100#ifdef HAVE_GRP_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200101# include <grp.h>
Guido van Rossuma6535fd2001-10-18 19:44:10 +0000102#endif
103
Barry Warsaw5676bd12003-01-07 20:57:09 +0000104#ifdef HAVE_SYSEXITS_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200105# include <sysexits.h>
106#endif
Barry Warsaw5676bd12003-01-07 20:57:09 +0000107
Anthony Baxter8a560de2004-10-13 15:30:56 +0000108#ifdef HAVE_SYS_LOADAVG_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200109# include <sys/loadavg.h>
Anthony Baxter8a560de2004-10-13 15:30:56 +0000110#endif
111
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000112#ifdef HAVE_SYS_SENDFILE_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200113# include <sys/sendfile.h>
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000114#endif
115
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +0200116#if defined(__APPLE__)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200117# include <copyfile.h>
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +0200118#endif
119
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500120#ifdef HAVE_SCHED_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200121# include <sched.h>
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500122#endif
123
Pablo Galindoaac4d032019-05-31 19:39:47 +0100124#ifdef HAVE_COPY_FILE_RANGE
Victor Stinner5eca75d2020-04-15 15:07:31 +0200125# include <unistd.h>
Pablo Galindoaac4d032019-05-31 19:39:47 +0100126#endif
127
Benjamin Peterson2dbda072012-03-16 10:12:55 -0500128#if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200129# undef HAVE_SCHED_SETAFFINITY
Benjamin Peterson7b51b8d2012-03-14 22:28:25 -0500130#endif
131
doko@ubuntu.com4a173bc2014-04-17 19:47:16 +0200132#if defined(HAVE_SYS_XATTR_H) && defined(__GLIBC__) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200133# define USE_XATTRS
Benjamin Peterson9428d532011-09-14 11:45:52 -0400134#endif
135
136#ifdef USE_XATTRS
Victor Stinner5eca75d2020-04-15 15:07:31 +0200137# include <sys/xattr.h>
Benjamin Peterson799bd802011-08-31 22:15:17 -0400138#endif
139
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000140#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200141# ifdef HAVE_SYS_SOCKET_H
142# include <sys/socket.h>
143# endif
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000144#endif
145
Victor Stinner8b905bd2011-10-25 13:34:04 +0200146#ifdef HAVE_DLFCN_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200147# include <dlfcn.h>
Victor Stinner8b905bd2011-10-25 13:34:04 +0200148#endif
149
Charles-Francois Natali44feda32013-05-20 14:40:46 +0200150#ifdef __hpux
Victor Stinner5eca75d2020-04-15 15:07:31 +0200151# include <sys/mpctl.h>
Charles-Francois Natali44feda32013-05-20 14:40:46 +0200152#endif
153
154#if defined(__DragonFly__) || \
155 defined(__OpenBSD__) || \
156 defined(__FreeBSD__) || \
157 defined(__NetBSD__) || \
158 defined(__APPLE__)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200159# include <sys/sysctl.h>
Charles-Francois Natali44feda32013-05-20 14:40:46 +0200160#endif
161
Victor Stinner9b1f4742016-09-06 16:18:52 -0700162#ifdef HAVE_LINUX_RANDOM_H
163# include <linux/random.h>
164#endif
165#ifdef HAVE_GETRANDOM_SYSCALL
166# include <sys/syscall.h>
167#endif
168
Antoine Pitroubcf2b592012-02-08 23:28:36 +0100169#if defined(MS_WINDOWS)
170# define TERMSIZE_USE_CONIO
171#elif defined(HAVE_SYS_IOCTL_H)
172# include <sys/ioctl.h>
173# if defined(HAVE_TERMIOS_H)
174# include <termios.h>
175# endif
176# if defined(TIOCGWINSZ)
177# define TERMSIZE_USE_IOCTL
178# endif
179#endif /* MS_WINDOWS */
180
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000181/* Various compilers have only certain posix functions */
Martin v. Löwis4f1cd8b2001-07-26 13:41:06 +0000182/* XXX Gosh I wish these were all moved into pyconfig.h */
Victor Stinner8c62be82010-05-06 00:08:46 +0000183#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
Victor Stinner5eca75d2020-04-15 15:07:31 +0200184# define HAVE_OPENDIR 1
185# define HAVE_SYSTEM 1
186# include <process.h>
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000187#else
Victor Stinner5eca75d2020-04-15 15:07:31 +0200188# ifdef _MSC_VER
189 /* Microsoft compiler */
190# define HAVE_GETPPID 1
191# define HAVE_GETLOGIN 1
192# define HAVE_SPAWNV 1
193# define HAVE_EXECV 1
194# define HAVE_WSPAWNV 1
195# define HAVE_WEXECV 1
196# define HAVE_PIPE 1
197# define HAVE_SYSTEM 1
198# define HAVE_CWAIT 1
199# define HAVE_FSYNC 1
200# define fsync _commit
201# else
202 /* Unix functions that the configure script doesn't check for */
203# ifndef __VXWORKS__
204# define HAVE_EXECV 1
205# define HAVE_FORK 1
206# if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */
207# define HAVE_FORK1 1
208# endif
209# endif
210# define HAVE_GETEGID 1
211# define HAVE_GETEUID 1
212# define HAVE_GETGID 1
213# define HAVE_GETPPID 1
214# define HAVE_GETUID 1
215# define HAVE_KILL 1
216# define HAVE_OPENDIR 1
217# define HAVE_PIPE 1
218# define HAVE_SYSTEM 1
219# define HAVE_WAIT 1
220# define HAVE_TTYNAME 1
221# endif /* _MSC_VER */
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000222#endif /* ! __WATCOMC__ || __QNX__ */
Guido van Rossumad0ee831995-03-01 10:34:45 +0000223
Eddie Elizondob3966632019-11-05 07:16:14 -0800224_Py_IDENTIFIER(__fspath__);
Victor Stinnera2f7c002012-02-08 03:36:25 +0100225
Larry Hastings61272b72014-01-07 12:41:53 -0800226/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +1000227# one of the few times we lie about this name!
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800228module os
Larry Hastings61272b72014-01-07 12:41:53 -0800229[clinic start generated code]*/
Larry Hastings2f936352014-08-05 14:04:04 +1000230/*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
Victor Stinnera2f7c002012-02-08 03:36:25 +0100231
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000232#ifndef _MSC_VER
Guido van Rossum36bc6801995-06-14 22:54:23 +0000233
Martin v. Löwis8eb92a02002-09-19 08:03:21 +0000234#if defined(__sgi)&&_COMPILER_VERSION>=700
235/* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
236 (default) */
237extern char *ctermid_r(char *);
238#endif
239
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000240#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000241
pxinwrf2d7ac72019-05-21 18:46:37 +0800242#if defined(__VXWORKS__)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200243# include <vxCpuLib.h>
244# include <rtpLib.h>
245# include <wait.h>
246# include <taskLib.h>
247# ifndef _P_WAIT
248# define _P_WAIT 0
249# define _P_NOWAIT 1
250# define _P_NOWAITO 1
251# endif
pxinwrf2d7ac72019-05-21 18:46:37 +0800252#endif /* __VXWORKS__ */
253
Pablo Galindo6c6ddf92018-01-29 01:56:10 +0000254#ifdef HAVE_POSIX_SPAWN
Victor Stinner5eca75d2020-04-15 15:07:31 +0200255# include <spawn.h>
Pablo Galindo6c6ddf92018-01-29 01:56:10 +0000256#endif
257
Guido van Rossumb6775db1994-08-01 11:34:53 +0000258#ifdef HAVE_UTIME_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200259# include <utime.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000260#endif /* HAVE_UTIME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000261
Guido van Rossum14ed0b21994-09-29 09:50:09 +0000262#ifdef HAVE_SYS_UTIME_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200263# include <sys/utime.h>
264# define HAVE_UTIME_H /* pretend we do for the rest of this file */
Guido van Rossum14ed0b21994-09-29 09:50:09 +0000265#endif /* HAVE_SYS_UTIME_H */
266
Guido van Rossumb6775db1994-08-01 11:34:53 +0000267#ifdef HAVE_SYS_TIMES_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200268# include <sys/times.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000269#endif /* HAVE_SYS_TIMES_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000270
271#ifdef HAVE_SYS_PARAM_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200272# include <sys/param.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000273#endif /* HAVE_SYS_PARAM_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000274
275#ifdef HAVE_SYS_UTSNAME_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200276# include <sys/utsname.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000277#endif /* HAVE_SYS_UTSNAME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000278
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000279#ifdef HAVE_DIRENT_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200280# include <dirent.h>
281# define NAMLEN(dirent) strlen((dirent)->d_name)
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000282#else
Victor Stinner5eca75d2020-04-15 15:07:31 +0200283# if defined(__WATCOMC__) && !defined(__QNX__)
284# include <direct.h>
285# define NAMLEN(dirent) strlen((dirent)->d_name)
286# else
287# define dirent direct
288# define NAMLEN(dirent) (dirent)->d_namlen
289# endif
290# ifdef HAVE_SYS_NDIR_H
291# include <sys/ndir.h>
292# endif
293# ifdef HAVE_SYS_DIR_H
294# include <sys/dir.h>
295# endif
296# ifdef HAVE_NDIR_H
297# include <ndir.h>
298# endif
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000299#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000300
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000301#ifdef _MSC_VER
Victor Stinner5eca75d2020-04-15 15:07:31 +0200302# ifdef HAVE_DIRECT_H
303# include <direct.h>
304# endif
305# ifdef HAVE_IO_H
306# include <io.h>
307# endif
308# ifdef HAVE_PROCESS_H
309# include <process.h>
310# endif
311# ifndef IO_REPARSE_TAG_SYMLINK
312# define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
313# endif
314# ifndef IO_REPARSE_TAG_MOUNT_POINT
315# define IO_REPARSE_TAG_MOUNT_POINT (0xA0000003L)
316# endif
317# include "osdefs.h" // SEP
318# include <malloc.h>
319# include <windows.h>
320# include <shellapi.h> // ShellExecute()
321# include <lmcons.h> // UNLEN
322# define HAVE_SYMLINK
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000323#endif /* _MSC_VER */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000324
Tim Petersbc2e10e2002-03-03 23:17:02 +0000325#ifndef MAXPATHLEN
Victor Stinner5eca75d2020-04-15 15:07:31 +0200326# if defined(PATH_MAX) && PATH_MAX > 1024
327# define MAXPATHLEN PATH_MAX
328# else
329# define MAXPATHLEN 1024
330# endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000331#endif /* MAXPATHLEN */
332
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000333#ifdef UNION_WAIT
Victor Stinner5eca75d2020-04-15 15:07:31 +0200334 /* Emulate some macros on systems that have a union instead of macros */
335# ifndef WIFEXITED
336# define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
337# endif
338# ifndef WEXITSTATUS
339# define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
340# endif
341# ifndef WTERMSIG
342# define WTERMSIG(u_wait) ((u_wait).w_termsig)
343# endif
344# define WAIT_TYPE union wait
345# define WAIT_STATUS_INT(s) (s.w_status)
346#else
347 /* !UNION_WAIT */
348# define WAIT_TYPE int
349# define WAIT_STATUS_INT(s) (s)
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000350#endif /* UNION_WAIT */
351
Greg Wardb48bc172000-03-01 21:51:56 +0000352/* Don't use the "_r" form if we don't need it (also, won't have a
353 prototype for it, at least on Solaris -- maybe others as well?). */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200354#if defined(HAVE_CTERMID_R)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200355# define USE_CTERMID_R
Greg Wardb48bc172000-03-01 21:51:56 +0000356#endif
357
Fred Drake699f3522000-06-29 21:12:41 +0000358/* choose the appropriate stat and fstat functions and return structs */
Guido van Rossum64529cd2000-06-30 22:45:12 +0000359#undef STAT
Antoine Pitroue47e0932011-01-19 15:21:35 +0000360#undef FSTAT
361#undef STRUCT_STAT
Victor Stinner14b9b112013-06-25 00:37:25 +0200362#ifdef MS_WINDOWS
Victor Stinner5eca75d2020-04-15 15:07:31 +0200363# define STAT win32_stat
364# define LSTAT win32_lstat
365# define FSTAT _Py_fstat_noraise
366# define STRUCT_STAT struct _Py_stat_struct
Fred Drake699f3522000-06-29 21:12:41 +0000367#else
Victor Stinner5eca75d2020-04-15 15:07:31 +0200368# define STAT stat
369# define LSTAT lstat
370# define FSTAT fstat
371# define STRUCT_STAT struct stat
Fred Drake699f3522000-06-29 21:12:41 +0000372#endif
373
Tim Peters11b23062003-04-23 02:39:17 +0000374#if defined(MAJOR_IN_MKDEV)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200375# include <sys/mkdev.h>
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000376#else
Victor Stinner5eca75d2020-04-15 15:07:31 +0200377# if defined(MAJOR_IN_SYSMACROS)
378# include <sys/sysmacros.h>
379# endif
380# if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
381# include <sys/mkdev.h>
382# endif
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000383#endif
Fred Drake699f3522000-06-29 21:12:41 +0000384
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200385#ifdef MS_WINDOWS
Victor Stinner5eca75d2020-04-15 15:07:31 +0200386# define INITFUNC PyInit_nt
387# define MODNAME "nt"
Victor Stinner6036e442015-03-08 01:58:04 +0100388#else
Victor Stinner5eca75d2020-04-15 15:07:31 +0200389# define INITFUNC PyInit_posix
390# define MODNAME "posix"
Victor Stinner6036e442015-03-08 01:58:04 +0100391#endif
392
jcea6c51d512018-01-28 14:00:08 +0100393#if defined(__sun)
394/* Something to implement in autoconf, not present in autoconf 2.69 */
Victor Stinner5eca75d2020-04-15 15:07:31 +0200395# define HAVE_STRUCT_STAT_ST_FSTYPE 1
jcea6c51d512018-01-28 14:00:08 +0100396#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200397
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600398/* memfd_create is either defined in sys/mman.h or sys/memfd.h
399 * linux/memfd.h defines additional flags
400 */
401#ifdef HAVE_SYS_MMAN_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200402# include <sys/mman.h>
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600403#endif
404#ifdef HAVE_SYS_MEMFD_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200405# include <sys/memfd.h>
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600406#endif
407#ifdef HAVE_LINUX_MEMFD_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200408# include <linux/memfd.h>
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600409#endif
410
Gregory P. Smith1d300ce2018-12-30 21:13:02 -0800411#ifdef _Py_MEMORY_SANITIZER
Victor Stinner5eca75d2020-04-15 15:07:31 +0200412# include <sanitizer/msan_interface.h>
Gregory P. Smith1d300ce2018-12-30 21:13:02 -0800413#endif
414
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200415#ifdef HAVE_FORK
416static void
417run_at_forkers(PyObject *lst, int reverse)
418{
419 Py_ssize_t i;
420 PyObject *cpy;
421
422 if (lst != NULL) {
423 assert(PyList_CheckExact(lst));
424
425 /* Use a list copy in case register_at_fork() is called from
426 * one of the callbacks.
427 */
428 cpy = PyList_GetSlice(lst, 0, PyList_GET_SIZE(lst));
429 if (cpy == NULL)
430 PyErr_WriteUnraisable(lst);
431 else {
432 if (reverse)
433 PyList_Reverse(cpy);
434 for (i = 0; i < PyList_GET_SIZE(cpy); i++) {
435 PyObject *func, *res;
436 func = PyList_GET_ITEM(cpy, i);
Jeroen Demeyer7f41c8e2019-07-04 12:35:31 +0200437 res = _PyObject_CallNoArg(func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200438 if (res == NULL)
439 PyErr_WriteUnraisable(func);
440 else
441 Py_DECREF(res);
442 }
443 Py_DECREF(cpy);
444 }
445 }
446}
447
448void
449PyOS_BeforeFork(void)
450{
Victor Stinner81a7be32020-04-14 15:14:01 +0200451 run_at_forkers(_PyInterpreterState_GET()->before_forkers, 1);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200452
453 _PyImport_AcquireLock();
454}
455
456void
457PyOS_AfterFork_Parent(void)
458{
459 if (_PyImport_ReleaseLock() <= 0)
460 Py_FatalError("failed releasing import lock after fork");
461
Victor Stinner81a7be32020-04-14 15:14:01 +0200462 run_at_forkers(_PyInterpreterState_GET()->after_forkers_parent, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200463}
464
465void
466PyOS_AfterFork_Child(void)
467{
Victor Stinner26881c82020-06-02 15:51:37 +0200468 PyStatus status;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200469 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner26881c82020-06-02 15:51:37 +0200470
471 status = _PyGILState_Reinit(runtime);
472 if (_PyStatus_EXCEPTION(status)) {
473 goto fatal_error;
474 }
475
Victor Stinner317bab02020-06-02 18:44:54 +0200476 PyThreadState *tstate = _PyThreadState_GET();
477 _Py_EnsureTstateNotNULL(tstate);
478
479 status = _PyEval_ReInitThreads(tstate);
Victor Stinner26881c82020-06-02 15:51:37 +0200480 if (_PyStatus_EXCEPTION(status)) {
481 goto fatal_error;
482 }
483
484 status = _PyImport_ReInitLock();
485 if (_PyStatus_EXCEPTION(status)) {
486 goto fatal_error;
487 }
488
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200489 _PySignal_AfterFork();
Victor Stinner26881c82020-06-02 15:51:37 +0200490
491 status = _PyRuntimeState_ReInitThreads(runtime);
492 if (_PyStatus_EXCEPTION(status)) {
493 goto fatal_error;
494 }
495
496 status = _PyInterpreterState_DeleteExceptMain(runtime);
497 if (_PyStatus_EXCEPTION(status)) {
498 goto fatal_error;
499 }
Victor Stinner317bab02020-06-02 18:44:54 +0200500 assert(_PyThreadState_GET() == tstate);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200501
Victor Stinner317bab02020-06-02 18:44:54 +0200502 run_at_forkers(tstate->interp->after_forkers_child, 0);
Victor Stinner26881c82020-06-02 15:51:37 +0200503 return;
504
505fatal_error:
506 Py_ExitStatusException(status);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200507}
508
509static int
510register_at_forker(PyObject **lst, PyObject *func)
511{
Gregory P. Smith163468a2017-05-29 10:03:41 -0700512 if (func == NULL) /* nothing to register? do nothing. */
513 return 0;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200514 if (*lst == NULL) {
515 *lst = PyList_New(0);
516 if (*lst == NULL)
517 return -1;
518 }
519 return PyList_Append(*lst, func);
520}
Victor Stinner87255be2020-04-07 23:11:49 +0200521#endif /* HAVE_FORK */
522
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200523
524/* Legacy wrapper */
525void
526PyOS_AfterFork(void)
527{
528#ifdef HAVE_FORK
529 PyOS_AfterFork_Child();
530#endif
531}
532
533
Victor Stinner6036e442015-03-08 01:58:04 +0100534#ifdef MS_WINDOWS
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200535/* defined in fileutils.c */
Benjamin Petersone5024512018-09-12 12:06:42 -0700536void _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
537void _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *,
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200538 ULONG, struct _Py_stat_struct *);
539#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700540
Larry Hastings9cf065c2012-06-22 16:30:09 -0700541
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200542#ifndef MS_WINDOWS
543PyObject *
544_PyLong_FromUid(uid_t uid)
545{
546 if (uid == (uid_t)-1)
547 return PyLong_FromLong(-1);
548 return PyLong_FromUnsignedLong(uid);
549}
550
551PyObject *
552_PyLong_FromGid(gid_t gid)
553{
554 if (gid == (gid_t)-1)
555 return PyLong_FromLong(-1);
556 return PyLong_FromUnsignedLong(gid);
557}
558
559int
560_Py_Uid_Converter(PyObject *obj, void *p)
561{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700562 uid_t uid;
563 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200564 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200565 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700566 unsigned long uresult;
567
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300568 index = _PyNumber_Index(obj);
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700569 if (index == NULL) {
570 PyErr_Format(PyExc_TypeError,
571 "uid should be integer, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800572 _PyType_Name(Py_TYPE(obj)));
Serhiy Storchakab4621892013-02-10 23:28:02 +0200573 return 0;
574 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700575
576 /*
577 * Handling uid_t is complicated for two reasons:
578 * * Although uid_t is (always?) unsigned, it still
579 * accepts -1.
580 * * We don't know its size in advance--it may be
581 * bigger than an int, or it may be smaller than
582 * a long.
583 *
584 * So a bit of defensive programming is in order.
585 * Start with interpreting the value passed
586 * in as a signed long and see if it works.
587 */
588
589 result = PyLong_AsLongAndOverflow(index, &overflow);
590
591 if (!overflow) {
592 uid = (uid_t)result;
593
594 if (result == -1) {
595 if (PyErr_Occurred())
596 goto fail;
597 /* It's a legitimate -1, we're done. */
598 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200599 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700600
601 /* Any other negative number is disallowed. */
602 if (result < 0)
603 goto underflow;
604
605 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200606 if (sizeof(uid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700607 (long)uid != result)
608 goto underflow;
609 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200610 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700611
612 if (overflow < 0)
613 goto underflow;
614
615 /*
616 * Okay, the value overflowed a signed long. If it
617 * fits in an *unsigned* long, it may still be okay,
618 * as uid_t may be unsigned long on this platform.
619 */
620 uresult = PyLong_AsUnsignedLong(index);
621 if (PyErr_Occurred()) {
622 if (PyErr_ExceptionMatches(PyExc_OverflowError))
623 goto overflow;
624 goto fail;
625 }
626
627 uid = (uid_t)uresult;
628
629 /*
630 * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
631 * but this value would get interpreted as (uid_t)-1 by chown
632 * and its siblings. That's not what the user meant! So we
633 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100634 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700635 */
636 if (uid == (uid_t)-1)
637 goto overflow;
638
639 /* Ensure the value wasn't truncated. */
640 if (sizeof(uid_t) < sizeof(long) &&
641 (unsigned long)uid != uresult)
642 goto overflow;
643 /* fallthrough */
644
645success:
646 Py_DECREF(index);
647 *(uid_t *)p = uid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200648 return 1;
649
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700650underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200651 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700652 "uid is less than minimum");
653 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200654
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700655overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200656 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700657 "uid is greater than maximum");
658 /* fallthrough */
659
660fail:
661 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200662 return 0;
663}
664
665int
666_Py_Gid_Converter(PyObject *obj, void *p)
667{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700668 gid_t gid;
669 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200670 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200671 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700672 unsigned long uresult;
673
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300674 index = _PyNumber_Index(obj);
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700675 if (index == NULL) {
676 PyErr_Format(PyExc_TypeError,
677 "gid should be integer, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800678 _PyType_Name(Py_TYPE(obj)));
Serhiy Storchakab4621892013-02-10 23:28:02 +0200679 return 0;
680 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700681
682 /*
683 * Handling gid_t is complicated for two reasons:
684 * * Although gid_t is (always?) unsigned, it still
685 * accepts -1.
686 * * We don't know its size in advance--it may be
687 * bigger than an int, or it may be smaller than
688 * a long.
689 *
690 * So a bit of defensive programming is in order.
691 * Start with interpreting the value passed
692 * in as a signed long and see if it works.
693 */
694
695 result = PyLong_AsLongAndOverflow(index, &overflow);
696
697 if (!overflow) {
698 gid = (gid_t)result;
699
700 if (result == -1) {
701 if (PyErr_Occurred())
702 goto fail;
703 /* It's a legitimate -1, we're done. */
704 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200705 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700706
707 /* Any other negative number is disallowed. */
708 if (result < 0) {
709 goto underflow;
710 }
711
712 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200713 if (sizeof(gid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700714 (long)gid != result)
715 goto underflow;
716 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200717 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700718
719 if (overflow < 0)
720 goto underflow;
721
722 /*
723 * Okay, the value overflowed a signed long. If it
724 * fits in an *unsigned* long, it may still be okay,
725 * as gid_t may be unsigned long on this platform.
726 */
727 uresult = PyLong_AsUnsignedLong(index);
728 if (PyErr_Occurred()) {
729 if (PyErr_ExceptionMatches(PyExc_OverflowError))
730 goto overflow;
731 goto fail;
732 }
733
734 gid = (gid_t)uresult;
735
736 /*
737 * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
738 * but this value would get interpreted as (gid_t)-1 by chown
739 * and its siblings. That's not what the user meant! So we
740 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100741 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700742 */
743 if (gid == (gid_t)-1)
744 goto overflow;
745
746 /* Ensure the value wasn't truncated. */
747 if (sizeof(gid_t) < sizeof(long) &&
748 (unsigned long)gid != uresult)
749 goto overflow;
750 /* fallthrough */
751
752success:
753 Py_DECREF(index);
754 *(gid_t *)p = gid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200755 return 1;
756
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700757underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200758 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700759 "gid is less than minimum");
760 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200761
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700762overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200763 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700764 "gid is greater than maximum");
765 /* fallthrough */
766
767fail:
768 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200769 return 0;
770}
771#endif /* MS_WINDOWS */
772
773
Benjamin Petersoned4aa832016-09-05 17:44:18 -0700774#define _PyLong_FromDev PyLong_FromLongLong
Gregory P. Smith702dada2015-01-28 16:07:52 -0800775
776
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200777#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
778static int
779_Py_Dev_Converter(PyObject *obj, void *p)
780{
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200781 *((dev_t *)p) = PyLong_AsUnsignedLongLong(obj);
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200782 if (PyErr_Occurred())
783 return 0;
784 return 1;
785}
Gregory P. Smith702dada2015-01-28 16:07:52 -0800786#endif /* HAVE_MKNOD && HAVE_MAKEDEV */
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200787
788
Larry Hastings9cf065c2012-06-22 16:30:09 -0700789#ifdef AT_FDCWD
Trent Nelson9a461052012-09-18 21:50:06 -0400790/*
791 * Why the (int) cast? Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
792 * without the int cast, the value gets interpreted as uint (4291925331),
793 * which doesn't play nicely with all the initializer lines in this file that
794 * look like this:
795 * int dir_fd = DEFAULT_DIR_FD;
796 */
797#define DEFAULT_DIR_FD (int)AT_FDCWD
Larry Hastings9cf065c2012-06-22 16:30:09 -0700798#else
799#define DEFAULT_DIR_FD (-100)
800#endif
801
802static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300803_fd_converter(PyObject *o, int *p)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200804{
805 int overflow;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700806 long long_value;
807
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300808 PyObject *index = _PyNumber_Index(o);
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700809 if (index == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700810 return 0;
811 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700812
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300813 assert(PyLong_Check(index));
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700814 long_value = PyLong_AsLongAndOverflow(index, &overflow);
815 Py_DECREF(index);
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300816 assert(!PyErr_Occurred());
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200817 if (overflow > 0 || long_value > INT_MAX) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700818 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700819 "fd is greater than maximum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700820 return 0;
821 }
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200822 if (overflow < 0 || long_value < INT_MIN) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700823 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700824 "fd is less than minimum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700825 return 0;
826 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700827
Larry Hastings9cf065c2012-06-22 16:30:09 -0700828 *p = (int)long_value;
829 return 1;
830}
831
832static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200833dir_fd_converter(PyObject *o, void *p)
834{
835 if (o == Py_None) {
836 *(int *)p = DEFAULT_DIR_FD;
837 return 1;
838 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300839 else if (PyIndex_Check(o)) {
840 return _fd_converter(o, (int *)p);
841 }
842 else {
843 PyErr_Format(PyExc_TypeError,
844 "argument should be integer or None, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800845 _PyType_Name(Py_TYPE(o)));
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300846 return 0;
847 }
Larry Hastings9cf065c2012-06-22 16:30:09 -0700848}
849
Eddie Elizondob3966632019-11-05 07:16:14 -0800850typedef struct {
851 PyObject *billion;
Eddie Elizondob3966632019-11-05 07:16:14 -0800852 PyObject *DirEntryType;
853 PyObject *ScandirIteratorType;
854#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
855 PyObject *SchedParamType;
856#endif
857 PyObject *StatResultType;
858 PyObject *StatVFSResultType;
859 PyObject *TerminalSizeType;
860 PyObject *TimesResultType;
861 PyObject *UnameResultType;
862#if defined(HAVE_WAITID) && !defined(__APPLE__)
863 PyObject *WaitidResultType;
864#endif
865#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
866 PyObject *struct_rusage;
867#endif
868 PyObject *st_mode;
869} _posixstate;
870
Eddie Elizondob3966632019-11-05 07:16:14 -0800871
Hai Shif707d942020-03-16 21:15:01 +0800872static inline _posixstate*
873get_posix_state(PyObject *module)
874{
875 void *state = PyModule_GetState(module);
876 assert(state != NULL);
877 return (_posixstate *)state;
878}
879
Larry Hastings9cf065c2012-06-22 16:30:09 -0700880/*
881 * A PyArg_ParseTuple "converter" function
882 * that handles filesystem paths in the manner
883 * preferred by the os module.
884 *
885 * path_converter accepts (Unicode) strings and their
886 * subclasses, and bytes and their subclasses. What
887 * it does with the argument depends on the platform:
888 *
889 * * On Windows, if we get a (Unicode) string we
890 * extract the wchar_t * and return it; if we get
Steve Dowercc16be82016-09-08 10:35:16 -0700891 * bytes we decode to wchar_t * and return that.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700892 *
893 * * On all other platforms, strings are encoded
894 * to bytes using PyUnicode_FSConverter, then we
895 * extract the char * from the bytes object and
896 * return that.
897 *
898 * path_converter also optionally accepts signed
899 * integers (representing open file descriptors) instead
900 * of path strings.
901 *
902 * Input fields:
903 * path.nullable
904 * If nonzero, the path is permitted to be None.
905 * path.allow_fd
906 * If nonzero, the path is permitted to be a file handle
907 * (a signed int) instead of a string.
908 * path.function_name
909 * If non-NULL, path_converter will use that as the name
910 * of the function in error messages.
Larry Hastings31826802013-10-19 00:09:25 -0700911 * (If path.function_name is NULL it omits the function name.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700912 * path.argument_name
913 * If non-NULL, path_converter will use that as the name
914 * of the parameter in error messages.
915 * (If path.argument_name is NULL it uses "path".)
916 *
917 * Output fields:
918 * path.wide
919 * Points to the path if it was expressed as Unicode
920 * and was not encoded. (Only used on Windows.)
921 * path.narrow
922 * Points to the path if it was expressed as bytes,
Steve Dowercc16be82016-09-08 10:35:16 -0700923 * or it was Unicode and was encoded to bytes. (On Windows,
Martin Panterb1321fb2016-10-10 00:38:21 +0000924 * is a non-zero integer if the path was expressed as bytes.
Steve Dowercc16be82016-09-08 10:35:16 -0700925 * The type is deliberately incompatible to prevent misuse.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700926 * path.fd
927 * Contains a file descriptor if path.accept_fd was true
928 * and the caller provided a signed integer instead of any
929 * sort of string.
930 *
931 * WARNING: if your "path" parameter is optional, and is
932 * unspecified, path_converter will never get called.
933 * So if you set allow_fd, you *MUST* initialize path.fd = -1
934 * yourself!
935 * path.length
936 * The length of the path in characters, if specified as
937 * a string.
938 * path.object
Xiang Zhang04316c42017-01-08 23:26:57 +0800939 * The original object passed in (if get a PathLike object,
940 * the result of PyOS_FSPath() is treated as the original object).
941 * Own a reference to the object.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700942 * path.cleanup
943 * For internal use only. May point to a temporary object.
944 * (Pay no attention to the man behind the curtain.)
945 *
946 * At most one of path.wide or path.narrow will be non-NULL.
947 * If path was None and path.nullable was set,
948 * or if path was an integer and path.allow_fd was set,
949 * both path.wide and path.narrow will be NULL
950 * and path.length will be 0.
Georg Brandlf7875592012-06-24 13:58:31 +0200951 *
Larry Hastings9cf065c2012-06-22 16:30:09 -0700952 * path_converter takes care to not write to the path_t
953 * unless it's successful. However it must reset the
954 * "cleanup" field each time it's called.
955 *
956 * Use as follows:
957 * path_t path;
958 * memset(&path, 0, sizeof(path));
959 * PyArg_ParseTuple(args, "O&", path_converter, &path);
960 * // ... use values from path ...
961 * path_cleanup(&path);
962 *
963 * (Note that if PyArg_Parse fails you don't need to call
964 * path_cleanup(). However it is safe to do so.)
965 */
966typedef struct {
Victor Stinner292c8352012-10-30 02:17:38 +0100967 const char *function_name;
968 const char *argument_name;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700969 int nullable;
970 int allow_fd;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300971 const wchar_t *wide;
Steve Dowercc16be82016-09-08 10:35:16 -0700972#ifdef MS_WINDOWS
973 BOOL narrow;
974#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300975 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700976#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700977 int fd;
978 Py_ssize_t length;
979 PyObject *object;
980 PyObject *cleanup;
981} path_t;
982
Steve Dowercc16be82016-09-08 10:35:16 -0700983#ifdef MS_WINDOWS
984#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
985 {function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
986#else
Larry Hastings2f936352014-08-05 14:04:04 +1000987#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
988 {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
Steve Dowercc16be82016-09-08 10:35:16 -0700989#endif
Larry Hastings31826802013-10-19 00:09:25 -0700990
Larry Hastings9cf065c2012-06-22 16:30:09 -0700991static void
Xiang Zhang04316c42017-01-08 23:26:57 +0800992path_cleanup(path_t *path)
993{
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +0300994#if !USE_UNICODE_WCHAR_CACHE
995 wchar_t *wide = (wchar_t *)path->wide;
996 path->wide = NULL;
997 PyMem_Free(wide);
998#endif /* USE_UNICODE_WCHAR_CACHE */
Xiang Zhang04316c42017-01-08 23:26:57 +0800999 Py_CLEAR(path->object);
1000 Py_CLEAR(path->cleanup);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001001}
1002
1003static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001004path_converter(PyObject *o, void *p)
1005{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001006 path_t *path = (path_t *)p;
Xiang Zhang04316c42017-01-08 23:26:57 +08001007 PyObject *bytes = NULL;
1008 Py_ssize_t length = 0;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001009 int is_index, is_buffer, is_bytes, is_unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03001010 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -07001011#ifdef MS_WINDOWS
Xiang Zhang04316c42017-01-08 23:26:57 +08001012 PyObject *wo = NULL;
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001013 wchar_t *wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001014#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07001015
1016#define FORMAT_EXCEPTION(exc, fmt) \
1017 PyErr_Format(exc, "%s%s" fmt, \
1018 path->function_name ? path->function_name : "", \
1019 path->function_name ? ": " : "", \
1020 path->argument_name ? path->argument_name : "path")
1021
1022 /* Py_CLEANUP_SUPPORTED support */
1023 if (o == NULL) {
1024 path_cleanup(path);
1025 return 1;
1026 }
1027
Brett Cannon3f9183b2016-08-26 14:44:48 -07001028 /* Ensure it's always safe to call path_cleanup(). */
Xiang Zhang04316c42017-01-08 23:26:57 +08001029 path->object = path->cleanup = NULL;
1030 /* path->object owns a reference to the original object */
1031 Py_INCREF(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001032
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001033 if ((o == Py_None) && path->nullable) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001034 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001035#ifdef MS_WINDOWS
1036 path->narrow = FALSE;
1037#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001038 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001039#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07001040 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001041 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001042 }
1043
Brett Cannon3f9183b2016-08-26 14:44:48 -07001044 /* Only call this here so that we don't treat the return value of
1045 os.fspath() as an fd or buffer. */
1046 is_index = path->allow_fd && PyIndex_Check(o);
1047 is_buffer = PyObject_CheckBuffer(o);
1048 is_bytes = PyBytes_Check(o);
1049 is_unicode = PyUnicode_Check(o);
1050
1051 if (!is_index && !is_buffer && !is_unicode && !is_bytes) {
1052 /* Inline PyOS_FSPath() for better error messages. */
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001053 PyObject *func, *res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001054
1055 func = _PyObject_LookupSpecial(o, &PyId___fspath__);
1056 if (NULL == func) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001057 goto error_format;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001058 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001059 res = _PyObject_CallNoArg(func);
Brett Cannon3f9183b2016-08-26 14:44:48 -07001060 Py_DECREF(func);
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001061 if (NULL == res) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001062 goto error_exit;
1063 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001064 else if (PyUnicode_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001065 is_unicode = 1;
1066 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001067 else if (PyBytes_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001068 is_bytes = 1;
1069 }
1070 else {
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001071 PyErr_Format(PyExc_TypeError,
1072 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -08001073 "not %.200s", _PyType_Name(Py_TYPE(o)),
1074 _PyType_Name(Py_TYPE(res)));
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001075 Py_DECREF(res);
1076 goto error_exit;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001077 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001078
1079 /* still owns a reference to the original object */
1080 Py_DECREF(o);
1081 o = res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001082 }
1083
1084 if (is_unicode) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001085#ifdef MS_WINDOWS
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001086#if USE_UNICODE_WCHAR_CACHE
1087_Py_COMP_DIAG_PUSH
1088_Py_COMP_DIAG_IGNORE_DEPR_DECLS
Victor Stinner26c03bd2016-09-19 11:55:44 +02001089 wide = PyUnicode_AsUnicodeAndSize(o, &length);
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001090_Py_COMP_DIAG_POP
1091#else /* USE_UNICODE_WCHAR_CACHE */
1092 wide = PyUnicode_AsWideCharString(o, &length);
1093#endif /* USE_UNICODE_WCHAR_CACHE */
Victor Stinner59799a82013-11-13 14:17:30 +01001094 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001095 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001096 }
Victor Stinner59799a82013-11-13 14:17:30 +01001097 if (length > 32767) {
1098 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001099 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001100 }
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001101 if (wcslen(wide) != length) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001102 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001103 goto error_exit;
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001104 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001105
1106 path->wide = wide;
Xiang Zhang04316c42017-01-08 23:26:57 +08001107 path->narrow = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001108 path->fd = -1;
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001109#if !USE_UNICODE_WCHAR_CACHE
1110 wide = NULL;
1111#endif /* USE_UNICODE_WCHAR_CACHE */
Xiang Zhang04316c42017-01-08 23:26:57 +08001112 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001113#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001114 if (!PyUnicode_FSConverter(o, &bytes)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001115 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001116 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001117#endif
1118 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001119 else if (is_bytes) {
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001120 bytes = o;
1121 Py_INCREF(bytes);
1122 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001123 else if (is_buffer) {
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03001124 /* XXX Replace PyObject_CheckBuffer with PyBytes_Check in other code
Ville Skyttä49b27342017-08-03 09:00:59 +03001125 after removing support of non-bytes buffer objects. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001126 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1127 "%s%s%s should be %s, not %.200s",
1128 path->function_name ? path->function_name : "",
1129 path->function_name ? ": " : "",
1130 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001131 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1132 "integer or None" :
1133 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1134 path->nullable ? "string, bytes, os.PathLike or None" :
1135 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001136 _PyType_Name(Py_TYPE(o)))) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001137 goto error_exit;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001138 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001139 bytes = PyBytes_FromObject(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001140 if (!bytes) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001141 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001142 }
1143 }
Steve Dowercc16be82016-09-08 10:35:16 -07001144 else if (is_index) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001145 if (!_fd_converter(o, &path->fd)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001146 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001147 }
1148 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001149#ifdef MS_WINDOWS
1150 path->narrow = FALSE;
1151#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001152 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001153#endif
Xiang Zhang04316c42017-01-08 23:26:57 +08001154 goto success_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001155 }
1156 else {
Xiang Zhang04316c42017-01-08 23:26:57 +08001157 error_format:
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001158 PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
1159 path->function_name ? path->function_name : "",
1160 path->function_name ? ": " : "",
1161 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001162 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1163 "integer or None" :
1164 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1165 path->nullable ? "string, bytes, os.PathLike or None" :
1166 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001167 _PyType_Name(Py_TYPE(o)));
Xiang Zhang04316c42017-01-08 23:26:57 +08001168 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001169 }
1170
Larry Hastings9cf065c2012-06-22 16:30:09 -07001171 length = PyBytes_GET_SIZE(bytes);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001172 narrow = PyBytes_AS_STRING(bytes);
Victor Stinner706768c2014-08-16 01:03:39 +02001173 if ((size_t)length != strlen(narrow)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03001174 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001175 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001176 }
1177
Steve Dowercc16be82016-09-08 10:35:16 -07001178#ifdef MS_WINDOWS
1179 wo = PyUnicode_DecodeFSDefaultAndSize(
1180 narrow,
1181 length
1182 );
1183 if (!wo) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001184 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001185 }
1186
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001187#if USE_UNICODE_WCHAR_CACHE
1188_Py_COMP_DIAG_PUSH
1189_Py_COMP_DIAG_IGNORE_DEPR_DECLS
Xiang Zhang04316c42017-01-08 23:26:57 +08001190 wide = PyUnicode_AsUnicodeAndSize(wo, &length);
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001191_Py_COMP_DIAG_POP
1192#else /* USE_UNICODE_WCHAR_CACHE */
1193 wide = PyUnicode_AsWideCharString(wo, &length);
1194 Py_DECREF(wo);
1195#endif /* USE_UNICODE_WCHAR_CACHE */
Steve Dowercc16be82016-09-08 10:35:16 -07001196 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001197 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001198 }
1199 if (length > 32767) {
1200 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001201 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001202 }
1203 if (wcslen(wide) != length) {
1204 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001205 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001206 }
1207 path->wide = wide;
1208 path->narrow = TRUE;
Xiang Zhang04316c42017-01-08 23:26:57 +08001209 Py_DECREF(bytes);
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001210#if USE_UNICODE_WCHAR_CACHE
1211 path->cleanup = wo;
1212#else /* USE_UNICODE_WCHAR_CACHE */
1213 wide = NULL;
1214#endif /* USE_UNICODE_WCHAR_CACHE */
Steve Dowercc16be82016-09-08 10:35:16 -07001215#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001216 path->wide = NULL;
1217 path->narrow = narrow;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001218 if (bytes == o) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001219 /* Still a reference owned by path->object, don't have to
1220 worry about path->narrow is used after free. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001221 Py_DECREF(bytes);
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001222 }
1223 else {
1224 path->cleanup = bytes;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001225 }
Xiang Zhang04316c42017-01-08 23:26:57 +08001226#endif
1227 path->fd = -1;
1228
1229 success_exit:
1230 path->length = length;
1231 path->object = o;
1232 return Py_CLEANUP_SUPPORTED;
1233
1234 error_exit:
1235 Py_XDECREF(o);
1236 Py_XDECREF(bytes);
1237#ifdef MS_WINDOWS
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001238#if USE_UNICODE_WCHAR_CACHE
Xiang Zhang04316c42017-01-08 23:26:57 +08001239 Py_XDECREF(wo);
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +03001240#else /* USE_UNICODE_WCHAR_CACHE */
1241 PyMem_Free(wide);
1242#endif /* USE_UNICODE_WCHAR_CACHE */
Xiang Zhang04316c42017-01-08 23:26:57 +08001243#endif
1244 return 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001245}
1246
1247static void
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001248argument_unavailable_error(const char *function_name, const char *argument_name)
1249{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001250 PyErr_Format(PyExc_NotImplementedError,
1251 "%s%s%s unavailable on this platform",
1252 (function_name != NULL) ? function_name : "",
1253 (function_name != NULL) ? ": ": "",
1254 argument_name);
1255}
1256
1257static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001258dir_fd_unavailable(PyObject *o, void *p)
1259{
1260 int dir_fd;
1261 if (!dir_fd_converter(o, &dir_fd))
Larry Hastings9cf065c2012-06-22 16:30:09 -07001262 return 0;
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001263 if (dir_fd != DEFAULT_DIR_FD) {
1264 argument_unavailable_error(NULL, "dir_fd");
1265 return 0;
1266 }
1267 *(int *)p = dir_fd;
1268 return 1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001269}
1270
1271static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001272fd_specified(const char *function_name, int fd)
1273{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001274 if (fd == -1)
1275 return 0;
1276
1277 argument_unavailable_error(function_name, "fd");
1278 return 1;
1279}
1280
1281static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001282follow_symlinks_specified(const char *function_name, int follow_symlinks)
1283{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001284 if (follow_symlinks)
1285 return 0;
1286
1287 argument_unavailable_error(function_name, "follow_symlinks");
1288 return 1;
1289}
1290
1291static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001292path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
1293{
Steve Dowercc16be82016-09-08 10:35:16 -07001294 if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
1295#ifndef MS_WINDOWS
1296 && !path->narrow
1297#endif
1298 ) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001299 PyErr_Format(PyExc_ValueError,
1300 "%s: can't specify dir_fd without matching path",
1301 function_name);
1302 return 1;
1303 }
1304 return 0;
1305}
1306
1307static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001308dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
1309{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001310 if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
1311 PyErr_Format(PyExc_ValueError,
1312 "%s: can't specify both dir_fd and fd",
1313 function_name);
1314 return 1;
1315 }
1316 return 0;
1317}
1318
1319static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001320fd_and_follow_symlinks_invalid(const char *function_name, int fd,
1321 int follow_symlinks)
1322{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001323 if ((fd > 0) && (!follow_symlinks)) {
1324 PyErr_Format(PyExc_ValueError,
1325 "%s: cannot use fd and follow_symlinks together",
1326 function_name);
1327 return 1;
1328 }
1329 return 0;
1330}
1331
1332static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001333dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
1334 int follow_symlinks)
1335{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001336 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
1337 PyErr_Format(PyExc_ValueError,
1338 "%s: cannot use dir_fd and follow_symlinks together",
1339 function_name);
1340 return 1;
1341 }
1342 return 0;
1343}
1344
Larry Hastings2f936352014-08-05 14:04:04 +10001345#ifdef MS_WINDOWS
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001346 typedef long long Py_off_t;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001347#else
Larry Hastings2f936352014-08-05 14:04:04 +10001348 typedef off_t Py_off_t;
1349#endif
1350
1351static int
1352Py_off_t_converter(PyObject *arg, void *addr)
1353{
1354#ifdef HAVE_LARGEFILE_SUPPORT
1355 *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
1356#else
1357 *((Py_off_t *)addr) = PyLong_AsLong(arg);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001358#endif
1359 if (PyErr_Occurred())
1360 return 0;
1361 return 1;
1362}
Larry Hastings2f936352014-08-05 14:04:04 +10001363
1364static PyObject *
1365PyLong_FromPy_off_t(Py_off_t offset)
1366{
1367#ifdef HAVE_LARGEFILE_SUPPORT
1368 return PyLong_FromLongLong(offset);
1369#else
1370 return PyLong_FromLong(offset);
Ross Lagerwallb1e5d592011-09-19 08:30:43 +02001371#endif
Larry Hastings2f936352014-08-05 14:04:04 +10001372}
1373
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001374#ifdef HAVE_SIGSET_T
1375/* Convert an iterable of integers to a sigset.
1376 Return 1 on success, return 0 and raise an exception on error. */
1377int
1378_Py_Sigset_Converter(PyObject *obj, void *addr)
1379{
1380 sigset_t *mask = (sigset_t *)addr;
1381 PyObject *iterator, *item;
1382 long signum;
1383 int overflow;
1384
Rémi Lapeyref0900192019-05-04 01:30:53 +02001385 // The extra parens suppress the unreachable-code warning with clang on MacOS
1386 if (sigemptyset(mask) < (0)) {
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001387 /* Probably only if mask == NULL. */
1388 PyErr_SetFromErrno(PyExc_OSError);
1389 return 0;
1390 }
1391
1392 iterator = PyObject_GetIter(obj);
1393 if (iterator == NULL) {
1394 return 0;
1395 }
1396
1397 while ((item = PyIter_Next(iterator)) != NULL) {
1398 signum = PyLong_AsLongAndOverflow(item, &overflow);
1399 Py_DECREF(item);
1400 if (signum <= 0 || signum >= NSIG) {
1401 if (overflow || signum != -1 || !PyErr_Occurred()) {
1402 PyErr_Format(PyExc_ValueError,
1403 "signal number %ld out of range", signum);
1404 }
1405 goto error;
1406 }
1407 if (sigaddset(mask, (int)signum)) {
1408 if (errno != EINVAL) {
1409 /* Probably impossible */
1410 PyErr_SetFromErrno(PyExc_OSError);
1411 goto error;
1412 }
1413 /* For backwards compatibility, allow idioms such as
1414 * `range(1, NSIG)` but warn about invalid signal numbers
1415 */
1416 const char msg[] =
1417 "invalid signal number %ld, please use valid_signals()";
1418 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
1419 goto error;
1420 }
1421 }
1422 }
1423 if (!PyErr_Occurred()) {
1424 Py_DECREF(iterator);
1425 return 1;
1426 }
1427
1428error:
1429 Py_DECREF(iterator);
1430 return 0;
1431}
1432#endif /* HAVE_SIGSET_T */
1433
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001434#ifdef MS_WINDOWS
Brian Curtinf5e76d02010-11-24 13:14:05 +00001435
1436static int
Brian Curtind25aef52011-06-13 15:16:04 -05001437win32_get_reparse_tag(HANDLE reparse_point_handle, ULONG *reparse_tag)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001438{
Martin Panter70214ad2016-08-04 02:38:59 +00001439 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1440 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001441 DWORD n_bytes_returned;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001442
1443 if (0 == DeviceIoControl(
1444 reparse_point_handle,
1445 FSCTL_GET_REPARSE_POINT,
1446 NULL, 0, /* in buffer */
1447 target_buffer, sizeof(target_buffer),
1448 &n_bytes_returned,
1449 NULL)) /* we're not using OVERLAPPED_IO */
Brian Curtind25aef52011-06-13 15:16:04 -05001450 return FALSE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001451
1452 if (reparse_tag)
1453 *reparse_tag = rdb->ReparseTag;
1454
Brian Curtind25aef52011-06-13 15:16:04 -05001455 return TRUE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001456}
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001457
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001458#endif /* MS_WINDOWS */
Brian Curtinf5e76d02010-11-24 13:14:05 +00001459
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001460/* Return a dictionary corresponding to the POSIX environment table */
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001461#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Jack Jansenea0c3822002-08-01 21:57:49 +00001462/* On Darwin/MacOSX a shared library or framework has no access to
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001463** environ directly, we must obtain it with _NSGetEnviron(). See also
1464** man environ(7).
Jack Jansenea0c3822002-08-01 21:57:49 +00001465*/
1466#include <crt_externs.h>
pxinwrf2d7ac72019-05-21 18:46:37 +08001467#elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001468extern char **environ;
Guido van Rossuma4916fa1996-05-23 22:58:55 +00001469#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001470
Barry Warsaw53699e91996-12-10 23:23:01 +00001471static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001472convertenviron(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001473{
Victor Stinner8c62be82010-05-06 00:08:46 +00001474 PyObject *d;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001475#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00001476 wchar_t **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001477#else
Victor Stinner8c62be82010-05-06 00:08:46 +00001478 char **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001479#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +00001480
Victor Stinner8c62be82010-05-06 00:08:46 +00001481 d = PyDict_New();
1482 if (d == NULL)
1483 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001484#ifdef MS_WINDOWS
1485 /* _wenviron must be initialized in this way if the program is started
1486 through main() instead of wmain(). */
1487 _wgetenv(L"");
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001488 e = _wenviron;
Benoit Hudson723f71a2019-12-06 14:15:03 -05001489#elif defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
1490 /* environ is not accessible as an extern in a shared object on OSX; use
1491 _NSGetEnviron to resolve it. The value changes if you add environment
1492 variables between calls to Py_Initialize, so don't cache the value. */
1493 e = *_NSGetEnviron();
Victor Stinner8c62be82010-05-06 00:08:46 +00001494#else
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001495 e = environ;
1496#endif
1497 if (e == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +00001498 return d;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001499 for (; *e != NULL; e++) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001500 PyObject *k;
1501 PyObject *v;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001502#ifdef MS_WINDOWS
1503 const wchar_t *p = wcschr(*e, L'=');
1504#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03001505 const char *p = strchr(*e, '=');
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001506#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001507 if (p == NULL)
1508 continue;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001509#ifdef MS_WINDOWS
1510 k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
1511#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001512 k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001513#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001514 if (k == NULL) {
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001515 Py_DECREF(d);
1516 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001517 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001518#ifdef MS_WINDOWS
1519 v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
1520#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001521 v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001522#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001523 if (v == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001524 Py_DECREF(k);
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001525 Py_DECREF(d);
1526 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001527 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001528 if (PyDict_GetItemWithError(d, k) == NULL) {
1529 if (PyErr_Occurred() || PyDict_SetItem(d, k, v) != 0) {
1530 Py_DECREF(v);
1531 Py_DECREF(k);
1532 Py_DECREF(d);
1533 return NULL;
1534 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001535 }
1536 Py_DECREF(k);
1537 Py_DECREF(v);
Guido van Rossumd48f2521997-12-05 22:19:34 +00001538 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001539 return d;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001540}
1541
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001542/* Set a POSIX-specific error from errno, and return NULL */
1543
Barry Warsawd58d7641998-07-23 16:14:40 +00001544static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001545posix_error(void)
Guido van Rossumad0ee831995-03-01 10:34:45 +00001546{
Victor Stinner8c62be82010-05-06 00:08:46 +00001547 return PyErr_SetFromErrno(PyExc_OSError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001548}
Mark Hammondef8b6542001-05-13 08:04:26 +00001549
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001550#ifdef MS_WINDOWS
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001551static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001552win32_error(const char* function, const char* filename)
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001553{
Victor Stinner8c62be82010-05-06 00:08:46 +00001554 /* XXX We should pass the function name along in the future.
1555 (winreg.c also wants to pass the function name.)
1556 This would however require an additional param to the
1557 Windows error object, which is non-trivial.
1558 */
1559 errno = GetLastError();
1560 if (filename)
1561 return PyErr_SetFromWindowsErrWithFilename(errno, filename);
1562 else
1563 return PyErr_SetFromWindowsErr(errno);
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001564}
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001565
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001566static PyObject *
Steve Dower2438cdf2019-03-29 16:37:16 -07001567win32_error_object_err(const char* function, PyObject* filename, DWORD err)
Victor Stinnereb5657a2011-09-30 01:44:27 +02001568{
1569 /* XXX - see win32_error for comments on 'function' */
Victor Stinnereb5657a2011-09-30 01:44:27 +02001570 if (filename)
1571 return PyErr_SetExcFromWindowsErrWithFilenameObject(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001572 PyExc_OSError,
Steve Dower2438cdf2019-03-29 16:37:16 -07001573 err,
Victor Stinnereb5657a2011-09-30 01:44:27 +02001574 filename);
1575 else
Steve Dower2438cdf2019-03-29 16:37:16 -07001576 return PyErr_SetFromWindowsErr(err);
1577}
1578
1579static PyObject *
1580win32_error_object(const char* function, PyObject* filename)
1581{
1582 errno = GetLastError();
1583 return win32_error_object_err(function, filename, errno);
Victor Stinnereb5657a2011-09-30 01:44:27 +02001584}
1585
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001586#endif /* MS_WINDOWS */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001587
Larry Hastings9cf065c2012-06-22 16:30:09 -07001588static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001589posix_path_object_error(PyObject *path)
1590{
1591 return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
1592}
1593
1594static PyObject *
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001595path_object_error(PyObject *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001596{
1597#ifdef MS_WINDOWS
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001598 return PyErr_SetExcFromWindowsErrWithFilenameObject(
1599 PyExc_OSError, 0, path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001600#else
Alexey Izbyshev83460312018-10-20 03:28:22 +03001601 return posix_path_object_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001602#endif
1603}
1604
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001605static PyObject *
1606path_object_error2(PyObject *path, PyObject *path2)
1607{
1608#ifdef MS_WINDOWS
1609 return PyErr_SetExcFromWindowsErrWithFilenameObjects(
1610 PyExc_OSError, 0, path, path2);
1611#else
1612 return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
1613#endif
1614}
1615
1616static PyObject *
1617path_error(path_t *path)
1618{
1619 return path_object_error(path->object);
1620}
Larry Hastings31826802013-10-19 00:09:25 -07001621
Larry Hastingsb0827312014-02-09 22:05:19 -08001622static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001623posix_path_error(path_t *path)
1624{
1625 return posix_path_object_error(path->object);
1626}
1627
1628static PyObject *
Larry Hastingsb0827312014-02-09 22:05:19 -08001629path_error2(path_t *path, path_t *path2)
1630{
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001631 return path_object_error2(path->object, path2->object);
Larry Hastingsb0827312014-02-09 22:05:19 -08001632}
1633
1634
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001635/* POSIX generic methods */
1636
Larry Hastings2f936352014-08-05 14:04:04 +10001637static int
1638fildes_converter(PyObject *o, void *p)
Fred Drake4d1e64b2002-04-15 19:40:07 +00001639{
Victor Stinner8c62be82010-05-06 00:08:46 +00001640 int fd;
Larry Hastings2f936352014-08-05 14:04:04 +10001641 int *pointer = (int *)p;
1642 fd = PyObject_AsFileDescriptor(o);
Victor Stinner8c62be82010-05-06 00:08:46 +00001643 if (fd < 0)
Larry Hastings2f936352014-08-05 14:04:04 +10001644 return 0;
Larry Hastings2f936352014-08-05 14:04:04 +10001645 *pointer = fd;
1646 return 1;
1647}
1648
1649static PyObject *
1650posix_fildes_fd(int fd, int (*func)(int))
1651{
1652 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001653 int async_err = 0;
1654
1655 do {
1656 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001657 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001658 res = (*func)(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001659 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001660 Py_END_ALLOW_THREADS
1661 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1662 if (res != 0)
1663 return (!async_err) ? posix_error() : NULL;
1664 Py_RETURN_NONE;
Fred Drake4d1e64b2002-04-15 19:40:07 +00001665}
Guido van Rossum21142a01999-01-08 21:05:37 +00001666
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001667
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001668#ifdef MS_WINDOWS
Thomas Wouters477c8d52006-05-27 19:21:47 +00001669/* This is a reimplementation of the C library's chdir function,
1670 but one that produces Win32 errors instead of DOS error codes.
1671 chdir is essentially a wrapper around SetCurrentDirectory; however,
1672 it also needs to set "magic" environment variables indicating
1673 the per-drive current directory, which are of the form =<drive>: */
Benjamin Peterson206e3072008-10-19 14:07:49 +00001674static BOOL __stdcall
Thomas Wouters477c8d52006-05-27 19:21:47 +00001675win32_wchdir(LPCWSTR path)
1676{
Victor Stinnered537822015-12-13 21:40:26 +01001677 wchar_t path_buf[MAX_PATH], *new_path = path_buf;
Victor Stinner8c62be82010-05-06 00:08:46 +00001678 int result;
1679 wchar_t env[4] = L"=x:";
Thomas Wouters477c8d52006-05-27 19:21:47 +00001680
Victor Stinner8c62be82010-05-06 00:08:46 +00001681 if(!SetCurrentDirectoryW(path))
1682 return FALSE;
Victor Stinnered537822015-12-13 21:40:26 +01001683 result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001684 if (!result)
1685 return FALSE;
Victor Stinnere847d712015-12-14 00:21:50 +01001686 if (result > Py_ARRAY_LENGTH(path_buf)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001687 new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00001688 if (!new_path) {
1689 SetLastError(ERROR_OUTOFMEMORY);
1690 return FALSE;
1691 }
1692 result = GetCurrentDirectoryW(result, new_path);
1693 if (!result) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001694 PyMem_RawFree(new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001695 return FALSE;
1696 }
1697 }
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001698 int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
1699 wcsncmp(new_path, L"//", 2) == 0);
1700 if (!is_unc_like_path) {
1701 env[1] = new_path[0];
1702 result = SetEnvironmentVariableW(env, new_path);
1703 }
Victor Stinnered537822015-12-13 21:40:26 +01001704 if (new_path != path_buf)
Victor Stinnerb6404912013-07-07 16:21:41 +02001705 PyMem_RawFree(new_path);
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001706 return result ? TRUE : FALSE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001707}
1708#endif
1709
Martin v. Löwis14694662006-02-03 12:54:16 +00001710#ifdef MS_WINDOWS
1711/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
1712 - time stamps are restricted to second resolution
1713 - file modification times suffer from forth-and-back conversions between
1714 UTC and local time
1715 Therefore, we implement our own stat, based on the Win32 API directly.
1716*/
Victor Stinner8c62be82010-05-06 00:08:46 +00001717#define HAVE_STAT_NSEC 1
Zachary Ware63f277b2014-06-19 09:46:37 -05001718#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001719#define HAVE_STRUCT_STAT_ST_REPARSE_TAG 1
Martin v. Löwis14694662006-02-03 12:54:16 +00001720
Victor Stinner6036e442015-03-08 01:58:04 +01001721static void
Steve Dowercc16be82016-09-08 10:35:16 -07001722find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
1723 BY_HANDLE_FILE_INFORMATION *info,
1724 ULONG *reparse_tag)
Victor Stinner6036e442015-03-08 01:58:04 +01001725{
1726 memset(info, 0, sizeof(*info));
1727 info->dwFileAttributes = pFileData->dwFileAttributes;
1728 info->ftCreationTime = pFileData->ftCreationTime;
1729 info->ftLastAccessTime = pFileData->ftLastAccessTime;
1730 info->ftLastWriteTime = pFileData->ftLastWriteTime;
1731 info->nFileSizeHigh = pFileData->nFileSizeHigh;
1732 info->nFileSizeLow = pFileData->nFileSizeLow;
1733/* info->nNumberOfLinks = 1; */
1734 if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
1735 *reparse_tag = pFileData->dwReserved0;
1736 else
1737 *reparse_tag = 0;
1738}
1739
Guido van Rossumd8faa362007-04-27 19:54:29 +00001740static BOOL
Steve Dowercc16be82016-09-08 10:35:16 -07001741attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001742{
Victor Stinner8c62be82010-05-06 00:08:46 +00001743 HANDLE hFindFile;
1744 WIN32_FIND_DATAW FileData;
1745 hFindFile = FindFirstFileW(pszFile, &FileData);
1746 if (hFindFile == INVALID_HANDLE_VALUE)
1747 return FALSE;
1748 FindClose(hFindFile);
Steve Dowercc16be82016-09-08 10:35:16 -07001749 find_data_to_file_info(&FileData, info, reparse_tag);
Victor Stinner8c62be82010-05-06 00:08:46 +00001750 return TRUE;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001751}
1752
Brian Curtind25aef52011-06-13 15:16:04 -05001753static int
Steve Dowercc16be82016-09-08 10:35:16 -07001754win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
Brian Curtind25aef52011-06-13 15:16:04 -05001755 BOOL traverse)
1756{
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001757 HANDLE hFile;
1758 BY_HANDLE_FILE_INFORMATION fileInfo;
1759 FILE_ATTRIBUTE_TAG_INFO tagInfo = { 0 };
1760 DWORD fileType, error;
1761 BOOL isUnhandledTag = FALSE;
1762 int retval = 0;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001763
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001764 DWORD access = FILE_READ_ATTRIBUTES;
1765 DWORD flags = FILE_FLAG_BACKUP_SEMANTICS; /* Allow opening directories. */
1766 if (!traverse) {
1767 flags |= FILE_FLAG_OPEN_REPARSE_POINT;
1768 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001769
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001770 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING, flags, NULL);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001771 if (hFile == INVALID_HANDLE_VALUE) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001772 /* Either the path doesn't exist, or the caller lacks access. */
1773 error = GetLastError();
1774 switch (error) {
1775 case ERROR_ACCESS_DENIED: /* Cannot sync or read attributes. */
1776 case ERROR_SHARING_VIOLATION: /* It's a paging file. */
1777 /* Try reading the parent directory. */
1778 if (!attributes_from_dir(path, &fileInfo, &tagInfo.ReparseTag)) {
1779 /* Cannot read the parent directory. */
1780 SetLastError(error);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001781 return -1;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001782 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001783 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1784 if (traverse ||
1785 !IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1786 /* The stat call has to traverse but cannot, so fail. */
1787 SetLastError(error);
Brian Curtind25aef52011-06-13 15:16:04 -05001788 return -1;
Mark Becwarb82bfac2019-02-02 16:08:23 -05001789 }
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001790 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001791 break;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001792
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001793 case ERROR_INVALID_PARAMETER:
1794 /* \\.\con requires read or write access. */
1795 hFile = CreateFileW(path, access | GENERIC_READ,
1796 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1797 OPEN_EXISTING, flags, NULL);
1798 if (hFile == INVALID_HANDLE_VALUE) {
1799 SetLastError(error);
1800 return -1;
1801 }
1802 break;
1803
1804 case ERROR_CANT_ACCESS_FILE:
1805 /* bpo37834: open unhandled reparse points if traverse fails. */
1806 if (traverse) {
1807 traverse = FALSE;
1808 isUnhandledTag = TRUE;
1809 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING,
1810 flags | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
1811 }
1812 if (hFile == INVALID_HANDLE_VALUE) {
1813 SetLastError(error);
1814 return -1;
1815 }
1816 break;
1817
1818 default:
1819 return -1;
1820 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001821 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001822
1823 if (hFile != INVALID_HANDLE_VALUE) {
1824 /* Handle types other than files on disk. */
1825 fileType = GetFileType(hFile);
1826 if (fileType != FILE_TYPE_DISK) {
1827 if (fileType == FILE_TYPE_UNKNOWN && GetLastError() != 0) {
1828 retval = -1;
1829 goto cleanup;
1830 }
1831 DWORD fileAttributes = GetFileAttributesW(path);
1832 memset(result, 0, sizeof(*result));
1833 if (fileAttributes != INVALID_FILE_ATTRIBUTES &&
1834 fileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1835 /* \\.\pipe\ or \\.\mailslot\ */
1836 result->st_mode = _S_IFDIR;
1837 } else if (fileType == FILE_TYPE_CHAR) {
1838 /* \\.\nul */
1839 result->st_mode = _S_IFCHR;
1840 } else if (fileType == FILE_TYPE_PIPE) {
1841 /* \\.\pipe\spam */
1842 result->st_mode = _S_IFIFO;
1843 }
1844 /* FILE_TYPE_UNKNOWN, e.g. \\.\mailslot\waitfor.exe\spam */
1845 goto cleanup;
1846 }
1847
1848 /* Query the reparse tag, and traverse a non-link. */
1849 if (!traverse) {
1850 if (!GetFileInformationByHandleEx(hFile, FileAttributeTagInfo,
1851 &tagInfo, sizeof(tagInfo))) {
1852 /* Allow devices that do not support FileAttributeTagInfo. */
1853 switch (GetLastError()) {
1854 case ERROR_INVALID_PARAMETER:
1855 case ERROR_INVALID_FUNCTION:
1856 case ERROR_NOT_SUPPORTED:
1857 tagInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1858 tagInfo.ReparseTag = 0;
1859 break;
1860 default:
1861 retval = -1;
1862 goto cleanup;
1863 }
1864 } else if (tagInfo.FileAttributes &
1865 FILE_ATTRIBUTE_REPARSE_POINT) {
1866 if (IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1867 if (isUnhandledTag) {
1868 /* Traversing previously failed for either this link
1869 or its target. */
1870 SetLastError(ERROR_CANT_ACCESS_FILE);
1871 retval = -1;
1872 goto cleanup;
1873 }
1874 /* Traverse a non-link, but not if traversing already failed
1875 for an unhandled tag. */
1876 } else if (!isUnhandledTag) {
1877 CloseHandle(hFile);
1878 return win32_xstat_impl(path, result, TRUE);
1879 }
1880 }
1881 }
1882
1883 if (!GetFileInformationByHandle(hFile, &fileInfo)) {
1884 switch (GetLastError()) {
1885 case ERROR_INVALID_PARAMETER:
1886 case ERROR_INVALID_FUNCTION:
1887 case ERROR_NOT_SUPPORTED:
Steve Dower772ec0f2019-09-04 14:42:54 -07001888 /* Volumes and physical disks are block devices, e.g.
1889 \\.\C: and \\.\PhysicalDrive0. */
1890 memset(result, 0, sizeof(*result));
1891 result->st_mode = 0x6000; /* S_IFBLK */
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001892 goto cleanup;
1893 }
Steve Dower772ec0f2019-09-04 14:42:54 -07001894 retval = -1;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001895 goto cleanup;
1896 }
1897 }
1898
1899 _Py_attribute_data_to_stat(&fileInfo, tagInfo.ReparseTag, result);
1900
1901 if (!(fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
1902 /* Fix the file execute permissions. This hack sets S_IEXEC if
1903 the filename has an extension that is commonly used by files
1904 that CreateProcessW can execute. A real implementation calls
1905 GetSecurityInfo, OpenThreadToken/OpenProcessToken, and
1906 AccessCheck to check for generic read, write, and execute
1907 access. */
1908 const wchar_t *fileExtension = wcsrchr(path, '.');
1909 if (fileExtension) {
1910 if (_wcsicmp(fileExtension, L".exe") == 0 ||
1911 _wcsicmp(fileExtension, L".bat") == 0 ||
1912 _wcsicmp(fileExtension, L".cmd") == 0 ||
1913 _wcsicmp(fileExtension, L".com") == 0) {
1914 result->st_mode |= 0111;
1915 }
1916 }
1917 }
1918
1919cleanup:
1920 if (hFile != INVALID_HANDLE_VALUE) {
Steve Dower772ec0f2019-09-04 14:42:54 -07001921 /* Preserve last error if we are failing */
1922 error = retval ? GetLastError() : 0;
1923 if (!CloseHandle(hFile)) {
1924 retval = -1;
1925 } else if (retval) {
1926 /* Restore last error */
1927 SetLastError(error);
1928 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001929 }
1930
1931 return retval;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001932}
1933
1934static int
Steve Dowercc16be82016-09-08 10:35:16 -07001935win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001936{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001937 /* Protocol violation: we explicitly clear errno, instead of
1938 setting it to a POSIX error. Callers should use GetLastError. */
Brian Curtind25aef52011-06-13 15:16:04 -05001939 int code = win32_xstat_impl(path, result, traverse);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001940 errno = 0;
1941 return code;
1942}
Brian Curtind25aef52011-06-13 15:16:04 -05001943/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
Brian Curtind40e6f72010-07-08 21:39:08 +00001944
1945 In Posix, stat automatically traverses symlinks and returns the stat
1946 structure for the target. In Windows, the equivalent GetFileAttributes by
1947 default does not traverse symlinks and instead returns attributes for
1948 the symlink.
1949
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001950 Instead, we will open the file (which *does* traverse symlinks by default)
1951 and GetFileInformationByHandle(). */
Brian Curtind40e6f72010-07-08 21:39:08 +00001952
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001953static int
Steve Dowercc16be82016-09-08 10:35:16 -07001954win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
Martin v. Löwis14694662006-02-03 12:54:16 +00001955{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001956 return win32_xstat(path, result, FALSE);
Martin v. Löwis14694662006-02-03 12:54:16 +00001957}
1958
Victor Stinner8c62be82010-05-06 00:08:46 +00001959static int
Steve Dowercc16be82016-09-08 10:35:16 -07001960win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
Brian Curtind40e6f72010-07-08 21:39:08 +00001961{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001962 return win32_xstat(path, result, TRUE);
Brian Curtind40e6f72010-07-08 21:39:08 +00001963}
1964
Martin v. Löwis14694662006-02-03 12:54:16 +00001965#endif /* MS_WINDOWS */
1966
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001967PyDoc_STRVAR(stat_result__doc__,
Larry Hastings9cf065c2012-06-22 16:30:09 -07001968"stat_result: Result from stat, fstat, or lstat.\n\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001969This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001970 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001971or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1972\n\
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001973Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1974or st_flags, they are available as attributes only.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001975\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001976See os.stat for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001977
1978static PyStructSequence_Field stat_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001979 {"st_mode", "protection bits"},
1980 {"st_ino", "inode"},
1981 {"st_dev", "device"},
1982 {"st_nlink", "number of hard links"},
1983 {"st_uid", "user ID of owner"},
1984 {"st_gid", "group ID of owner"},
1985 {"st_size", "total size, in bytes"},
1986 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1987 {NULL, "integer time of last access"},
1988 {NULL, "integer time of last modification"},
1989 {NULL, "integer time of last change"},
1990 {"st_atime", "time of last access"},
1991 {"st_mtime", "time of last modification"},
1992 {"st_ctime", "time of last change"},
Larry Hastings6fe20b32012-04-19 15:07:49 -07001993 {"st_atime_ns", "time of last access in nanoseconds"},
1994 {"st_mtime_ns", "time of last modification in nanoseconds"},
1995 {"st_ctime_ns", "time of last change in nanoseconds"},
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001996#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00001997 {"st_blksize", "blocksize for filesystem I/O"},
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_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00002000 {"st_blocks", "number of blocks allocated"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002001#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002002#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00002003 {"st_rdev", "device type (if inode device)"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002004#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002005#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00002006 {"st_flags", "user defined flags for file"},
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002007#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002008#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00002009 {"st_gen", "generation number"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002010#endif
2011#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00002012 {"st_birthtime", "time of creation"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002013#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05002014#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2015 {"st_file_attributes", "Windows file attribute bits"},
2016#endif
jcea6c51d512018-01-28 14:00:08 +01002017#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2018 {"st_fstype", "Type of filesystem"},
2019#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002020#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2021 {"st_reparse_tag", "Windows reparse tag"},
2022#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002023 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002024};
2025
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002026#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Larry Hastings6fe20b32012-04-19 15:07:49 -07002027#define ST_BLKSIZE_IDX 16
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002028#else
Larry Hastings6fe20b32012-04-19 15:07:49 -07002029#define ST_BLKSIZE_IDX 15
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002030#endif
2031
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002032#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002033#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
2034#else
2035#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
2036#endif
2037
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002038#ifdef HAVE_STRUCT_STAT_ST_RDEV
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002039#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
2040#else
2041#define ST_RDEV_IDX ST_BLOCKS_IDX
2042#endif
2043
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002044#ifdef HAVE_STRUCT_STAT_ST_FLAGS
2045#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
2046#else
2047#define ST_FLAGS_IDX ST_RDEV_IDX
2048#endif
2049
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002050#ifdef HAVE_STRUCT_STAT_ST_GEN
Martin v. Löwisf09582e2005-08-14 21:42:34 +00002051#define ST_GEN_IDX (ST_FLAGS_IDX+1)
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002052#else
Martin v. Löwisf09582e2005-08-14 21:42:34 +00002053#define ST_GEN_IDX ST_FLAGS_IDX
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002054#endif
2055
2056#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
2057#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
2058#else
2059#define ST_BIRTHTIME_IDX ST_GEN_IDX
2060#endif
2061
Zachary Ware63f277b2014-06-19 09:46:37 -05002062#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2063#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_IDX+1)
2064#else
2065#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_IDX
2066#endif
2067
jcea6c51d512018-01-28 14:00:08 +01002068#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2069#define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
2070#else
2071#define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
2072#endif
2073
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002074#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2075#define ST_REPARSE_TAG_IDX (ST_FSTYPE_IDX+1)
2076#else
2077#define ST_REPARSE_TAG_IDX ST_FSTYPE_IDX
2078#endif
2079
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002080static PyStructSequence_Desc stat_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002081 "stat_result", /* name */
2082 stat_result__doc__, /* doc */
2083 stat_result_fields,
2084 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002085};
2086
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002087PyDoc_STRVAR(statvfs_result__doc__,
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002088"statvfs_result: Result from statvfs or fstatvfs.\n\n\
2089This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00002090 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
Guido van Rossuma4dc73e2001-10-18 20:53:15 +00002091or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002092\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002093See os.statvfs for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002094
2095static PyStructSequence_Field statvfs_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002096 {"f_bsize", },
2097 {"f_frsize", },
2098 {"f_blocks", },
2099 {"f_bfree", },
2100 {"f_bavail", },
2101 {"f_files", },
2102 {"f_ffree", },
2103 {"f_favail", },
2104 {"f_flag", },
2105 {"f_namemax",},
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +01002106 {"f_fsid", },
Victor Stinner8c62be82010-05-06 00:08:46 +00002107 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002108};
2109
2110static PyStructSequence_Desc statvfs_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002111 "statvfs_result", /* name */
2112 statvfs_result__doc__, /* doc */
2113 statvfs_result_fields,
2114 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002115};
2116
Ross Lagerwall7807c352011-03-17 20:20:30 +02002117#if defined(HAVE_WAITID) && !defined(__APPLE__)
2118PyDoc_STRVAR(waitid_result__doc__,
2119"waitid_result: Result from waitid.\n\n\
2120This object may be accessed either as a tuple of\n\
2121 (si_pid, si_uid, si_signo, si_status, si_code),\n\
2122or via the attributes si_pid, si_uid, and so on.\n\
2123\n\
2124See os.waitid for more information.");
2125
2126static PyStructSequence_Field waitid_result_fields[] = {
2127 {"si_pid", },
2128 {"si_uid", },
2129 {"si_signo", },
2130 {"si_status", },
2131 {"si_code", },
2132 {0}
2133};
2134
2135static PyStructSequence_Desc waitid_result_desc = {
2136 "waitid_result", /* name */
2137 waitid_result__doc__, /* doc */
2138 waitid_result_fields,
2139 5
2140};
Benjamin Petersonbad9c2f2011-08-02 18:42:14 -05002141#endif
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002142static newfunc structseq_new;
2143
2144static PyObject *
2145statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2146{
Victor Stinner8c62be82010-05-06 00:08:46 +00002147 PyStructSequence *result;
2148 int i;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002149
Victor Stinner8c62be82010-05-06 00:08:46 +00002150 result = (PyStructSequence*)structseq_new(type, args, kwds);
2151 if (!result)
2152 return NULL;
2153 /* If we have been initialized from a tuple,
2154 st_?time might be set to None. Initialize it
2155 from the int slots. */
2156 for (i = 7; i <= 9; i++) {
2157 if (result->ob_item[i+3] == Py_None) {
2158 Py_DECREF(Py_None);
2159 Py_INCREF(result->ob_item[i]);
2160 result->ob_item[i+3] = result->ob_item[i];
2161 }
2162 }
2163 return (PyObject*)result;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002164}
2165
Eddie Elizondob3966632019-11-05 07:16:14 -08002166static int
2167_posix_clear(PyObject *module)
2168{
Victor Stinner97f33c32020-05-14 18:05:58 +02002169 _posixstate *state = get_posix_state(module);
2170 Py_CLEAR(state->billion);
2171 Py_CLEAR(state->DirEntryType);
2172 Py_CLEAR(state->ScandirIteratorType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002173#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Victor Stinner97f33c32020-05-14 18:05:58 +02002174 Py_CLEAR(state->SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002175#endif
Victor Stinner97f33c32020-05-14 18:05:58 +02002176 Py_CLEAR(state->StatResultType);
2177 Py_CLEAR(state->StatVFSResultType);
2178 Py_CLEAR(state->TerminalSizeType);
2179 Py_CLEAR(state->TimesResultType);
2180 Py_CLEAR(state->UnameResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002181#if defined(HAVE_WAITID) && !defined(__APPLE__)
Victor Stinner97f33c32020-05-14 18:05:58 +02002182 Py_CLEAR(state->WaitidResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002183#endif
2184#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
Victor Stinner97f33c32020-05-14 18:05:58 +02002185 Py_CLEAR(state->struct_rusage);
Eddie Elizondob3966632019-11-05 07:16:14 -08002186#endif
Victor Stinner97f33c32020-05-14 18:05:58 +02002187 Py_CLEAR(state->st_mode);
Eddie Elizondob3966632019-11-05 07:16:14 -08002188 return 0;
2189}
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002190
Eddie Elizondob3966632019-11-05 07:16:14 -08002191static int
2192_posix_traverse(PyObject *module, visitproc visit, void *arg)
2193{
Victor Stinner97f33c32020-05-14 18:05:58 +02002194 _posixstate *state = get_posix_state(module);
2195 Py_VISIT(state->billion);
2196 Py_VISIT(state->DirEntryType);
2197 Py_VISIT(state->ScandirIteratorType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002198#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Victor Stinner97f33c32020-05-14 18:05:58 +02002199 Py_VISIT(state->SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002200#endif
Victor Stinner97f33c32020-05-14 18:05:58 +02002201 Py_VISIT(state->StatResultType);
2202 Py_VISIT(state->StatVFSResultType);
2203 Py_VISIT(state->TerminalSizeType);
2204 Py_VISIT(state->TimesResultType);
2205 Py_VISIT(state->UnameResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002206#if defined(HAVE_WAITID) && !defined(__APPLE__)
Victor Stinner97f33c32020-05-14 18:05:58 +02002207 Py_VISIT(state->WaitidResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002208#endif
2209#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
Victor Stinner97f33c32020-05-14 18:05:58 +02002210 Py_VISIT(state->struct_rusage);
Eddie Elizondob3966632019-11-05 07:16:14 -08002211#endif
Victor Stinner97f33c32020-05-14 18:05:58 +02002212 Py_VISIT(state->st_mode);
Eddie Elizondob3966632019-11-05 07:16:14 -08002213 return 0;
2214}
2215
2216static void
2217_posix_free(void *module)
2218{
2219 _posix_clear((PyObject *)module);
2220}
Larry Hastings6fe20b32012-04-19 15:07:49 -07002221
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002222static void
Victor Stinner1c2fa782020-05-10 11:05:29 +02002223fill_time(PyObject *module, PyObject *v, int index, time_t sec, unsigned long nsec)
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002224{
Larry Hastings6fe20b32012-04-19 15:07:49 -07002225 PyObject *s = _PyLong_FromTime_t(sec);
2226 PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
2227 PyObject *s_in_ns = NULL;
2228 PyObject *ns_total = NULL;
2229 PyObject *float_s = NULL;
2230
2231 if (!(s && ns_fractional))
2232 goto exit;
2233
Victor Stinner1c2fa782020-05-10 11:05:29 +02002234 s_in_ns = PyNumber_Multiply(s, get_posix_state(module)->billion);
Larry Hastings6fe20b32012-04-19 15:07:49 -07002235 if (!s_in_ns)
2236 goto exit;
2237
2238 ns_total = PyNumber_Add(s_in_ns, ns_fractional);
2239 if (!ns_total)
2240 goto exit;
2241
Victor Stinner01b5aab2017-10-24 02:02:00 -07002242 float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
2243 if (!float_s) {
2244 goto exit;
Larry Hastings6fe20b32012-04-19 15:07:49 -07002245 }
2246
2247 PyStructSequence_SET_ITEM(v, index, s);
2248 PyStructSequence_SET_ITEM(v, index+3, float_s);
2249 PyStructSequence_SET_ITEM(v, index+6, ns_total);
2250 s = NULL;
2251 float_s = NULL;
2252 ns_total = NULL;
2253exit:
2254 Py_XDECREF(s);
2255 Py_XDECREF(ns_fractional);
2256 Py_XDECREF(s_in_ns);
2257 Py_XDECREF(ns_total);
2258 Py_XDECREF(float_s);
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002259}
2260
Tim Peters5aa91602002-01-30 05:46:57 +00002261/* pack a system stat C structure into the Python stat tuple
Fred Drake699f3522000-06-29 21:12:41 +00002262 (used by posix_stat() and posix_fstat()) */
2263static PyObject*
Victor Stinner1c2fa782020-05-10 11:05:29 +02002264_pystat_fromstructstat(PyObject *module, STRUCT_STAT *st)
Fred Drake699f3522000-06-29 21:12:41 +00002265{
Victor Stinner8c62be82010-05-06 00:08:46 +00002266 unsigned long ansec, mnsec, cnsec;
Victor Stinner1c2fa782020-05-10 11:05:29 +02002267 PyObject *StatResultType = get_posix_state(module)->StatResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -08002268 PyObject *v = PyStructSequence_New((PyTypeObject *)StatResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +00002269 if (v == NULL)
2270 return NULL;
Fred Drake699f3522000-06-29 21:12:41 +00002271
Victor Stinner8c62be82010-05-06 00:08:46 +00002272 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode));
Victor Stinner0f6d7332017-03-09 17:34:28 +01002273 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(st->st_ino));
xdegaye50e86032017-05-22 11:15:08 +02002274 PyStructSequence_SET_ITEM(v, 1, PyLong_FromUnsignedLongLong(st->st_ino));
Serhiy Storchaka404fa922013-01-02 18:22:23 +02002275#ifdef MS_WINDOWS
2276 PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002277#else
Serhiy Storchakab2653b32015-01-18 11:12:11 +02002278 PyStructSequence_SET_ITEM(v, 2, _PyLong_FromDev(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002279#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002280 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02002281#if defined(MS_WINDOWS)
2282 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong(0));
2283 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong(0));
2284#else
2285 PyStructSequence_SET_ITEM(v, 4, _PyLong_FromUid(st->st_uid));
2286 PyStructSequence_SET_ITEM(v, 5, _PyLong_FromGid(st->st_gid));
2287#endif
xdegaye50e86032017-05-22 11:15:08 +02002288 Py_BUILD_ASSERT(sizeof(long long) >= sizeof(st->st_size));
2289 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLongLong(st->st_size));
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002290
Martin v. Löwis14694662006-02-03 12:54:16 +00002291#if defined(HAVE_STAT_TV_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002292 ansec = st->st_atim.tv_nsec;
2293 mnsec = st->st_mtim.tv_nsec;
2294 cnsec = st->st_ctim.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002295#elif defined(HAVE_STAT_TV_NSEC2)
Victor Stinner8c62be82010-05-06 00:08:46 +00002296 ansec = st->st_atimespec.tv_nsec;
2297 mnsec = st->st_mtimespec.tv_nsec;
2298 cnsec = st->st_ctimespec.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002299#elif defined(HAVE_STAT_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002300 ansec = st->st_atime_nsec;
2301 mnsec = st->st_mtime_nsec;
2302 cnsec = st->st_ctime_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002303#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002304 ansec = mnsec = cnsec = 0;
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002305#endif
Victor Stinner1c2fa782020-05-10 11:05:29 +02002306 fill_time(module, v, 7, st->st_atime, ansec);
2307 fill_time(module, v, 8, st->st_mtime, mnsec);
2308 fill_time(module, v, 9, st->st_ctime, cnsec);
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002309
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002310#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00002311 PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
2312 PyLong_FromLong((long)st->st_blksize));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002313#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002314#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00002315 PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
2316 PyLong_FromLong((long)st->st_blocks));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002317#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002318#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00002319 PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
2320 PyLong_FromLong((long)st->st_rdev));
Fred Drake699f3522000-06-29 21:12:41 +00002321#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002322#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00002323 PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
2324 PyLong_FromLong((long)st->st_gen));
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002325#endif
2326#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00002327 {
Victor Stinner4195b5c2012-02-08 23:03:19 +01002328 PyObject *val;
2329 unsigned long bsec,bnsec;
2330 bsec = (long)st->st_birthtime;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002331#ifdef HAVE_STAT_TV_NSEC2
Victor Stinner4195b5c2012-02-08 23:03:19 +01002332 bnsec = st->st_birthtimespec.tv_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002333#else
Victor Stinner4195b5c2012-02-08 23:03:19 +01002334 bnsec = 0;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002335#endif
Victor Stinner01b5aab2017-10-24 02:02:00 -07002336 val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
Victor Stinner4195b5c2012-02-08 23:03:19 +01002337 PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
2338 val);
Victor Stinner8c62be82010-05-06 00:08:46 +00002339 }
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002340#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002341#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00002342 PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
2343 PyLong_FromLong((long)st->st_flags));
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002344#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05002345#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2346 PyStructSequence_SET_ITEM(v, ST_FILE_ATTRIBUTES_IDX,
2347 PyLong_FromUnsignedLong(st->st_file_attributes));
2348#endif
jcea6c51d512018-01-28 14:00:08 +01002349#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2350 PyStructSequence_SET_ITEM(v, ST_FSTYPE_IDX,
2351 PyUnicode_FromString(st->st_fstype));
2352#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002353#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2354 PyStructSequence_SET_ITEM(v, ST_REPARSE_TAG_IDX,
2355 PyLong_FromUnsignedLong(st->st_reparse_tag));
2356#endif
Fred Drake699f3522000-06-29 21:12:41 +00002357
Victor Stinner8c62be82010-05-06 00:08:46 +00002358 if (PyErr_Occurred()) {
2359 Py_DECREF(v);
2360 return NULL;
2361 }
Fred Drake699f3522000-06-29 21:12:41 +00002362
Victor Stinner8c62be82010-05-06 00:08:46 +00002363 return v;
Fred Drake699f3522000-06-29 21:12:41 +00002364}
2365
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002366/* POSIX methods */
2367
Guido van Rossum94f6f721999-01-06 18:42:14 +00002368
2369static PyObject *
Victor Stinner1c2fa782020-05-10 11:05:29 +02002370posix_do_stat(PyObject *module, const char *function_name, path_t *path,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002371 int dir_fd, int follow_symlinks)
Guido van Rossum94f6f721999-01-06 18:42:14 +00002372{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002373 STRUCT_STAT st;
2374 int result;
2375
2376#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
2377 if (follow_symlinks_specified(function_name, follow_symlinks))
2378 return NULL;
2379#endif
2380
2381 if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
2382 dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
2383 fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
2384 return NULL;
2385
2386 Py_BEGIN_ALLOW_THREADS
2387 if (path->fd != -1)
2388 result = FSTAT(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002389#ifdef MS_WINDOWS
Steve Dower513d7472016-09-08 10:41:50 -07002390 else if (follow_symlinks)
Steve Dowercc16be82016-09-08 10:35:16 -07002391 result = win32_stat(path->wide, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002392 else
Steve Dowercc16be82016-09-08 10:35:16 -07002393 result = win32_lstat(path->wide, &st);
2394#else
2395 else
2396#if defined(HAVE_LSTAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002397 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
2398 result = LSTAT(path->narrow, &st);
2399 else
Steve Dowercc16be82016-09-08 10:35:16 -07002400#endif /* HAVE_LSTAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002401#ifdef HAVE_FSTATAT
2402 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks)
2403 result = fstatat(dir_fd, path->narrow, &st,
2404 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2405 else
Steve Dowercc16be82016-09-08 10:35:16 -07002406#endif /* HAVE_FSTATAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002407 result = STAT(path->narrow, &st);
Steve Dowercc16be82016-09-08 10:35:16 -07002408#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002409 Py_END_ALLOW_THREADS
2410
Victor Stinner292c8352012-10-30 02:17:38 +01002411 if (result != 0) {
2412 return path_error(path);
2413 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07002414
Victor Stinner1c2fa782020-05-10 11:05:29 +02002415 return _pystat_fromstructstat(module, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002416}
2417
Larry Hastings2f936352014-08-05 14:04:04 +10002418/*[python input]
2419
2420for s in """
2421
2422FACCESSAT
2423FCHMODAT
2424FCHOWNAT
2425FSTATAT
2426LINKAT
2427MKDIRAT
2428MKFIFOAT
2429MKNODAT
2430OPENAT
2431READLINKAT
2432SYMLINKAT
2433UNLINKAT
2434
2435""".strip().split():
2436 s = s.strip()
2437 print("""
2438#ifdef HAVE_{s}
2439 #define {s}_DIR_FD_CONVERTER dir_fd_converter
Larry Hastings31826802013-10-19 00:09:25 -07002440#else
Larry Hastings2f936352014-08-05 14:04:04 +10002441 #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings31826802013-10-19 00:09:25 -07002442#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002443""".rstrip().format(s=s))
2444
2445for s in """
2446
2447FCHDIR
2448FCHMOD
2449FCHOWN
2450FDOPENDIR
2451FEXECVE
2452FPATHCONF
2453FSTATVFS
2454FTRUNCATE
2455
2456""".strip().split():
2457 s = s.strip()
2458 print("""
2459#ifdef HAVE_{s}
2460 #define PATH_HAVE_{s} 1
2461#else
2462 #define PATH_HAVE_{s} 0
2463#endif
2464
2465""".rstrip().format(s=s))
2466[python start generated code]*/
2467
2468#ifdef HAVE_FACCESSAT
2469 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
2470#else
2471 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
2472#endif
2473
2474#ifdef HAVE_FCHMODAT
2475 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
2476#else
2477 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
2478#endif
2479
2480#ifdef HAVE_FCHOWNAT
2481 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
2482#else
2483 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
2484#endif
2485
2486#ifdef HAVE_FSTATAT
2487 #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
2488#else
2489 #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
2490#endif
2491
2492#ifdef HAVE_LINKAT
2493 #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
2494#else
2495 #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2496#endif
2497
2498#ifdef HAVE_MKDIRAT
2499 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
2500#else
2501 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
2502#endif
2503
2504#ifdef HAVE_MKFIFOAT
2505 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
2506#else
2507 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
2508#endif
2509
2510#ifdef HAVE_MKNODAT
2511 #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
2512#else
2513 #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
2514#endif
2515
2516#ifdef HAVE_OPENAT
2517 #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
2518#else
2519 #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
2520#endif
2521
2522#ifdef HAVE_READLINKAT
2523 #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
2524#else
2525 #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2526#endif
2527
2528#ifdef HAVE_SYMLINKAT
2529 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
2530#else
2531 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2532#endif
2533
2534#ifdef HAVE_UNLINKAT
2535 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
2536#else
2537 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2538#endif
2539
2540#ifdef HAVE_FCHDIR
2541 #define PATH_HAVE_FCHDIR 1
2542#else
2543 #define PATH_HAVE_FCHDIR 0
2544#endif
2545
2546#ifdef HAVE_FCHMOD
2547 #define PATH_HAVE_FCHMOD 1
2548#else
2549 #define PATH_HAVE_FCHMOD 0
2550#endif
2551
2552#ifdef HAVE_FCHOWN
2553 #define PATH_HAVE_FCHOWN 1
2554#else
2555 #define PATH_HAVE_FCHOWN 0
2556#endif
2557
2558#ifdef HAVE_FDOPENDIR
2559 #define PATH_HAVE_FDOPENDIR 1
2560#else
2561 #define PATH_HAVE_FDOPENDIR 0
2562#endif
2563
2564#ifdef HAVE_FEXECVE
2565 #define PATH_HAVE_FEXECVE 1
2566#else
2567 #define PATH_HAVE_FEXECVE 0
2568#endif
2569
2570#ifdef HAVE_FPATHCONF
2571 #define PATH_HAVE_FPATHCONF 1
2572#else
2573 #define PATH_HAVE_FPATHCONF 0
2574#endif
2575
2576#ifdef HAVE_FSTATVFS
2577 #define PATH_HAVE_FSTATVFS 1
2578#else
2579 #define PATH_HAVE_FSTATVFS 0
2580#endif
2581
2582#ifdef HAVE_FTRUNCATE
2583 #define PATH_HAVE_FTRUNCATE 1
2584#else
2585 #define PATH_HAVE_FTRUNCATE 0
2586#endif
2587/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
Larry Hastings31826802013-10-19 00:09:25 -07002588
Steve Dowerfe0a41a2015-03-20 19:50:46 -07002589#ifdef MS_WINDOWS
2590 #undef PATH_HAVE_FTRUNCATE
2591 #define PATH_HAVE_FTRUNCATE 1
2592#endif
Larry Hastings31826802013-10-19 00:09:25 -07002593
Larry Hastings61272b72014-01-07 12:41:53 -08002594/*[python input]
Larry Hastings31826802013-10-19 00:09:25 -07002595
2596class path_t_converter(CConverter):
2597
2598 type = "path_t"
2599 impl_by_reference = True
2600 parse_by_reference = True
2601
2602 converter = 'path_converter'
2603
2604 def converter_init(self, *, allow_fd=False, nullable=False):
Larry Hastings31826802013-10-19 00:09:25 -07002605 # right now path_t doesn't support default values.
2606 # to support a default value, you'll need to override initialize().
Larry Hastings2f936352014-08-05 14:04:04 +10002607 if self.default not in (unspecified, None):
Larry Hastings7726ac92014-01-31 22:03:12 -08002608 fail("Can't specify a default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002609
Larry Hastings2f936352014-08-05 14:04:04 +10002610 if self.c_default not in (None, 'Py_None'):
2611 raise RuntimeError("Can't specify a c_default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002612
2613 self.nullable = nullable
2614 self.allow_fd = allow_fd
2615
Larry Hastings7726ac92014-01-31 22:03:12 -08002616 def pre_render(self):
2617 def strify(value):
Larry Hastings2f936352014-08-05 14:04:04 +10002618 if isinstance(value, str):
2619 return value
Larry Hastings7726ac92014-01-31 22:03:12 -08002620 return str(int(bool(value)))
2621
2622 # add self.py_name here when merging with posixmodule conversion
Larry Hastings2f936352014-08-05 14:04:04 +10002623 self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
Larry Hastings31826802013-10-19 00:09:25 -07002624 self.function.name,
Larry Hastings2f936352014-08-05 14:04:04 +10002625 self.name,
Larry Hastings7726ac92014-01-31 22:03:12 -08002626 strify(self.nullable),
2627 strify(self.allow_fd),
Larry Hastings31826802013-10-19 00:09:25 -07002628 )
2629
2630 def cleanup(self):
2631 return "path_cleanup(&" + self.name + ");\n"
2632
2633
2634class dir_fd_converter(CConverter):
2635 type = 'int'
Larry Hastings31826802013-10-19 00:09:25 -07002636
Larry Hastings2f936352014-08-05 14:04:04 +10002637 def converter_init(self, requires=None):
Larry Hastings31826802013-10-19 00:09:25 -07002638 if self.default in (unspecified, None):
2639 self.c_default = 'DEFAULT_DIR_FD'
Larry Hastings2f936352014-08-05 14:04:04 +10002640 if isinstance(requires, str):
2641 self.converter = requires.upper() + '_DIR_FD_CONVERTER'
2642 else:
2643 self.converter = 'dir_fd_converter'
Larry Hastings31826802013-10-19 00:09:25 -07002644
Larry Hastings2f936352014-08-05 14:04:04 +10002645class fildes_converter(CConverter):
2646 type = 'int'
2647 converter = 'fildes_converter'
2648
2649class uid_t_converter(CConverter):
2650 type = "uid_t"
2651 converter = '_Py_Uid_Converter'
2652
2653class gid_t_converter(CConverter):
2654 type = "gid_t"
2655 converter = '_Py_Gid_Converter'
2656
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02002657class dev_t_converter(CConverter):
2658 type = 'dev_t'
2659 converter = '_Py_Dev_Converter'
2660
2661class dev_t_return_converter(unsigned_long_return_converter):
2662 type = 'dev_t'
2663 conversion_fn = '_PyLong_FromDev'
2664 unsigned_cast = '(dev_t)'
2665
Larry Hastings2f936352014-08-05 14:04:04 +10002666class FSConverter_converter(CConverter):
2667 type = 'PyObject *'
2668 converter = 'PyUnicode_FSConverter'
2669 def converter_init(self):
2670 if self.default is not unspecified:
2671 fail("FSConverter_converter does not support default values")
2672 self.c_default = 'NULL'
2673
2674 def cleanup(self):
2675 return "Py_XDECREF(" + self.name + ");\n"
2676
2677class pid_t_converter(CConverter):
2678 type = 'pid_t'
2679 format_unit = '" _Py_PARSE_PID "'
2680
2681class idtype_t_converter(int_converter):
2682 type = 'idtype_t'
2683
2684class id_t_converter(CConverter):
2685 type = 'id_t'
2686 format_unit = '" _Py_PARSE_PID "'
2687
Benjamin Petersonca470632016-09-06 13:47:26 -07002688class intptr_t_converter(CConverter):
2689 type = 'intptr_t'
Larry Hastings2f936352014-08-05 14:04:04 +10002690 format_unit = '" _Py_PARSE_INTPTR "'
2691
2692class Py_off_t_converter(CConverter):
2693 type = 'Py_off_t'
2694 converter = 'Py_off_t_converter'
2695
2696class Py_off_t_return_converter(long_return_converter):
2697 type = 'Py_off_t'
2698 conversion_fn = 'PyLong_FromPy_off_t'
2699
2700class path_confname_converter(CConverter):
2701 type="int"
2702 converter="conv_path_confname"
2703
2704class confstr_confname_converter(path_confname_converter):
2705 converter='conv_confstr_confname'
2706
2707class sysconf_confname_converter(path_confname_converter):
2708 converter="conv_sysconf_confname"
2709
Larry Hastings61272b72014-01-07 12:41:53 -08002710[python start generated code]*/
Victor Stinner1c2fa782020-05-10 11:05:29 +02002711/*[python end generated code: output=da39a3ee5e6b4b0d input=f1c8ae8d744f6c8b]*/
Larry Hastings31826802013-10-19 00:09:25 -07002712
Larry Hastings61272b72014-01-07 12:41:53 -08002713/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002714
Larry Hastings2a727912014-01-16 11:32:01 -08002715os.stat
Larry Hastings31826802013-10-19 00:09:25 -07002716
2717 path : path_t(allow_fd=True)
BNMetricsb9427072018-11-02 15:20:19 +00002718 Path to be examined; can be string, bytes, a path-like object or
Xiang Zhang4459e002017-01-22 13:04:17 +08002719 open-file-descriptor int.
Larry Hastings31826802013-10-19 00:09:25 -07002720
2721 *
2722
Larry Hastings2f936352014-08-05 14:04:04 +10002723 dir_fd : dir_fd(requires='fstatat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002724 If not None, it should be a file descriptor open to a directory,
2725 and path should be a relative string; path will then be relative to
2726 that directory.
2727
2728 follow_symlinks: bool = True
2729 If False, and the last element of the path is a symbolic link,
2730 stat will examine the symbolic link itself instead of the file
2731 the link points to.
2732
2733Perform a stat system call on the given path.
2734
2735dir_fd and follow_symlinks may not be implemented
2736 on your platform. If they are unavailable, using them will raise a
2737 NotImplementedError.
2738
2739It's an error to use dir_fd or follow_symlinks when specifying path as
2740 an open file descriptor.
2741
Larry Hastings61272b72014-01-07 12:41:53 -08002742[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002743
Larry Hastings31826802013-10-19 00:09:25 -07002744static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002745os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002746/*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
Larry Hastings31826802013-10-19 00:09:25 -07002747{
Victor Stinner1c2fa782020-05-10 11:05:29 +02002748 return posix_do_stat(module, "stat", path, dir_fd, follow_symlinks);
Larry Hastings31826802013-10-19 00:09:25 -07002749}
2750
Larry Hastings2f936352014-08-05 14:04:04 +10002751
2752/*[clinic input]
2753os.lstat
2754
2755 path : path_t
2756
2757 *
2758
2759 dir_fd : dir_fd(requires='fstatat') = None
2760
2761Perform a stat system call on the given path, without following symbolic links.
2762
2763Like stat(), but do not follow symbolic links.
2764Equivalent to stat(path, follow_symlinks=False).
2765[clinic start generated code]*/
2766
Larry Hastings2f936352014-08-05 14:04:04 +10002767static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002768os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
2769/*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002770{
2771 int follow_symlinks = 0;
Victor Stinner1c2fa782020-05-10 11:05:29 +02002772 return posix_do_stat(module, "lstat", path, dir_fd, follow_symlinks);
Larry Hastings2f936352014-08-05 14:04:04 +10002773}
Larry Hastings31826802013-10-19 00:09:25 -07002774
Larry Hastings2f936352014-08-05 14:04:04 +10002775
Larry Hastings61272b72014-01-07 12:41:53 -08002776/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10002777os.access -> bool
Larry Hastings31826802013-10-19 00:09:25 -07002778
Benjamin Peterson768f3b42016-09-05 15:29:33 -07002779 path: path_t
BNMetricsb9427072018-11-02 15:20:19 +00002780 Path to be tested; can be string, bytes, or a path-like object.
Larry Hastings31826802013-10-19 00:09:25 -07002781
2782 mode: int
2783 Operating-system mode bitfield. Can be F_OK to test existence,
2784 or the inclusive-OR of R_OK, W_OK, and X_OK.
2785
2786 *
2787
Larry Hastings2f936352014-08-05 14:04:04 +10002788 dir_fd : dir_fd(requires='faccessat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002789 If not None, it should be a file descriptor open to a directory,
2790 and path should be relative; path will then be relative to that
2791 directory.
2792
2793 effective_ids: bool = False
2794 If True, access will use the effective uid/gid instead of
2795 the real uid/gid.
2796
2797 follow_symlinks: bool = True
2798 If False, and the last element of the path is a symbolic link,
2799 access will examine the symbolic link itself instead of the file
2800 the link points to.
2801
2802Use the real uid/gid to test for access to a path.
2803
2804{parameters}
2805dir_fd, effective_ids, and follow_symlinks may not be implemented
2806 on your platform. If they are unavailable, using them will raise a
2807 NotImplementedError.
2808
2809Note that most operations will use the effective uid/gid, therefore this
2810 routine can be used in a suid/sgid environment to test if the invoking user
2811 has the specified access to the path.
2812
Larry Hastings61272b72014-01-07 12:41:53 -08002813[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002814
Larry Hastings2f936352014-08-05 14:04:04 +10002815static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002816os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002817 int effective_ids, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002818/*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
Larry Hastings31826802013-10-19 00:09:25 -07002819{
Larry Hastings2f936352014-08-05 14:04:04 +10002820 int return_value;
Victor Stinner8c62be82010-05-06 00:08:46 +00002821
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002822#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002823 DWORD attr;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002824#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07002825 int result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002826#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07002827
Larry Hastings9cf065c2012-06-22 16:30:09 -07002828#ifndef HAVE_FACCESSAT
2829 if (follow_symlinks_specified("access", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002830 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002831
2832 if (effective_ids) {
2833 argument_unavailable_error("access", "effective_ids");
Larry Hastings2f936352014-08-05 14:04:04 +10002834 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002835 }
2836#endif
2837
2838#ifdef MS_WINDOWS
2839 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002840 attr = GetFileAttributesW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002841 Py_END_ALLOW_THREADS
2842
2843 /*
Georg Brandlf7875592012-06-24 13:58:31 +02002844 * Access is possible if
Larry Hastings9cf065c2012-06-22 16:30:09 -07002845 * * we didn't get a -1, and
2846 * * write access wasn't requested,
2847 * * or the file isn't read-only,
2848 * * or it's a directory.
2849 * (Directories cannot be read-only on Windows.)
2850 */
Larry Hastings2f936352014-08-05 14:04:04 +10002851 return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
Georg Brandl5bb7aa92012-06-23 12:48:40 +02002852 (!(mode & 2) ||
Larry Hastings9cf065c2012-06-22 16:30:09 -07002853 !(attr & FILE_ATTRIBUTE_READONLY) ||
Larry Hastings2f936352014-08-05 14:04:04 +10002854 (attr & FILE_ATTRIBUTE_DIRECTORY));
Larry Hastings9cf065c2012-06-22 16:30:09 -07002855#else
2856
2857 Py_BEGIN_ALLOW_THREADS
2858#ifdef HAVE_FACCESSAT
2859 if ((dir_fd != DEFAULT_DIR_FD) ||
2860 effective_ids ||
2861 !follow_symlinks) {
2862 int flags = 0;
2863 if (!follow_symlinks)
2864 flags |= AT_SYMLINK_NOFOLLOW;
2865 if (effective_ids)
2866 flags |= AT_EACCESS;
Larry Hastings31826802013-10-19 00:09:25 -07002867 result = faccessat(dir_fd, path->narrow, mode, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002868 }
2869 else
2870#endif
Larry Hastings31826802013-10-19 00:09:25 -07002871 result = access(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002872 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10002873 return_value = !result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002874#endif
2875
Larry Hastings9cf065c2012-06-22 16:30:09 -07002876 return return_value;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002877}
2878
Guido van Rossumd371ff11999-01-25 16:12:23 +00002879#ifndef F_OK
2880#define F_OK 0
2881#endif
2882#ifndef R_OK
2883#define R_OK 4
2884#endif
2885#ifndef W_OK
2886#define W_OK 2
2887#endif
2888#ifndef X_OK
2889#define X_OK 1
2890#endif
2891
Larry Hastings31826802013-10-19 00:09:25 -07002892
Guido van Rossumd371ff11999-01-25 16:12:23 +00002893#ifdef HAVE_TTYNAME
Larry Hastings61272b72014-01-07 12:41:53 -08002894/*[clinic input]
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002895os.ttyname
Larry Hastings31826802013-10-19 00:09:25 -07002896
2897 fd: int
2898 Integer file descriptor handle.
2899
2900 /
2901
2902Return the name of the terminal device connected to 'fd'.
Larry Hastings61272b72014-01-07 12:41:53 -08002903[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002904
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002905static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002906os_ttyname_impl(PyObject *module, int fd)
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002907/*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
Larry Hastings31826802013-10-19 00:09:25 -07002908{
Guido van Rossum94f6f721999-01-06 18:42:14 +00002909
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002910 long size = sysconf(_SC_TTY_NAME_MAX);
2911 if (size == -1) {
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002912 return posix_error();
2913 }
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002914 char *buffer = (char *)PyMem_RawMalloc(size);
2915 if (buffer == NULL) {
2916 return PyErr_NoMemory();
2917 }
2918 int ret = ttyname_r(fd, buffer, size);
2919 if (ret != 0) {
2920 PyMem_RawFree(buffer);
2921 errno = ret;
2922 return posix_error();
2923 }
2924 PyObject *res = PyUnicode_DecodeFSDefault(buffer);
2925 PyMem_RawFree(buffer);
2926 return res;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002927}
Guido van Rossumd371ff11999-01-25 16:12:23 +00002928#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +00002929
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002930#ifdef HAVE_CTERMID
Larry Hastings2f936352014-08-05 14:04:04 +10002931/*[clinic input]
2932os.ctermid
2933
2934Return the name of the controlling terminal for this process.
2935[clinic start generated code]*/
2936
Larry Hastings2f936352014-08-05 14:04:04 +10002937static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002938os_ctermid_impl(PyObject *module)
2939/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002940{
Victor Stinner8c62be82010-05-06 00:08:46 +00002941 char *ret;
2942 char buffer[L_ctermid];
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002943
Greg Wardb48bc172000-03-01 21:51:56 +00002944#ifdef USE_CTERMID_R
Victor Stinner8c62be82010-05-06 00:08:46 +00002945 ret = ctermid_r(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002946#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002947 ret = ctermid(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002948#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002949 if (ret == NULL)
2950 return posix_error();
Victor Stinner5fe6de82010-08-15 09:12:51 +00002951 return PyUnicode_DecodeFSDefault(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002952}
Larry Hastings2f936352014-08-05 14:04:04 +10002953#endif /* HAVE_CTERMID */
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002954
Larry Hastings2f936352014-08-05 14:04:04 +10002955
2956/*[clinic input]
2957os.chdir
2958
2959 path: path_t(allow_fd='PATH_HAVE_FCHDIR')
2960
2961Change the current working directory to the specified path.
2962
2963path may always be specified as a string.
2964On some platforms, path may also be specified as an open file descriptor.
2965 If this functionality is unavailable, using it raises an exception.
2966[clinic start generated code]*/
2967
Larry Hastings2f936352014-08-05 14:04:04 +10002968static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002969os_chdir_impl(PyObject *module, path_t *path)
2970/*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002971{
2972 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002973
Saiyang Gou7514f4f2020-02-12 23:47:42 -08002974 if (PySys_Audit("os.chdir", "(O)", path->object) < 0) {
2975 return NULL;
2976 }
2977
Larry Hastings9cf065c2012-06-22 16:30:09 -07002978 Py_BEGIN_ALLOW_THREADS
2979#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07002980 /* on unix, success = 0, on windows, success = !0 */
2981 result = !win32_wchdir(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002982#else
2983#ifdef HAVE_FCHDIR
Larry Hastings2f936352014-08-05 14:04:04 +10002984 if (path->fd != -1)
2985 result = fchdir(path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002986 else
2987#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002988 result = chdir(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002989#endif
2990 Py_END_ALLOW_THREADS
2991
2992 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002993 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002994 }
2995
Larry Hastings2f936352014-08-05 14:04:04 +10002996 Py_RETURN_NONE;
2997}
2998
2999
3000#ifdef HAVE_FCHDIR
3001/*[clinic input]
3002os.fchdir
3003
3004 fd: fildes
3005
3006Change to the directory of the given file descriptor.
3007
3008fd must be opened on a directory, not a file.
3009Equivalent to os.chdir(fd).
3010
3011[clinic start generated code]*/
3012
Fred Drake4d1e64b2002-04-15 19:40:07 +00003013static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003014os_fchdir_impl(PyObject *module, int fd)
3015/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
Fred Drake4d1e64b2002-04-15 19:40:07 +00003016{
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003017 if (PySys_Audit("os.chdir", "(i)", fd) < 0) {
3018 return NULL;
3019 }
Larry Hastings2f936352014-08-05 14:04:04 +10003020 return posix_fildes_fd(fd, fchdir);
Fred Drake4d1e64b2002-04-15 19:40:07 +00003021}
3022#endif /* HAVE_FCHDIR */
3023
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003024
Larry Hastings2f936352014-08-05 14:04:04 +10003025/*[clinic input]
3026os.chmod
3027
3028 path: path_t(allow_fd='PATH_HAVE_FCHMOD')
BNMetricsb9427072018-11-02 15:20:19 +00003029 Path to be modified. May always be specified as a str, bytes, or a path-like object.
Larry Hastings2f936352014-08-05 14:04:04 +10003030 On some platforms, path may also be specified as an open file descriptor.
3031 If this functionality is unavailable, using it raises an exception.
3032
3033 mode: int
3034 Operating-system mode bitfield.
3035
3036 *
3037
3038 dir_fd : dir_fd(requires='fchmodat') = None
3039 If not None, it should be a file descriptor open to a directory,
3040 and path should be relative; path will then be relative to that
3041 directory.
3042
3043 follow_symlinks: bool = True
3044 If False, and the last element of the path is a symbolic link,
3045 chmod will modify the symbolic link itself instead of the file
3046 the link points to.
3047
3048Change the access permissions of a file.
3049
3050It is an error to use dir_fd or follow_symlinks when specifying path as
3051 an open file descriptor.
3052dir_fd and follow_symlinks may not be implemented on your platform.
3053 If they are unavailable, using them will raise a NotImplementedError.
3054
3055[clinic start generated code]*/
3056
Larry Hastings2f936352014-08-05 14:04:04 +10003057static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003058os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003059 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003060/*[clinic end generated code: output=5cf6a94915cc7bff input=989081551c00293b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003061{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003062 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003063
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003064#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003065 DWORD attr;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003066#endif
Hirokazu Yamamoto892a37a2009-06-28 11:07:03 +00003067
Larry Hastings9cf065c2012-06-22 16:30:09 -07003068#ifdef HAVE_FCHMODAT
3069 int fchmodat_nofollow_unsupported = 0;
3070#endif
3071
Larry Hastings9cf065c2012-06-22 16:30:09 -07003072#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
3073 if (follow_symlinks_specified("chmod", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003074 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003075#endif
3076
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003077 if (PySys_Audit("os.chmod", "Oii", path->object, mode,
3078 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
3079 return NULL;
3080 }
3081
Larry Hastings9cf065c2012-06-22 16:30:09 -07003082#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003083 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003084 attr = GetFileAttributesW(path->wide);
Tim Golden23005082013-10-25 11:22:37 +01003085 if (attr == INVALID_FILE_ATTRIBUTES)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003086 result = 0;
3087 else {
3088 if (mode & _S_IWRITE)
Victor Stinner8c62be82010-05-06 00:08:46 +00003089 attr &= ~FILE_ATTRIBUTE_READONLY;
3090 else
3091 attr |= FILE_ATTRIBUTE_READONLY;
Steve Dowercc16be82016-09-08 10:35:16 -07003092 result = SetFileAttributesW(path->wide, attr);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003093 }
3094 Py_END_ALLOW_THREADS
3095
3096 if (!result) {
Larry Hastings2f936352014-08-05 14:04:04 +10003097 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003098 }
3099#else /* MS_WINDOWS */
3100 Py_BEGIN_ALLOW_THREADS
3101#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003102 if (path->fd != -1)
3103 result = fchmod(path->fd, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003104 else
3105#endif
3106#ifdef HAVE_LCHMOD
3107 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003108 result = lchmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003109 else
3110#endif
3111#ifdef HAVE_FCHMODAT
3112 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
3113 /*
3114 * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
3115 * The documentation specifically shows how to use it,
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003116 * and then says it isn't implemented yet.
3117 * (true on linux with glibc 2.15, and openindiana 3.x)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003118 *
3119 * Once it is supported, os.chmod will automatically
3120 * support dir_fd and follow_symlinks=False. (Hopefully.)
3121 * Until then, we need to be careful what exception we raise.
3122 */
Larry Hastings2f936352014-08-05 14:04:04 +10003123 result = fchmodat(dir_fd, path->narrow, mode,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003124 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3125 /*
3126 * But wait! We can't throw the exception without allowing threads,
3127 * and we can't do that in this nested scope. (Macro trickery, sigh.)
3128 */
3129 fchmodat_nofollow_unsupported =
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003130 result &&
3131 ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
3132 !follow_symlinks;
Victor Stinner8c62be82010-05-06 00:08:46 +00003133 }
3134 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00003135#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003136 result = chmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003137 Py_END_ALLOW_THREADS
3138
3139 if (result) {
3140#ifdef HAVE_FCHMODAT
3141 if (fchmodat_nofollow_unsupported) {
3142 if (dir_fd != DEFAULT_DIR_FD)
3143 dir_fd_and_follow_symlinks_invalid("chmod",
3144 dir_fd, follow_symlinks);
3145 else
3146 follow_symlinks_specified("chmod", follow_symlinks);
Anthony Sottile233ef242017-12-14 08:57:55 -08003147 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003148 }
3149 else
3150#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003151 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003152 }
3153#endif
3154
Larry Hastings2f936352014-08-05 14:04:04 +10003155 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003156}
3157
Larry Hastings9cf065c2012-06-22 16:30:09 -07003158
Christian Heimes4e30a842007-11-30 22:12:06 +00003159#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003160/*[clinic input]
3161os.fchmod
3162
3163 fd: int
3164 mode: int
3165
3166Change the access permissions of the file given by file descriptor fd.
3167
3168Equivalent to os.chmod(fd, mode).
3169[clinic start generated code]*/
3170
Larry Hastings2f936352014-08-05 14:04:04 +10003171static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003172os_fchmod_impl(PyObject *module, int fd, int mode)
3173/*[clinic end generated code: output=afd9bc05b4e426b3 input=8ab11975ca01ee5b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003174{
3175 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003176 int async_err = 0;
3177
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003178 if (PySys_Audit("os.chmod", "iii", fd, mode, -1) < 0) {
3179 return NULL;
3180 }
3181
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003182 do {
3183 Py_BEGIN_ALLOW_THREADS
3184 res = fchmod(fd, mode);
3185 Py_END_ALLOW_THREADS
3186 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3187 if (res != 0)
3188 return (!async_err) ? posix_error() : NULL;
3189
Victor Stinner8c62be82010-05-06 00:08:46 +00003190 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003191}
3192#endif /* HAVE_FCHMOD */
3193
Larry Hastings2f936352014-08-05 14:04:04 +10003194
Christian Heimes4e30a842007-11-30 22:12:06 +00003195#ifdef HAVE_LCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003196/*[clinic input]
3197os.lchmod
3198
3199 path: path_t
3200 mode: int
3201
3202Change the access permissions of a file, without following symbolic links.
3203
3204If path is a symlink, this affects the link itself rather than the target.
3205Equivalent to chmod(path, mode, follow_symlinks=False)."
3206[clinic start generated code]*/
3207
Larry Hastings2f936352014-08-05 14:04:04 +10003208static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003209os_lchmod_impl(PyObject *module, path_t *path, int mode)
3210/*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003211{
Victor Stinner8c62be82010-05-06 00:08:46 +00003212 int res;
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003213 if (PySys_Audit("os.chmod", "Oii", path->object, mode, -1) < 0) {
3214 return NULL;
3215 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003216 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003217 res = lchmod(path->narrow, mode);
Victor Stinner8c62be82010-05-06 00:08:46 +00003218 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003219 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003220 path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003221 return NULL;
3222 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003223 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003224}
3225#endif /* HAVE_LCHMOD */
3226
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003227
Thomas Wouterscf297e42007-02-23 15:07:44 +00003228#ifdef HAVE_CHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003229/*[clinic input]
3230os.chflags
3231
3232 path: path_t
3233 flags: unsigned_long(bitwise=True)
3234 follow_symlinks: bool=True
3235
3236Set file flags.
3237
3238If follow_symlinks is False, and the last element of the path is a symbolic
3239 link, chflags will change flags on the symbolic link itself instead of the
3240 file the link points to.
3241follow_symlinks may not be implemented on your platform. If it is
3242unavailable, using it will raise a NotImplementedError.
3243
3244[clinic start generated code]*/
3245
Larry Hastings2f936352014-08-05 14:04:04 +10003246static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003247os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
Larry Hastings89964c42015-04-14 18:07:59 -04003248 int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003249/*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003250{
3251 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003252
3253#ifndef HAVE_LCHFLAGS
3254 if (follow_symlinks_specified("chflags", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003255 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003256#endif
3257
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003258 if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
3259 return NULL;
3260 }
3261
Victor Stinner8c62be82010-05-06 00:08:46 +00003262 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003263#ifdef HAVE_LCHFLAGS
3264 if (!follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +10003265 result = lchflags(path->narrow, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003266 else
3267#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003268 result = chflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003269 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003270
Larry Hastings2f936352014-08-05 14:04:04 +10003271 if (result)
3272 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003273
Larry Hastings2f936352014-08-05 14:04:04 +10003274 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003275}
3276#endif /* HAVE_CHFLAGS */
3277
Larry Hastings2f936352014-08-05 14:04:04 +10003278
Thomas Wouterscf297e42007-02-23 15:07:44 +00003279#ifdef HAVE_LCHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003280/*[clinic input]
3281os.lchflags
3282
3283 path: path_t
3284 flags: unsigned_long(bitwise=True)
3285
3286Set file flags.
3287
3288This function will not follow symbolic links.
3289Equivalent to chflags(path, flags, follow_symlinks=False).
3290[clinic start generated code]*/
3291
Larry Hastings2f936352014-08-05 14:04:04 +10003292static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003293os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
3294/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003295{
Victor Stinner8c62be82010-05-06 00:08:46 +00003296 int res;
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003297 if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
3298 return NULL;
3299 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003300 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003301 res = lchflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003302 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003303 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003304 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003305 }
Victor Stinner292c8352012-10-30 02:17:38 +01003306 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003307}
3308#endif /* HAVE_LCHFLAGS */
3309
Larry Hastings2f936352014-08-05 14:04:04 +10003310
Martin v. Löwis244edc82001-10-04 22:44:26 +00003311#ifdef HAVE_CHROOT
Larry Hastings2f936352014-08-05 14:04:04 +10003312/*[clinic input]
3313os.chroot
3314 path: path_t
3315
3316Change root directory to path.
3317
3318[clinic start generated code]*/
3319
Larry Hastings2f936352014-08-05 14:04:04 +10003320static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003321os_chroot_impl(PyObject *module, path_t *path)
3322/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003323{
3324 int res;
3325 Py_BEGIN_ALLOW_THREADS
3326 res = chroot(path->narrow);
3327 Py_END_ALLOW_THREADS
3328 if (res < 0)
3329 return path_error(path);
3330 Py_RETURN_NONE;
3331}
3332#endif /* HAVE_CHROOT */
3333
Martin v. Löwis244edc82001-10-04 22:44:26 +00003334
Guido van Rossum21142a01999-01-08 21:05:37 +00003335#ifdef HAVE_FSYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003336/*[clinic input]
3337os.fsync
3338
3339 fd: fildes
3340
3341Force write of fd to disk.
3342[clinic start generated code]*/
3343
Larry Hastings2f936352014-08-05 14:04:04 +10003344static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003345os_fsync_impl(PyObject *module, int fd)
3346/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003347{
3348 return posix_fildes_fd(fd, fsync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003349}
3350#endif /* HAVE_FSYNC */
3351
Larry Hastings2f936352014-08-05 14:04:04 +10003352
Ross Lagerwall7807c352011-03-17 20:20:30 +02003353#ifdef HAVE_SYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003354/*[clinic input]
3355os.sync
3356
3357Force write of everything to disk.
3358[clinic start generated code]*/
3359
Larry Hastings2f936352014-08-05 14:04:04 +10003360static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003361os_sync_impl(PyObject *module)
3362/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
Ross Lagerwall7807c352011-03-17 20:20:30 +02003363{
3364 Py_BEGIN_ALLOW_THREADS
3365 sync();
3366 Py_END_ALLOW_THREADS
3367 Py_RETURN_NONE;
3368}
Larry Hastings2f936352014-08-05 14:04:04 +10003369#endif /* HAVE_SYNC */
3370
Ross Lagerwall7807c352011-03-17 20:20:30 +02003371
Guido van Rossum21142a01999-01-08 21:05:37 +00003372#ifdef HAVE_FDATASYNC
Guido van Rossum7f58e2e2000-09-22 17:26:14 +00003373#ifdef __hpux
Guido van Rossumecc23b02000-09-22 16:01:05 +00003374extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
3375#endif
3376
Larry Hastings2f936352014-08-05 14:04:04 +10003377/*[clinic input]
3378os.fdatasync
3379
3380 fd: fildes
3381
3382Force write of fd to disk without forcing update of metadata.
3383[clinic start generated code]*/
3384
Larry Hastings2f936352014-08-05 14:04:04 +10003385static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003386os_fdatasync_impl(PyObject *module, int fd)
3387/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003388{
3389 return posix_fildes_fd(fd, fdatasync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003390}
3391#endif /* HAVE_FDATASYNC */
3392
3393
Fredrik Lundh10723342000-07-10 16:38:09 +00003394#ifdef HAVE_CHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003395/*[clinic input]
3396os.chown
3397
3398 path : path_t(allow_fd='PATH_HAVE_FCHOWN')
BNMetricsb9427072018-11-02 15:20:19 +00003399 Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
Larry Hastings2f936352014-08-05 14:04:04 +10003400
3401 uid: uid_t
3402
3403 gid: gid_t
3404
3405 *
3406
3407 dir_fd : dir_fd(requires='fchownat') = None
3408 If not None, it should be a file descriptor open to a directory,
3409 and path should be relative; path will then be relative to that
3410 directory.
3411
3412 follow_symlinks: bool = True
3413 If False, and the last element of the path is a symbolic link,
3414 stat will examine the symbolic link itself instead of the file
3415 the link points to.
3416
3417Change the owner and group id of path to the numeric uid and gid.\
3418
3419path may always be specified as a string.
3420On some platforms, path may also be specified as an open file descriptor.
3421 If this functionality is unavailable, using it raises an exception.
3422If dir_fd is not None, it should be a file descriptor open to a directory,
3423 and path should be relative; path will then be relative to that directory.
3424If follow_symlinks is False, and the last element of the path is a symbolic
3425 link, chown will modify the symbolic link itself instead of the file the
3426 link points to.
3427It is an error to use dir_fd or follow_symlinks when specifying path as
3428 an open file descriptor.
3429dir_fd and follow_symlinks may not be implemented on your platform.
3430 If they are unavailable, using them will raise a NotImplementedError.
3431
3432[clinic start generated code]*/
3433
Larry Hastings2f936352014-08-05 14:04:04 +10003434static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003435os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
Larry Hastings89964c42015-04-14 18:07:59 -04003436 int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003437/*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003438{
3439 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003440
3441#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
3442 if (follow_symlinks_specified("chown", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003443 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003444#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003445 if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
3446 fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
3447 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003448
3449#ifdef __APPLE__
3450 /*
3451 * This is for Mac OS X 10.3, which doesn't have lchown.
3452 * (But we still have an lchown symbol because of weak-linking.)
3453 * It doesn't have fchownat either. So there's no possibility
3454 * of a graceful failover.
Georg Brandlf7875592012-06-24 13:58:31 +02003455 */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003456 if ((!follow_symlinks) && (lchown == NULL)) {
3457 follow_symlinks_specified("chown", follow_symlinks);
Larry Hastings2f936352014-08-05 14:04:04 +10003458 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003459 }
3460#endif
3461
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003462 if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid,
3463 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
3464 return NULL;
3465 }
3466
Victor Stinner8c62be82010-05-06 00:08:46 +00003467 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003468#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003469 if (path->fd != -1)
3470 result = fchown(path->fd, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003471 else
3472#endif
3473#ifdef HAVE_LCHOWN
3474 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003475 result = lchown(path->narrow, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003476 else
3477#endif
3478#ifdef HAVE_FCHOWNAT
3479 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003480 result = fchownat(dir_fd, path->narrow, uid, gid,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003481 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3482 else
3483#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003484 result = chown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003485 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003486
Larry Hastings2f936352014-08-05 14:04:04 +10003487 if (result)
3488 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003489
Larry Hastings2f936352014-08-05 14:04:04 +10003490 Py_RETURN_NONE;
Guido van Rossumb6775db1994-08-01 11:34:53 +00003491}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003492#endif /* HAVE_CHOWN */
Guido van Rossumb6775db1994-08-01 11:34:53 +00003493
Larry Hastings2f936352014-08-05 14:04:04 +10003494
Christian Heimes4e30a842007-11-30 22:12:06 +00003495#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003496/*[clinic input]
3497os.fchown
3498
3499 fd: int
3500 uid: uid_t
3501 gid: gid_t
3502
3503Change the owner and group id of the file specified by file descriptor.
3504
3505Equivalent to os.chown(fd, uid, gid).
3506
3507[clinic start generated code]*/
3508
Larry Hastings2f936352014-08-05 14:04:04 +10003509static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003510os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
3511/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003512{
Victor Stinner8c62be82010-05-06 00:08:46 +00003513 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003514 int async_err = 0;
3515
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003516 if (PySys_Audit("os.chown", "iIIi", fd, uid, gid, -1) < 0) {
3517 return NULL;
3518 }
3519
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003520 do {
3521 Py_BEGIN_ALLOW_THREADS
3522 res = fchown(fd, uid, gid);
3523 Py_END_ALLOW_THREADS
3524 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3525 if (res != 0)
3526 return (!async_err) ? posix_error() : NULL;
3527
Victor Stinner8c62be82010-05-06 00:08:46 +00003528 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003529}
3530#endif /* HAVE_FCHOWN */
3531
Larry Hastings2f936352014-08-05 14:04:04 +10003532
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003533#ifdef HAVE_LCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003534/*[clinic input]
3535os.lchown
3536
3537 path : path_t
3538 uid: uid_t
3539 gid: gid_t
3540
3541Change the owner and group id of path to the numeric uid and gid.
3542
3543This function will not follow symbolic links.
3544Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
3545[clinic start generated code]*/
3546
Larry Hastings2f936352014-08-05 14:04:04 +10003547static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003548os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
3549/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003550{
Victor Stinner8c62be82010-05-06 00:08:46 +00003551 int res;
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003552 if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid, -1) < 0) {
3553 return NULL;
3554 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003555 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10003556 res = lchown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003557 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003558 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003559 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003560 }
Larry Hastings2f936352014-08-05 14:04:04 +10003561 Py_RETURN_NONE;
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003562}
3563#endif /* HAVE_LCHOWN */
3564
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003565
Barry Warsaw53699e91996-12-10 23:23:01 +00003566static PyObject *
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003567posix_getcwd(int use_bytes)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003568{
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003569#ifdef MS_WINDOWS
Victor Stinner689830e2019-06-26 17:31:12 +02003570 wchar_t wbuf[MAXPATHLEN];
3571 wchar_t *wbuf2 = wbuf;
3572 DWORD len;
3573
3574 Py_BEGIN_ALLOW_THREADS
3575 len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
3576 /* If the buffer is large enough, len does not include the
3577 terminating \0. If the buffer is too small, len includes
3578 the space needed for the terminator. */
3579 if (len >= Py_ARRAY_LENGTH(wbuf)) {
Victor Stinnerec3e20a2019-06-28 18:01:59 +02003580 if (len <= PY_SSIZE_T_MAX / sizeof(wchar_t)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02003581 wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00003582 }
Victor Stinner689830e2019-06-26 17:31:12 +02003583 else {
3584 wbuf2 = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003585 }
Victor Stinner689830e2019-06-26 17:31:12 +02003586 if (wbuf2) {
3587 len = GetCurrentDirectoryW(len, wbuf2);
Victor Stinner8c62be82010-05-06 00:08:46 +00003588 }
Victor Stinner689830e2019-06-26 17:31:12 +02003589 }
3590 Py_END_ALLOW_THREADS
3591
3592 if (!wbuf2) {
3593 PyErr_NoMemory();
3594 return NULL;
3595 }
3596 if (!len) {
Victor Stinnerb024e842012-10-31 22:24:06 +01003597 if (wbuf2 != wbuf)
Victor Stinnerb6404912013-07-07 16:21:41 +02003598 PyMem_RawFree(wbuf2);
Victor Stinner689830e2019-06-26 17:31:12 +02003599 return PyErr_SetFromWindowsErr(0);
Victor Stinner8c62be82010-05-06 00:08:46 +00003600 }
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01003601
Victor Stinner689830e2019-06-26 17:31:12 +02003602 PyObject *resobj = PyUnicode_FromWideChar(wbuf2, len);
3603 if (wbuf2 != wbuf) {
3604 PyMem_RawFree(wbuf2);
3605 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003606
Victor Stinner689830e2019-06-26 17:31:12 +02003607 if (use_bytes) {
3608 if (resobj == NULL) {
3609 return NULL;
3610 }
3611 Py_SETREF(resobj, PyUnicode_EncodeFSDefault(resobj));
3612 }
3613
3614 return resobj;
3615#else
3616 const size_t chunk = 1024;
3617
3618 char *buf = NULL;
3619 char *cwd = NULL;
3620 size_t buflen = 0;
3621
Victor Stinner8c62be82010-05-06 00:08:46 +00003622 Py_BEGIN_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003623 do {
Victor Stinner689830e2019-06-26 17:31:12 +02003624 char *newbuf;
3625 if (buflen <= PY_SSIZE_T_MAX - chunk) {
3626 buflen += chunk;
3627 newbuf = PyMem_RawRealloc(buf, buflen);
3628 }
3629 else {
3630 newbuf = NULL;
3631 }
3632 if (newbuf == NULL) {
3633 PyMem_RawFree(buf);
3634 buf = NULL;
Victor Stinnerc44f7072016-03-14 18:07:53 +01003635 break;
3636 }
Victor Stinner689830e2019-06-26 17:31:12 +02003637 buf = newbuf;
Victor Stinner4403d7d2015-04-25 00:16:10 +02003638
Victor Stinner4403d7d2015-04-25 00:16:10 +02003639 cwd = getcwd(buf, buflen);
3640 } while (cwd == NULL && errno == ERANGE);
Victor Stinner8c62be82010-05-06 00:08:46 +00003641 Py_END_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003642
Victor Stinner689830e2019-06-26 17:31:12 +02003643 if (buf == NULL) {
3644 return PyErr_NoMemory();
3645 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003646 if (cwd == NULL) {
3647 PyMem_RawFree(buf);
Victor Stinner8c62be82010-05-06 00:08:46 +00003648 return posix_error();
Victor Stinner4403d7d2015-04-25 00:16:10 +02003649 }
3650
Victor Stinner689830e2019-06-26 17:31:12 +02003651 PyObject *obj;
3652 if (use_bytes) {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003653 obj = PyBytes_FromStringAndSize(buf, strlen(buf));
Victor Stinner689830e2019-06-26 17:31:12 +02003654 }
3655 else {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003656 obj = PyUnicode_DecodeFSDefault(buf);
Victor Stinner689830e2019-06-26 17:31:12 +02003657 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003658 PyMem_RawFree(buf);
3659
3660 return obj;
Victor Stinner689830e2019-06-26 17:31:12 +02003661#endif /* !MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003662}
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003663
Larry Hastings2f936352014-08-05 14:04:04 +10003664
3665/*[clinic input]
3666os.getcwd
3667
3668Return a unicode string representing the current working directory.
3669[clinic start generated code]*/
3670
Larry Hastings2f936352014-08-05 14:04:04 +10003671static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003672os_getcwd_impl(PyObject *module)
3673/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003674{
3675 return posix_getcwd(0);
3676}
3677
Larry Hastings2f936352014-08-05 14:04:04 +10003678
3679/*[clinic input]
3680os.getcwdb
3681
3682Return a bytes string representing the current working directory.
3683[clinic start generated code]*/
3684
Larry Hastings2f936352014-08-05 14:04:04 +10003685static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003686os_getcwdb_impl(PyObject *module)
3687/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003688{
3689 return posix_getcwd(1);
3690}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003691
Larry Hastings2f936352014-08-05 14:04:04 +10003692
Larry Hastings9cf065c2012-06-22 16:30:09 -07003693#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
3694#define HAVE_LINK 1
3695#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003696
Guido van Rossumb6775db1994-08-01 11:34:53 +00003697#ifdef HAVE_LINK
Larry Hastings2f936352014-08-05 14:04:04 +10003698/*[clinic input]
3699
3700os.link
3701
3702 src : path_t
3703 dst : path_t
3704 *
3705 src_dir_fd : dir_fd = None
3706 dst_dir_fd : dir_fd = None
3707 follow_symlinks: bool = True
3708
3709Create a hard link to a file.
3710
3711If either src_dir_fd or dst_dir_fd is not None, it should be a file
3712 descriptor open to a directory, and the respective path string (src or dst)
3713 should be relative; the path will then be relative to that directory.
3714If follow_symlinks is False, and the last element of src is a symbolic
3715 link, link will create a link to the symbolic link itself instead of the
3716 file the link points to.
3717src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
3718 platform. If they are unavailable, using them will raise a
3719 NotImplementedError.
3720[clinic start generated code]*/
3721
Larry Hastings2f936352014-08-05 14:04:04 +10003722static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003723os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003724 int dst_dir_fd, int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003725/*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003726{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003727#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07003728 BOOL result = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003729#else
3730 int result;
3731#endif
3732
Larry Hastings9cf065c2012-06-22 16:30:09 -07003733#ifndef HAVE_LINKAT
3734 if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
3735 argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10003736 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003737 }
3738#endif
3739
Steve Dowercc16be82016-09-08 10:35:16 -07003740#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10003741 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003742 PyErr_SetString(PyExc_NotImplementedError,
3743 "link: src and dst must be the same type");
Larry Hastings2f936352014-08-05 14:04:04 +10003744 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003745 }
Steve Dowercc16be82016-09-08 10:35:16 -07003746#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003747
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003748 if (PySys_Audit("os.link", "OOii", src->object, dst->object,
3749 src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
3750 dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
3751 return NULL;
3752 }
3753
Brian Curtin1b9df392010-11-24 20:24:31 +00003754#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003755 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08003756 result = CreateHardLinkW(dst->wide, src->wide, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003757 Py_END_ALLOW_THREADS
Brian Curtin1b9df392010-11-24 20:24:31 +00003758
Larry Hastings2f936352014-08-05 14:04:04 +10003759 if (!result)
3760 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003761#else
3762 Py_BEGIN_ALLOW_THREADS
Larry Hastings67cbf7b2012-06-22 17:06:48 -07003763#ifdef HAVE_LINKAT
Larry Hastings9cf065c2012-06-22 16:30:09 -07003764 if ((src_dir_fd != DEFAULT_DIR_FD) ||
3765 (dst_dir_fd != DEFAULT_DIR_FD) ||
3766 (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003767 result = linkat(src_dir_fd, src->narrow,
3768 dst_dir_fd, dst->narrow,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003769 follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
3770 else
Steve Dowercc16be82016-09-08 10:35:16 -07003771#endif /* HAVE_LINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10003772 result = link(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003773 Py_END_ALLOW_THREADS
Brian Curtinfc889c42010-11-28 23:59:46 +00003774
Larry Hastings2f936352014-08-05 14:04:04 +10003775 if (result)
3776 return path_error2(src, dst);
Steve Dowercc16be82016-09-08 10:35:16 -07003777#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003778
Larry Hastings2f936352014-08-05 14:04:04 +10003779 Py_RETURN_NONE;
Brian Curtin1b9df392010-11-24 20:24:31 +00003780}
Larry Hastings9cf065c2012-06-22 16:30:09 -07003781#endif
3782
Brian Curtin1b9df392010-11-24 20:24:31 +00003783
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003784#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
Barry Warsaw53699e91996-12-10 23:23:01 +00003785static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003786_listdir_windows_no_opendir(path_t *path, PyObject *list)
Guido van Rossumb6775db1994-08-01 11:34:53 +00003787{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003788 PyObject *v;
3789 HANDLE hFindFile = INVALID_HANDLE_VALUE;
3790 BOOL result;
Steve Dowercc16be82016-09-08 10:35:16 -07003791 wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003792 /* only claim to have space for MAX_PATH */
Victor Stinner75875072013-11-24 19:23:25 +01003793 Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003794 wchar_t *wnamebuf = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003795
Steve Dowercc16be82016-09-08 10:35:16 -07003796 WIN32_FIND_DATAW wFileData;
3797 const wchar_t *po_wchars;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003798
Steve Dowercc16be82016-09-08 10:35:16 -07003799 if (!path->wide) { /* Default arg: "." */
3800 po_wchars = L".";
3801 len = 1;
3802 } else {
3803 po_wchars = path->wide;
3804 len = wcslen(path->wide);
3805 }
3806 /* The +5 is so we can append "\\*.*\0" */
3807 wnamebuf = PyMem_New(wchar_t, len + 5);
3808 if (!wnamebuf) {
3809 PyErr_NoMemory();
Larry Hastings9cf065c2012-06-22 16:30:09 -07003810 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003811 }
Steve Dowercc16be82016-09-08 10:35:16 -07003812 wcscpy(wnamebuf, po_wchars);
Victor Stinner8c62be82010-05-06 00:08:46 +00003813 if (len > 0) {
Steve Dowercc16be82016-09-08 10:35:16 -07003814 wchar_t wch = wnamebuf[len-1];
3815 if (wch != SEP && wch != ALTSEP && wch != L':')
3816 wnamebuf[len++] = SEP;
3817 wcscpy(wnamebuf + len, L"*.*");
Victor Stinner8c62be82010-05-06 00:08:46 +00003818 }
Steve Dowercc16be82016-09-08 10:35:16 -07003819 if ((list = PyList_New(0)) == NULL) {
3820 goto exit;
3821 }
Antoine Pitroub73caab2010-08-09 23:39:31 +00003822 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003823 hFindFile = FindFirstFileW(wnamebuf, &wFileData);
Antoine Pitroub73caab2010-08-09 23:39:31 +00003824 Py_END_ALLOW_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +00003825 if (hFindFile == INVALID_HANDLE_VALUE) {
3826 int error = GetLastError();
3827 if (error == ERROR_FILE_NOT_FOUND)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003828 goto exit;
3829 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003830 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003831 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003832 }
3833 do {
3834 /* Skip over . and .. */
Steve Dowercc16be82016-09-08 10:35:16 -07003835 if (wcscmp(wFileData.cFileName, L".") != 0 &&
3836 wcscmp(wFileData.cFileName, L"..") != 0) {
3837 v = PyUnicode_FromWideChar(wFileData.cFileName,
3838 wcslen(wFileData.cFileName));
3839 if (path->narrow && v) {
3840 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3841 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003842 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003843 Py_DECREF(list);
3844 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003845 break;
3846 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003847 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003848 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003849 Py_DECREF(list);
3850 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003851 break;
3852 }
3853 Py_DECREF(v);
3854 }
3855 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003856 result = FindNextFileW(hFindFile, &wFileData);
Victor Stinner8c62be82010-05-06 00:08:46 +00003857 Py_END_ALLOW_THREADS
3858 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
3859 it got to the end of the directory. */
3860 if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003861 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003862 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003863 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003864 }
3865 } while (result == TRUE);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003866
Larry Hastings9cf065c2012-06-22 16:30:09 -07003867exit:
3868 if (hFindFile != INVALID_HANDLE_VALUE) {
3869 if (FindClose(hFindFile) == FALSE) {
3870 if (list != NULL) {
3871 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003872 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003873 }
3874 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003875 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003876 PyMem_Free(wnamebuf);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003877
Larry Hastings9cf065c2012-06-22 16:30:09 -07003878 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003879} /* end of _listdir_windows_no_opendir */
3880
3881#else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
3882
3883static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003884_posix_listdir(path_t *path, PyObject *list)
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003885{
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003886 PyObject *v;
3887 DIR *dirp = NULL;
3888 struct dirent *ep;
3889 int return_str; /* if false, return bytes */
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003890#ifdef HAVE_FDOPENDIR
3891 int fd = -1;
3892#endif
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003893
Victor Stinner8c62be82010-05-06 00:08:46 +00003894 errno = 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003895#ifdef HAVE_FDOPENDIR
Gregory P. Smith40a21602013-03-20 20:52:50 -07003896 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003897 /* closedir() closes the FD, so we duplicate it */
Victor Stinnerdaf45552013-08-28 00:53:59 +02003898 fd = _Py_dup(path->fd);
Victor Stinnerf3266652013-12-19 13:24:49 +01003899 if (fd == -1)
3900 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003901
Larry Hastingsfdaea062012-06-25 04:42:23 -07003902 return_str = 1;
3903
Larry Hastings9cf065c2012-06-22 16:30:09 -07003904 Py_BEGIN_ALLOW_THREADS
3905 dirp = fdopendir(fd);
3906 Py_END_ALLOW_THREADS
3907 }
3908 else
3909#endif
3910 {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003911 const char *name;
Gregory P. Smith40a21602013-03-20 20:52:50 -07003912 if (path->narrow) {
3913 name = path->narrow;
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03003914 /* only return bytes if they specified a bytes-like object */
3915 return_str = !PyObject_CheckBuffer(path->object);
Larry Hastingsfdaea062012-06-25 04:42:23 -07003916 }
3917 else {
3918 name = ".";
3919 return_str = 1;
3920 }
3921
Larry Hastings9cf065c2012-06-22 16:30:09 -07003922 Py_BEGIN_ALLOW_THREADS
3923 dirp = opendir(name);
3924 Py_END_ALLOW_THREADS
3925 }
3926
3927 if (dirp == NULL) {
Gregory P. Smith40a21602013-03-20 20:52:50 -07003928 list = path_error(path);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003929#ifdef HAVE_FDOPENDIR
3930 if (fd != -1) {
3931 Py_BEGIN_ALLOW_THREADS
3932 close(fd);
3933 Py_END_ALLOW_THREADS
3934 }
3935#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003936 goto exit;
3937 }
3938 if ((list = PyList_New(0)) == NULL) {
3939 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003940 }
3941 for (;;) {
3942 errno = 0;
3943 Py_BEGIN_ALLOW_THREADS
3944 ep = readdir(dirp);
3945 Py_END_ALLOW_THREADS
3946 if (ep == NULL) {
3947 if (errno == 0) {
3948 break;
3949 } else {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003950 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003951 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003952 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003953 }
3954 }
3955 if (ep->d_name[0] == '.' &&
3956 (NAMLEN(ep) == 1 ||
3957 (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
3958 continue;
Larry Hastingsfdaea062012-06-25 04:42:23 -07003959 if (return_str)
Victor Stinnera45598a2010-05-14 16:35:39 +00003960 v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
3961 else
3962 v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
Victor Stinner8c62be82010-05-06 00:08:46 +00003963 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003964 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003965 break;
3966 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003967 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003968 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003969 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003970 break;
3971 }
3972 Py_DECREF(v);
3973 }
Guido van Rossum0ee42cd1991-04-08 21:01:03 +00003974
Larry Hastings9cf065c2012-06-22 16:30:09 -07003975exit:
3976 if (dirp != NULL) {
3977 Py_BEGIN_ALLOW_THREADS
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003978#ifdef HAVE_FDOPENDIR
Larry Hastings9cf065c2012-06-22 16:30:09 -07003979 if (fd > -1)
3980 rewinddir(dirp);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003981#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003982 closedir(dirp);
3983 Py_END_ALLOW_THREADS
3984 }
3985
Larry Hastings9cf065c2012-06-22 16:30:09 -07003986 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003987} /* end of _posix_listdir */
3988#endif /* which OS */
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003989
Larry Hastings2f936352014-08-05 14:04:04 +10003990
3991/*[clinic input]
3992os.listdir
3993
3994 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
3995
3996Return a list containing the names of the files in the directory.
3997
BNMetricsb9427072018-11-02 15:20:19 +00003998path can be specified as either str, bytes, or a path-like object. If path is bytes,
Larry Hastings2f936352014-08-05 14:04:04 +10003999 the filenames returned will also be bytes; in all other circumstances
4000 the filenames returned will be str.
4001If path is None, uses the path='.'.
4002On some platforms, path may also be specified as an open file descriptor;\
4003 the file descriptor must refer to a directory.
4004 If this functionality is unavailable, using it raises NotImplementedError.
4005
4006The list is in arbitrary order. It does not include the special
4007entries '.' and '..' even if they are present in the directory.
4008
4009
4010[clinic start generated code]*/
4011
Larry Hastings2f936352014-08-05 14:04:04 +10004012static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004013os_listdir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +00004014/*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004015{
Steve Dower60419a72019-06-24 08:42:54 -07004016 if (PySys_Audit("os.listdir", "O",
4017 path->object ? path->object : Py_None) < 0) {
4018 return NULL;
4019 }
Larry Hastings2f936352014-08-05 14:04:04 +10004020#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
4021 return _listdir_windows_no_opendir(path, NULL);
4022#else
4023 return _posix_listdir(path, NULL);
4024#endif
4025}
4026
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004027#ifdef MS_WINDOWS
Mark Hammondef8b6542001-05-13 08:04:26 +00004028/* A helper function for abspath on win32 */
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03004029/*[clinic input]
4030os._getfullpathname
Victor Stinnereb5657a2011-09-30 01:44:27 +02004031
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03004032 path: path_t
4033 /
4034
4035[clinic start generated code]*/
4036
4037static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004038os__getfullpathname_impl(PyObject *module, path_t *path)
4039/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03004040{
Victor Stinner3939c322019-06-25 15:02:43 +02004041 wchar_t *abspath;
Victor Stinnereb5657a2011-09-30 01:44:27 +02004042
Victor Stinner3939c322019-06-25 15:02:43 +02004043 /* _Py_abspath() is implemented with GetFullPathNameW() on Windows */
4044 if (_Py_abspath(path->wide, &abspath) < 0) {
4045 return win32_error_object("GetFullPathNameW", path->object);
Victor Stinner8c62be82010-05-06 00:08:46 +00004046 }
Victor Stinner3939c322019-06-25 15:02:43 +02004047 if (abspath == NULL) {
4048 return PyErr_NoMemory();
4049 }
4050
4051 PyObject *str = PyUnicode_FromWideChar(abspath, wcslen(abspath));
4052 PyMem_RawFree(abspath);
4053 if (str == NULL) {
4054 return NULL;
4055 }
4056 if (path->narrow) {
4057 Py_SETREF(str, PyUnicode_EncodeFSDefault(str));
4058 }
4059 return str;
Larry Hastings2f936352014-08-05 14:04:04 +10004060}
Brian Curtind40e6f72010-07-08 21:39:08 +00004061
Brian Curtind25aef52011-06-13 15:16:04 -05004062
Larry Hastings2f936352014-08-05 14:04:04 +10004063/*[clinic input]
4064os._getfinalpathname
Brian Curtinf5e76d02010-11-24 13:14:05 +00004065
Steve Dower23ad6d02018-02-22 10:39:10 -08004066 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10004067 /
4068
4069A helper function for samepath on windows.
4070[clinic start generated code]*/
4071
Larry Hastings2f936352014-08-05 14:04:04 +10004072static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08004073os__getfinalpathname_impl(PyObject *module, path_t *path)
4074/*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
Brian Curtind40e6f72010-07-08 21:39:08 +00004075{
4076 HANDLE hFile;
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004077 wchar_t buf[MAXPATHLEN], *target_path = buf;
4078 int buf_size = Py_ARRAY_LENGTH(buf);
Brian Curtind40e6f72010-07-08 21:39:08 +00004079 int result_length;
Larry Hastings2f936352014-08-05 14:04:04 +10004080 PyObject *result;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004081
Steve Dower23ad6d02018-02-22 10:39:10 -08004082 Py_BEGIN_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00004083 hFile = CreateFileW(
Steve Dower23ad6d02018-02-22 10:39:10 -08004084 path->wide,
Brian Curtind40e6f72010-07-08 21:39:08 +00004085 0, /* desired access */
4086 0, /* share mode */
4087 NULL, /* security attributes */
4088 OPEN_EXISTING,
4089 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
4090 FILE_FLAG_BACKUP_SEMANTICS,
4091 NULL);
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004092 Py_END_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004093
Steve Dower23ad6d02018-02-22 10:39:10 -08004094 if (hFile == INVALID_HANDLE_VALUE) {
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004095 return win32_error_object("CreateFileW", path->object);
Steve Dower23ad6d02018-02-22 10:39:10 -08004096 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004097
4098 /* We have a good handle to the target, use it to determine the
4099 target path name. */
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004100 while (1) {
4101 Py_BEGIN_ALLOW_THREADS
4102 result_length = GetFinalPathNameByHandleW(hFile, target_path,
4103 buf_size, VOLUME_NAME_DOS);
4104 Py_END_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00004105
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004106 if (!result_length) {
4107 result = win32_error_object("GetFinalPathNameByHandleW",
4108 path->object);
4109 goto cleanup;
4110 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004111
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004112 if (result_length < buf_size) {
4113 break;
4114 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004115
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004116 wchar_t *tmp;
4117 tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
4118 result_length * sizeof(*tmp));
4119 if (!tmp) {
4120 result = PyErr_NoMemory();
4121 goto cleanup;
4122 }
4123
4124 buf_size = result_length;
4125 target_path = tmp;
Steve Dower23ad6d02018-02-22 10:39:10 -08004126 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004127
Victor Stinner9d3b93b2011-11-22 02:27:30 +01004128 result = PyUnicode_FromWideChar(target_path, result_length);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004129 if (result && path->narrow) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004130 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004131 }
Steve Dower23ad6d02018-02-22 10:39:10 -08004132
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004133cleanup:
4134 if (target_path != buf) {
4135 PyMem_Free(target_path);
4136 }
4137 CloseHandle(hFile);
4138 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10004139}
Brian Curtin62857742010-09-06 17:07:27 +00004140
Tim Golden6b528062013-08-01 12:44:00 +01004141
Larry Hastings2f936352014-08-05 14:04:04 +10004142/*[clinic input]
4143os._getvolumepathname
4144
Steve Dower23ad6d02018-02-22 10:39:10 -08004145 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10004146
4147A helper function for ismount on Win32.
4148[clinic start generated code]*/
4149
Larry Hastings2f936352014-08-05 14:04:04 +10004150static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08004151os__getvolumepathname_impl(PyObject *module, path_t *path)
4152/*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004153{
4154 PyObject *result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004155 wchar_t *mountpath=NULL;
Victor Stinner6edddfa2013-11-24 19:22:57 +01004156 size_t buflen;
Tim Golden6b528062013-08-01 12:44:00 +01004157 BOOL ret;
4158
Tim Golden6b528062013-08-01 12:44:00 +01004159 /* Volume path should be shorter than entire path */
Steve Dower23ad6d02018-02-22 10:39:10 -08004160 buflen = Py_MAX(path->length, MAX_PATH);
Victor Stinner6edddfa2013-11-24 19:22:57 +01004161
Victor Stinner850a18e2017-10-24 16:53:32 -07004162 if (buflen > PY_DWORD_MAX) {
Victor Stinner6edddfa2013-11-24 19:22:57 +01004163 PyErr_SetString(PyExc_OverflowError, "path too long");
4164 return NULL;
4165 }
4166
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004167 mountpath = PyMem_New(wchar_t, buflen);
Tim Golden6b528062013-08-01 12:44:00 +01004168 if (mountpath == NULL)
4169 return PyErr_NoMemory();
4170
4171 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -08004172 ret = GetVolumePathNameW(path->wide, mountpath,
Victor Stinner6edddfa2013-11-24 19:22:57 +01004173 Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
Tim Golden6b528062013-08-01 12:44:00 +01004174 Py_END_ALLOW_THREADS
4175
4176 if (!ret) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004177 result = win32_error_object("_getvolumepathname", path->object);
Tim Golden6b528062013-08-01 12:44:00 +01004178 goto exit;
4179 }
4180 result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
Steve Dower23ad6d02018-02-22 10:39:10 -08004181 if (path->narrow)
4182 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Tim Golden6b528062013-08-01 12:44:00 +01004183
4184exit:
4185 PyMem_Free(mountpath);
4186 return result;
4187}
Tim Golden6b528062013-08-01 12:44:00 +01004188
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004189#endif /* MS_WINDOWS */
Mark Hammondef8b6542001-05-13 08:04:26 +00004190
Larry Hastings2f936352014-08-05 14:04:04 +10004191
4192/*[clinic input]
4193os.mkdir
4194
4195 path : path_t
4196
4197 mode: int = 0o777
4198
4199 *
4200
4201 dir_fd : dir_fd(requires='mkdirat') = None
4202
4203# "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
4204
4205Create a directory.
4206
4207If dir_fd is not None, it should be a file descriptor open to a directory,
4208 and path should be relative; path will then be relative to that directory.
4209dir_fd may not be implemented on your platform.
4210 If it is unavailable, using it will raise a NotImplementedError.
4211
4212The mode argument is ignored on Windows.
4213[clinic start generated code]*/
4214
Larry Hastings2f936352014-08-05 14:04:04 +10004215static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004216os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
4217/*[clinic end generated code: output=a70446903abe821f input=e965f68377e9b1ce]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004218{
4219 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004220
Saiyang Gou7514f4f2020-02-12 23:47:42 -08004221 if (PySys_Audit("os.mkdir", "Oii", path->object, mode,
4222 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4223 return NULL;
4224 }
4225
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004226#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004227 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004228 result = CreateDirectoryW(path->wide, NULL);
Victor Stinner8c62be82010-05-06 00:08:46 +00004229 Py_END_ALLOW_THREADS
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004230
Larry Hastings2f936352014-08-05 14:04:04 +10004231 if (!result)
4232 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004233#else
Victor Stinner8c62be82010-05-06 00:08:46 +00004234 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004235#if HAVE_MKDIRAT
4236 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004237 result = mkdirat(dir_fd, path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004238 else
4239#endif
Erik Bray03eb11f2017-10-27 14:27:06 +02004240#if defined(__WATCOMC__) && !defined(__QNX__)
Larry Hastings2f936352014-08-05 14:04:04 +10004241 result = mkdir(path->narrow);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004242#else
Larry Hastings2f936352014-08-05 14:04:04 +10004243 result = mkdir(path->narrow, mode);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004244#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004245 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004246 if (result < 0)
4247 return path_error(path);
Steve Dowercc16be82016-09-08 10:35:16 -07004248#endif /* MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10004249 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004250}
4251
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004252
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004253/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
4254#if defined(HAVE_SYS_RESOURCE_H)
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004255#include <sys/resource.h>
4256#endif
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004257
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004258
4259#ifdef HAVE_NICE
Larry Hastings2f936352014-08-05 14:04:04 +10004260/*[clinic input]
4261os.nice
4262
4263 increment: int
4264 /
4265
4266Add increment to the priority of process and return the new priority.
4267[clinic start generated code]*/
4268
Larry Hastings2f936352014-08-05 14:04:04 +10004269static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004270os_nice_impl(PyObject *module, int increment)
4271/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004272{
4273 int value;
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004274
Victor Stinner8c62be82010-05-06 00:08:46 +00004275 /* There are two flavours of 'nice': one that returns the new
4276 priority (as required by almost all standards out there) and the
Benjamin Peterson288d1da2017-09-28 22:44:27 -07004277 Linux/FreeBSD one, which returns '0' on success and advices
Victor Stinner8c62be82010-05-06 00:08:46 +00004278 the use of getpriority() to get the new priority.
Tim Peters5aa91602002-01-30 05:46:57 +00004279
Victor Stinner8c62be82010-05-06 00:08:46 +00004280 If we are of the nice family that returns the new priority, we
4281 need to clear errno before the call, and check if errno is filled
4282 before calling posix_error() on a returnvalue of -1, because the
4283 -1 may be the actual new priority! */
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004284
Victor Stinner8c62be82010-05-06 00:08:46 +00004285 errno = 0;
4286 value = nice(increment);
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004287#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
Victor Stinner8c62be82010-05-06 00:08:46 +00004288 if (value == 0)
4289 value = getpriority(PRIO_PROCESS, 0);
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004290#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004291 if (value == -1 && errno != 0)
4292 /* either nice() or getpriority() returned an error */
4293 return posix_error();
4294 return PyLong_FromLong((long) value);
Guido van Rossum775f4da1993-01-09 17:18:52 +00004295}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004296#endif /* HAVE_NICE */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004297
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004298
4299#ifdef HAVE_GETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004300/*[clinic input]
4301os.getpriority
4302
4303 which: int
4304 who: int
4305
4306Return program scheduling priority.
4307[clinic start generated code]*/
4308
Larry Hastings2f936352014-08-05 14:04:04 +10004309static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004310os_getpriority_impl(PyObject *module, int which, int who)
4311/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004312{
4313 int retval;
4314
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004315 errno = 0;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004316 retval = getpriority(which, who);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004317 if (errno != 0)
4318 return posix_error();
4319 return PyLong_FromLong((long)retval);
4320}
4321#endif /* HAVE_GETPRIORITY */
4322
4323
4324#ifdef HAVE_SETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004325/*[clinic input]
4326os.setpriority
4327
4328 which: int
4329 who: int
4330 priority: int
4331
4332Set program scheduling priority.
4333[clinic start generated code]*/
4334
Larry Hastings2f936352014-08-05 14:04:04 +10004335static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004336os_setpriority_impl(PyObject *module, int which, int who, int priority)
4337/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004338{
4339 int retval;
4340
4341 retval = setpriority(which, who, priority);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004342 if (retval == -1)
4343 return posix_error();
4344 Py_RETURN_NONE;
4345}
4346#endif /* HAVE_SETPRIORITY */
4347
4348
Barry Warsaw53699e91996-12-10 23:23:01 +00004349static PyObject *
Larry Hastings2f936352014-08-05 14:04:04 +10004350internal_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 +00004351{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004352 const char *function_name = is_replace ? "replace" : "rename";
Larry Hastings9cf065c2012-06-22 16:30:09 -07004353 int dir_fd_specified;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004354
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004355#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004356 BOOL result;
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004357 int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004358#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004359 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004360#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004361
Larry Hastings9cf065c2012-06-22 16:30:09 -07004362 dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
4363 (dst_dir_fd != DEFAULT_DIR_FD);
4364#ifndef HAVE_RENAMEAT
4365 if (dir_fd_specified) {
4366 argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10004367 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004368 }
4369#endif
4370
Saiyang Gou7514f4f2020-02-12 23:47:42 -08004371 if (PySys_Audit("os.rename", "OOii", src->object, dst->object,
4372 src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
4373 dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
4374 return NULL;
4375 }
4376
Larry Hastings9cf065c2012-06-22 16:30:09 -07004377#ifdef MS_WINDOWS
4378 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004379 result = MoveFileExW(src->wide, dst->wide, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004380 Py_END_ALLOW_THREADS
4381
Larry Hastings2f936352014-08-05 14:04:04 +10004382 if (!result)
4383 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004384
4385#else
Steve Dowercc16be82016-09-08 10:35:16 -07004386 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
4387 PyErr_Format(PyExc_ValueError,
4388 "%s: src and dst must be the same type", function_name);
4389 return NULL;
4390 }
4391
Larry Hastings9cf065c2012-06-22 16:30:09 -07004392 Py_BEGIN_ALLOW_THREADS
4393#ifdef HAVE_RENAMEAT
4394 if (dir_fd_specified)
Larry Hastings2f936352014-08-05 14:04:04 +10004395 result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004396 else
4397#endif
Steve Dowercc16be82016-09-08 10:35:16 -07004398 result = rename(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004399 Py_END_ALLOW_THREADS
4400
Larry Hastings2f936352014-08-05 14:04:04 +10004401 if (result)
4402 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004403#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004404 Py_RETURN_NONE;
4405}
Larry Hastings9cf065c2012-06-22 16:30:09 -07004406
Larry Hastings2f936352014-08-05 14:04:04 +10004407
4408/*[clinic input]
4409os.rename
4410
4411 src : path_t
4412 dst : path_t
4413 *
4414 src_dir_fd : dir_fd = None
4415 dst_dir_fd : dir_fd = None
4416
4417Rename a file or directory.
4418
4419If either src_dir_fd or dst_dir_fd is not None, it should be a file
4420 descriptor open to a directory, and the respective path string (src or dst)
4421 should be relative; the path will then be relative to that directory.
4422src_dir_fd and dst_dir_fd, may not be implemented on your platform.
4423 If they are unavailable, using them will raise a NotImplementedError.
4424[clinic start generated code]*/
4425
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004426static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004427os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04004428 int dst_dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004429/*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004430{
Larry Hastings2f936352014-08-05 14:04:04 +10004431 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004432}
4433
Larry Hastings2f936352014-08-05 14:04:04 +10004434
4435/*[clinic input]
4436os.replace = os.rename
4437
4438Rename a file or directory, overwriting the destination.
4439
4440If either src_dir_fd or dst_dir_fd is not None, it should be a file
4441 descriptor open to a directory, and the respective path string (src or dst)
4442 should be relative; the path will then be relative to that directory.
4443src_dir_fd and dst_dir_fd, may not be implemented on your platform.
Anthony Sottile73d60022019-02-12 23:15:54 -05004444 If they are unavailable, using them will raise a NotImplementedError.
Larry Hastings2f936352014-08-05 14:04:04 +10004445[clinic start generated code]*/
4446
Larry Hastings2f936352014-08-05 14:04:04 +10004447static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004448os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
4449 int dst_dir_fd)
Anthony Sottile73d60022019-02-12 23:15:54 -05004450/*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004451{
4452 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
4453}
4454
4455
4456/*[clinic input]
4457os.rmdir
4458
4459 path: path_t
4460 *
4461 dir_fd: dir_fd(requires='unlinkat') = None
4462
4463Remove a directory.
4464
4465If dir_fd is not None, it should be a file descriptor open to a directory,
4466 and path should be relative; path will then be relative to that directory.
4467dir_fd may not be implemented on your platform.
4468 If it is unavailable, using it will raise a NotImplementedError.
4469[clinic start generated code]*/
4470
Larry Hastings2f936352014-08-05 14:04:04 +10004471static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004472os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
4473/*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004474{
4475 int result;
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004476
Saiyang Gou7514f4f2020-02-12 23:47:42 -08004477 if (PySys_Audit("os.rmdir", "Oi", path->object,
4478 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4479 return NULL;
4480 }
4481
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004482 Py_BEGIN_ALLOW_THREADS
4483#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004484 /* Windows, success=1, UNIX, success=0 */
4485 result = !RemoveDirectoryW(path->wide);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004486#else
4487#ifdef HAVE_UNLINKAT
4488 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004489 result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004490 else
4491#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004492 result = rmdir(path->narrow);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004493#endif
4494 Py_END_ALLOW_THREADS
4495
Larry Hastings2f936352014-08-05 14:04:04 +10004496 if (result)
4497 return path_error(path);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004498
Larry Hastings2f936352014-08-05 14:04:04 +10004499 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004500}
4501
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004502
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004503#ifdef HAVE_SYSTEM
Larry Hastings2f936352014-08-05 14:04:04 +10004504#ifdef MS_WINDOWS
4505/*[clinic input]
4506os.system -> long
4507
4508 command: Py_UNICODE
4509
4510Execute the command in a subshell.
4511[clinic start generated code]*/
4512
Larry Hastings2f936352014-08-05 14:04:04 +10004513static long
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02004514os_system_impl(PyObject *module, const Py_UNICODE *command)
4515/*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004516{
4517 long result;
Steve Dowerb82e17e2019-05-23 08:45:22 -07004518
Steve Dowerfbe3c762019-10-18 00:52:15 -07004519 if (PySys_Audit("os.system", "(u)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004520 return -1;
4521 }
4522
Victor Stinner8c62be82010-05-06 00:08:46 +00004523 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08004524 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10004525 result = _wsystem(command);
Steve Dowerc3630612016-11-19 18:41:16 -08004526 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00004527 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004528 return result;
4529}
4530#else /* MS_WINDOWS */
4531/*[clinic input]
4532os.system -> long
4533
4534 command: FSConverter
4535
4536Execute the command in a subshell.
4537[clinic start generated code]*/
4538
Larry Hastings2f936352014-08-05 14:04:04 +10004539static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004540os_system_impl(PyObject *module, PyObject *command)
4541/*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004542{
4543 long result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004544 const char *bytes = PyBytes_AsString(command);
Steve Dowerb82e17e2019-05-23 08:45:22 -07004545
Steve Dowerfbe3c762019-10-18 00:52:15 -07004546 if (PySys_Audit("os.system", "(O)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004547 return -1;
4548 }
4549
Larry Hastings2f936352014-08-05 14:04:04 +10004550 Py_BEGIN_ALLOW_THREADS
4551 result = system(bytes);
4552 Py_END_ALLOW_THREADS
4553 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004554}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004555#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004556#endif /* HAVE_SYSTEM */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004557
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004558
Larry Hastings2f936352014-08-05 14:04:04 +10004559/*[clinic input]
4560os.umask
4561
4562 mask: int
4563 /
4564
4565Set the current numeric umask and return the previous umask.
4566[clinic start generated code]*/
4567
Larry Hastings2f936352014-08-05 14:04:04 +10004568static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004569os_umask_impl(PyObject *module, int mask)
4570/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004571{
4572 int i = (int)umask(mask);
Victor Stinner8c62be82010-05-06 00:08:46 +00004573 if (i < 0)
4574 return posix_error();
4575 return PyLong_FromLong((long)i);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004576}
4577
Brian Curtind40e6f72010-07-08 21:39:08 +00004578#ifdef MS_WINDOWS
4579
4580/* override the default DeleteFileW behavior so that directory
4581symlinks can be removed with this function, the same as with
4582Unix symlinks */
4583BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
4584{
4585 WIN32_FILE_ATTRIBUTE_DATA info;
4586 WIN32_FIND_DATAW find_data;
4587 HANDLE find_data_handle;
4588 int is_directory = 0;
4589 int is_link = 0;
4590
4591 if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
4592 is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004593
Brian Curtind40e6f72010-07-08 21:39:08 +00004594 /* Get WIN32_FIND_DATA structure for the path to determine if
4595 it is a symlink */
4596 if(is_directory &&
4597 info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
4598 find_data_handle = FindFirstFileW(lpFileName, &find_data);
4599
4600 if(find_data_handle != INVALID_HANDLE_VALUE) {
Tim Golden0321cf22014-05-05 19:46:17 +01004601 /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
4602 IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
4603 is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
4604 find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
Brian Curtind40e6f72010-07-08 21:39:08 +00004605 FindClose(find_data_handle);
4606 }
4607 }
4608 }
4609
4610 if (is_directory && is_link)
4611 return RemoveDirectoryW(lpFileName);
4612
4613 return DeleteFileW(lpFileName);
4614}
4615#endif /* MS_WINDOWS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004616
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004617
Larry Hastings2f936352014-08-05 14:04:04 +10004618/*[clinic input]
4619os.unlink
4620
4621 path: path_t
4622 *
4623 dir_fd: dir_fd(requires='unlinkat')=None
4624
4625Remove a file (same as remove()).
4626
4627If dir_fd is not None, it should be a file descriptor open to a directory,
4628 and path should be relative; path will then be relative to that directory.
4629dir_fd may not be implemented on your platform.
4630 If it is unavailable, using it will raise a NotImplementedError.
4631
4632[clinic start generated code]*/
4633
Larry Hastings2f936352014-08-05 14:04:04 +10004634static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004635os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
4636/*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004637{
4638 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004639
Saiyang Gou7514f4f2020-02-12 23:47:42 -08004640 if (PySys_Audit("os.remove", "Oi", path->object,
4641 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4642 return NULL;
4643 }
4644
Larry Hastings9cf065c2012-06-22 16:30:09 -07004645 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04004646 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004647#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004648 /* Windows, success=1, UNIX, success=0 */
4649 result = !Py_DeleteFileW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004650#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004651#ifdef HAVE_UNLINKAT
4652 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004653 result = unlinkat(dir_fd, path->narrow, 0);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004654 else
4655#endif /* HAVE_UNLINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10004656 result = unlink(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004657#endif
Steve Dower8fc89802015-04-12 00:26:27 -04004658 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004659 Py_END_ALLOW_THREADS
4660
Larry Hastings2f936352014-08-05 14:04:04 +10004661 if (result)
4662 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004663
Larry Hastings2f936352014-08-05 14:04:04 +10004664 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004665}
4666
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004667
Larry Hastings2f936352014-08-05 14:04:04 +10004668/*[clinic input]
4669os.remove = os.unlink
4670
4671Remove a file (same as unlink()).
4672
4673If dir_fd is not None, it should be a file descriptor open to a directory,
4674 and path should be relative; path will then be relative to that directory.
4675dir_fd may not be implemented on your platform.
4676 If it is unavailable, using it will raise a NotImplementedError.
4677[clinic start generated code]*/
4678
Larry Hastings2f936352014-08-05 14:04:04 +10004679static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004680os_remove_impl(PyObject *module, path_t *path, int dir_fd)
4681/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004682{
4683 return os_unlink_impl(module, path, dir_fd);
4684}
4685
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004686
Larry Hastings605a62d2012-06-24 04:33:36 -07004687static PyStructSequence_Field uname_result_fields[] = {
4688 {"sysname", "operating system name"},
4689 {"nodename", "name of machine on network (implementation-defined)"},
4690 {"release", "operating system release"},
4691 {"version", "operating system version"},
4692 {"machine", "hardware identifier"},
4693 {NULL}
4694};
4695
4696PyDoc_STRVAR(uname_result__doc__,
4697"uname_result: Result from os.uname().\n\n\
4698This object may be accessed either as a tuple of\n\
4699 (sysname, nodename, release, version, machine),\n\
4700or via the attributes sysname, nodename, release, version, and machine.\n\
4701\n\
4702See os.uname for more information.");
4703
4704static PyStructSequence_Desc uname_result_desc = {
Eddie Elizondob3966632019-11-05 07:16:14 -08004705 MODNAME ".uname_result", /* name */
Larry Hastings605a62d2012-06-24 04:33:36 -07004706 uname_result__doc__, /* doc */
4707 uname_result_fields,
4708 5
4709};
4710
Larry Hastings605a62d2012-06-24 04:33:36 -07004711#ifdef HAVE_UNAME
Larry Hastings2f936352014-08-05 14:04:04 +10004712/*[clinic input]
4713os.uname
4714
4715Return an object identifying the current operating system.
4716
4717The object behaves like a named tuple with the following fields:
4718 (sysname, nodename, release, version, machine)
4719
4720[clinic start generated code]*/
4721
Larry Hastings2f936352014-08-05 14:04:04 +10004722static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004723os_uname_impl(PyObject *module)
4724/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004725{
Victor Stinner8c62be82010-05-06 00:08:46 +00004726 struct utsname u;
4727 int res;
Larry Hastings605a62d2012-06-24 04:33:36 -07004728 PyObject *value;
Neal Norwitze241ce82003-02-17 18:17:05 +00004729
Victor Stinner8c62be82010-05-06 00:08:46 +00004730 Py_BEGIN_ALLOW_THREADS
4731 res = uname(&u);
4732 Py_END_ALLOW_THREADS
4733 if (res < 0)
4734 return posix_error();
Larry Hastings605a62d2012-06-24 04:33:36 -07004735
Hai Shif707d942020-03-16 21:15:01 +08004736 PyObject *UnameResultType = get_posix_state(module)->UnameResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -08004737 value = PyStructSequence_New((PyTypeObject *)UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07004738 if (value == NULL)
4739 return NULL;
4740
4741#define SET(i, field) \
4742 { \
Victor Stinnera534fc42013-06-03 22:07:27 +02004743 PyObject *o = PyUnicode_DecodeFSDefault(field); \
Larry Hastings605a62d2012-06-24 04:33:36 -07004744 if (!o) { \
4745 Py_DECREF(value); \
4746 return NULL; \
4747 } \
4748 PyStructSequence_SET_ITEM(value, i, o); \
4749 } \
4750
4751 SET(0, u.sysname);
4752 SET(1, u.nodename);
4753 SET(2, u.release);
4754 SET(3, u.version);
4755 SET(4, u.machine);
4756
4757#undef SET
4758
4759 return value;
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004760}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004761#endif /* HAVE_UNAME */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004762
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004763
Larry Hastings9cf065c2012-06-22 16:30:09 -07004764
4765typedef struct {
4766 int now;
4767 time_t atime_s;
4768 long atime_ns;
4769 time_t mtime_s;
4770 long mtime_ns;
4771} utime_t;
4772
4773/*
Victor Stinner484df002014-10-09 13:52:31 +02004774 * these macros assume that "ut" is a pointer to a utime_t
Larry Hastings9cf065c2012-06-22 16:30:09 -07004775 * they also intentionally leak the declaration of a pointer named "time"
4776 */
4777#define UTIME_TO_TIMESPEC \
4778 struct timespec ts[2]; \
4779 struct timespec *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004780 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004781 time = NULL; \
4782 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004783 ts[0].tv_sec = ut->atime_s; \
4784 ts[0].tv_nsec = ut->atime_ns; \
4785 ts[1].tv_sec = ut->mtime_s; \
4786 ts[1].tv_nsec = ut->mtime_ns; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004787 time = ts; \
4788 } \
4789
4790#define UTIME_TO_TIMEVAL \
4791 struct timeval tv[2]; \
4792 struct timeval *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004793 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004794 time = NULL; \
4795 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004796 tv[0].tv_sec = ut->atime_s; \
4797 tv[0].tv_usec = ut->atime_ns / 1000; \
4798 tv[1].tv_sec = ut->mtime_s; \
4799 tv[1].tv_usec = ut->mtime_ns / 1000; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004800 time = tv; \
4801 } \
4802
4803#define UTIME_TO_UTIMBUF \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004804 struct utimbuf u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004805 struct utimbuf *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004806 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004807 time = NULL; \
4808 else { \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004809 u.actime = ut->atime_s; \
4810 u.modtime = ut->mtime_s; \
4811 time = &u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004812 }
4813
4814#define UTIME_TO_TIME_T \
4815 time_t timet[2]; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004816 time_t *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004817 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004818 time = NULL; \
4819 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004820 timet[0] = ut->atime_s; \
4821 timet[1] = ut->mtime_s; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004822 time = timet; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004823 } \
4824
4825
Victor Stinner528a9ab2015-09-03 21:30:26 +02004826#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004827
4828static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004829utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004830{
4831#ifdef HAVE_UTIMENSAT
4832 int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
4833 UTIME_TO_TIMESPEC;
4834 return utimensat(dir_fd, path, time, flags);
4835#elif defined(HAVE_FUTIMESAT)
4836 UTIME_TO_TIMEVAL;
4837 /*
4838 * follow_symlinks will never be false here;
4839 * we only allow !follow_symlinks and dir_fd together
4840 * if we have utimensat()
4841 */
4842 assert(follow_symlinks);
4843 return futimesat(dir_fd, path, time);
4844#endif
4845}
4846
Larry Hastings2f936352014-08-05 14:04:04 +10004847 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
4848#else
4849 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings9cf065c2012-06-22 16:30:09 -07004850#endif
4851
Victor Stinner528a9ab2015-09-03 21:30:26 +02004852#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004853
4854static int
Victor Stinner484df002014-10-09 13:52:31 +02004855utime_fd(utime_t *ut, int fd)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004856{
4857#ifdef HAVE_FUTIMENS
4858 UTIME_TO_TIMESPEC;
4859 return futimens(fd, time);
4860#else
4861 UTIME_TO_TIMEVAL;
4862 return futimes(fd, time);
4863#endif
4864}
4865
Larry Hastings2f936352014-08-05 14:04:04 +10004866 #define PATH_UTIME_HAVE_FD 1
4867#else
4868 #define PATH_UTIME_HAVE_FD 0
Larry Hastings9cf065c2012-06-22 16:30:09 -07004869#endif
4870
Victor Stinner5ebae872015-09-22 01:29:33 +02004871#if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
4872# define UTIME_HAVE_NOFOLLOW_SYMLINKS
4873#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004874
Victor Stinner4552ced2015-09-21 22:37:15 +02004875#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004876
4877static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004878utime_nofollow_symlinks(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004879{
4880#ifdef HAVE_UTIMENSAT
4881 UTIME_TO_TIMESPEC;
4882 return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
4883#else
4884 UTIME_TO_TIMEVAL;
4885 return lutimes(path, time);
4886#endif
4887}
4888
4889#endif
4890
4891#ifndef MS_WINDOWS
4892
4893static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004894utime_default(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004895{
4896#ifdef HAVE_UTIMENSAT
4897 UTIME_TO_TIMESPEC;
4898 return utimensat(DEFAULT_DIR_FD, path, time, 0);
4899#elif defined(HAVE_UTIMES)
4900 UTIME_TO_TIMEVAL;
4901 return utimes(path, time);
4902#elif defined(HAVE_UTIME_H)
4903 UTIME_TO_UTIMBUF;
4904 return utime(path, time);
4905#else
4906 UTIME_TO_TIME_T;
4907 return utime(path, time);
4908#endif
4909}
4910
4911#endif
4912
Larry Hastings76ad59b2012-05-03 00:30:07 -07004913static int
Victor Stinner1c2fa782020-05-10 11:05:29 +02004914split_py_long_to_s_and_ns(PyObject *module, PyObject *py_long, time_t *s, long *ns)
Larry Hastings76ad59b2012-05-03 00:30:07 -07004915{
4916 int result = 0;
Benjamin Petersonfbd85a02012-05-04 11:06:09 -04004917 PyObject *divmod;
Victor Stinner1c2fa782020-05-10 11:05:29 +02004918 divmod = PyNumber_Divmod(py_long, get_posix_state(module)->billion);
Larry Hastings76ad59b2012-05-03 00:30:07 -07004919 if (!divmod)
4920 goto exit;
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004921 if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
4922 PyErr_Format(PyExc_TypeError,
4923 "%.200s.__divmod__() must return a 2-tuple, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -08004924 _PyType_Name(Py_TYPE(py_long)), _PyType_Name(Py_TYPE(divmod)));
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004925 goto exit;
4926 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004927 *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
4928 if ((*s == -1) && PyErr_Occurred())
4929 goto exit;
4930 *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
Benjamin Peterson35a8f0d2012-05-04 01:10:59 -04004931 if ((*ns == -1) && PyErr_Occurred())
Larry Hastings76ad59b2012-05-03 00:30:07 -07004932 goto exit;
4933
4934 result = 1;
4935exit:
4936 Py_XDECREF(divmod);
4937 return result;
4938}
4939
Larry Hastings2f936352014-08-05 14:04:04 +10004940
4941/*[clinic input]
4942os.utime
4943
4944 path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004945 times: object = None
Larry Hastings2f936352014-08-05 14:04:04 +10004946 *
4947 ns: object = NULL
4948 dir_fd: dir_fd(requires='futimensat') = None
4949 follow_symlinks: bool=True
4950
Martin Panter0ff89092015-09-09 01:56:53 +00004951# "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
Larry Hastings2f936352014-08-05 14:04:04 +10004952
4953Set the access and modified time of path.
4954
4955path may always be specified as a string.
4956On some platforms, path may also be specified as an open file descriptor.
4957 If this functionality is unavailable, using it raises an exception.
4958
4959If times is not None, it must be a tuple (atime, mtime);
4960 atime and mtime should be expressed as float seconds since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004961If ns is specified, it must be a tuple (atime_ns, mtime_ns);
Larry Hastings2f936352014-08-05 14:04:04 +10004962 atime_ns and mtime_ns should be expressed as integer nanoseconds
4963 since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004964If times is None and ns is unspecified, utime uses the current time.
Larry Hastings2f936352014-08-05 14:04:04 +10004965Specifying tuples for both times and ns is an error.
4966
4967If dir_fd is not None, it should be a file descriptor open to a directory,
4968 and path should be relative; path will then be relative to that directory.
4969If follow_symlinks is False, and the last element of the path is a symbolic
4970 link, utime will modify the symbolic link itself instead of the file the
4971 link points to.
4972It is an error to use dir_fd or follow_symlinks when specifying path
4973 as an open file descriptor.
4974dir_fd and follow_symlinks may not be available on your platform.
4975 If they are unavailable, using them will raise a NotImplementedError.
4976
4977[clinic start generated code]*/
4978
Larry Hastings2f936352014-08-05 14:04:04 +10004979static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004980os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
4981 int dir_fd, int follow_symlinks)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004982/*[clinic end generated code: output=cfcac69d027b82cf input=2fbd62a2f228f8f4]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004983{
Larry Hastings9cf065c2012-06-22 16:30:09 -07004984#ifdef MS_WINDOWS
4985 HANDLE hFile;
4986 FILETIME atime, mtime;
4987#else
4988 int result;
4989#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004990
Larry Hastings2f936352014-08-05 14:04:04 +10004991 utime_t utime;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004992
Christian Heimesb3c87242013-08-01 00:08:16 +02004993 memset(&utime, 0, sizeof(utime_t));
Larry Hastings76ad59b2012-05-03 00:30:07 -07004994
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004995 if (times != Py_None && ns) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004996 PyErr_SetString(PyExc_ValueError,
4997 "utime: you may specify either 'times'"
4998 " or 'ns' but not both");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004999 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07005000 }
5001
Serhiy Storchaka279f4462019-09-14 12:24:05 +03005002 if (times != Py_None) {
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02005003 time_t a_sec, m_sec;
5004 long a_nsec, m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07005005 if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07005006 PyErr_SetString(PyExc_TypeError,
5007 "utime: 'times' must be either"
5008 " a tuple of two ints or None");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005009 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07005010 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07005011 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04005012 if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
Victor Stinnerdca028b2015-03-30 01:02:57 +02005013 &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04005014 _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
Victor Stinnerdca028b2015-03-30 01:02:57 +02005015 &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005016 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07005017 }
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02005018 utime.atime_s = a_sec;
5019 utime.atime_ns = a_nsec;
5020 utime.mtime_s = m_sec;
5021 utime.mtime_ns = m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07005022 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07005023 else if (ns) {
Larry Hastings76ad59b2012-05-03 00:30:07 -07005024 if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07005025 PyErr_SetString(PyExc_TypeError,
5026 "utime: 'ns' must be a tuple of two ints");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005027 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07005028 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07005029 utime.now = 0;
Victor Stinner1c2fa782020-05-10 11:05:29 +02005030 if (!split_py_long_to_s_and_ns(module, PyTuple_GET_ITEM(ns, 0),
Larry Hastings9cf065c2012-06-22 16:30:09 -07005031 &utime.atime_s, &utime.atime_ns) ||
Victor Stinner1c2fa782020-05-10 11:05:29 +02005032 !split_py_long_to_s_and_ns(module, PyTuple_GET_ITEM(ns, 1),
Larry Hastings9cf065c2012-06-22 16:30:09 -07005033 &utime.mtime_s, &utime.mtime_ns)) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005034 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07005035 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07005036 }
5037 else {
5038 /* times and ns are both None/unspecified. use "now". */
5039 utime.now = 1;
Larry Hastings76ad59b2012-05-03 00:30:07 -07005040 }
5041
Victor Stinner4552ced2015-09-21 22:37:15 +02005042#if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07005043 if (follow_symlinks_specified("utime", follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005044 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07005045#endif
Benjamin Petersonb399ab22012-05-04 01:31:13 -04005046
Larry Hastings2f936352014-08-05 14:04:04 +10005047 if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
5048 dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
5049 fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005050 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07005051
Larry Hastings9cf065c2012-06-22 16:30:09 -07005052#if !defined(HAVE_UTIMENSAT)
5053 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
Georg Brandl969288e2012-06-26 09:25:44 +02005054 PyErr_SetString(PyExc_ValueError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005055 "utime: cannot use dir_fd and follow_symlinks "
5056 "together on this platform");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005057 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07005058 }
5059#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07005060
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005061 if (PySys_Audit("os.utime", "OOOi", path->object, times, ns ? ns : Py_None,
5062 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
5063 return NULL;
5064 }
5065
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00005066#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07005067 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07005068 hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
5069 NULL, OPEN_EXISTING,
5070 FILE_FLAG_BACKUP_SEMANTICS, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005071 Py_END_ALLOW_THREADS
5072 if (hFile == INVALID_HANDLE_VALUE) {
Larry Hastings2f936352014-08-05 14:04:04 +10005073 path_error(path);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005074 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07005075 }
5076
Larry Hastings9cf065c2012-06-22 16:30:09 -07005077 if (utime.now) {
Antoine Pitrou91a7af32013-11-23 15:23:26 +01005078 GetSystemTimeAsFileTime(&mtime);
5079 atime = mtime;
Victor Stinner8c62be82010-05-06 00:08:46 +00005080 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005081 else {
Steve Dowerbf1f3762015-02-21 15:26:02 -08005082 _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
5083 _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
Victor Stinner8c62be82010-05-06 00:08:46 +00005084 }
5085 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
5086 /* Avoid putting the file name into the error here,
5087 as that may confuse the user into believing that
5088 something is wrong with the file, when it also
5089 could be the time stamp that gives a problem. */
Victor Stinnerb024e842012-10-31 22:24:06 +01005090 PyErr_SetFromWindowsErr(0);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005091 CloseHandle(hFile);
5092 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00005093 }
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005094 CloseHandle(hFile);
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00005095#else /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07005096 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00005097
Victor Stinner4552ced2015-09-21 22:37:15 +02005098#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07005099 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10005100 result = utime_nofollow_symlinks(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005101 else
Larry Hastings9e3e70b2011-09-08 19:29:07 -07005102#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07005103
Victor Stinner528a9ab2015-09-03 21:30:26 +02005104#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07005105 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10005106 result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005107 else
5108#endif
5109
Victor Stinner528a9ab2015-09-03 21:30:26 +02005110#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings2f936352014-08-05 14:04:04 +10005111 if (path->fd != -1)
5112 result = utime_fd(&utime, path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005113 else
5114#endif
5115
Larry Hastings2f936352014-08-05 14:04:04 +10005116 result = utime_default(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005117
5118 Py_END_ALLOW_THREADS
5119
5120 if (result < 0) {
5121 /* see previous comment about not putting filename in error here */
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005122 posix_error();
5123 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00005124 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07005125
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00005126#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07005127
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005128 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005129}
5130
Guido van Rossum3b066191991-06-04 19:40:25 +00005131/* Process operations */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005132
Larry Hastings2f936352014-08-05 14:04:04 +10005133
5134/*[clinic input]
5135os._exit
5136
5137 status: int
5138
5139Exit to the system with specified status, without normal exit processing.
5140[clinic start generated code]*/
5141
Larry Hastings2f936352014-08-05 14:04:04 +10005142static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005143os__exit_impl(PyObject *module, int status)
5144/*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005145{
5146 _exit(status);
Victor Stinner8c62be82010-05-06 00:08:46 +00005147 return NULL; /* Make gcc -Wall happy */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005148}
5149
Steve Dowercc16be82016-09-08 10:35:16 -07005150#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5151#define EXECV_CHAR wchar_t
5152#else
5153#define EXECV_CHAR char
5154#endif
5155
pxinwrf2d7ac72019-05-21 18:46:37 +08005156#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005157static void
Steve Dowercc16be82016-09-08 10:35:16 -07005158free_string_array(EXECV_CHAR **array, Py_ssize_t count)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005159{
Victor Stinner8c62be82010-05-06 00:08:46 +00005160 Py_ssize_t i;
5161 for (i = 0; i < count; i++)
5162 PyMem_Free(array[i]);
5163 PyMem_DEL(array);
Martin v. Löwis114619e2002-10-07 06:44:21 +00005164}
Martin v. Löwis011e8422009-05-05 04:43:17 +00005165
Berker Peksag81816462016-09-15 20:19:47 +03005166static int
5167fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
Martin v. Löwis011e8422009-05-05 04:43:17 +00005168{
Victor Stinner8c62be82010-05-06 00:08:46 +00005169 Py_ssize_t size;
Berker Peksag81816462016-09-15 20:19:47 +03005170 PyObject *ub;
5171 int result = 0;
Steve Dowercc16be82016-09-08 10:35:16 -07005172#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
Berker Peksag81816462016-09-15 20:19:47 +03005173 if (!PyUnicode_FSDecoder(o, &ub))
Steve Dowercc16be82016-09-08 10:35:16 -07005174 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005175 *out = PyUnicode_AsWideCharString(ub, &size);
5176 if (*out)
5177 result = 1;
Steve Dowercc16be82016-09-08 10:35:16 -07005178#else
Berker Peksag81816462016-09-15 20:19:47 +03005179 if (!PyUnicode_FSConverter(o, &ub))
Victor Stinner8c62be82010-05-06 00:08:46 +00005180 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005181 size = PyBytes_GET_SIZE(ub);
5182 *out = PyMem_Malloc(size + 1);
5183 if (*out) {
5184 memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
5185 result = 1;
5186 } else
Victor Stinner50abf222013-11-07 23:56:10 +01005187 PyErr_NoMemory();
Steve Dowercc16be82016-09-08 10:35:16 -07005188#endif
Berker Peksag81816462016-09-15 20:19:47 +03005189 Py_DECREF(ub);
5190 return result;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005191}
Martin v. Löwis114619e2002-10-07 06:44:21 +00005192#endif
5193
pxinwrf2d7ac72019-05-21 18:46:37 +08005194#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
Steve Dowercc16be82016-09-08 10:35:16 -07005195static EXECV_CHAR**
Victor Stinner13bb71c2010-04-23 21:41:56 +00005196parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
5197{
Victor Stinner8c62be82010-05-06 00:08:46 +00005198 Py_ssize_t i, pos, envc;
5199 PyObject *keys=NULL, *vals=NULL;
Berker Peksag81816462016-09-15 20:19:47 +03005200 PyObject *key, *val, *key2, *val2, *keyval;
Steve Dowercc16be82016-09-08 10:35:16 -07005201 EXECV_CHAR **envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005202
Victor Stinner8c62be82010-05-06 00:08:46 +00005203 i = PyMapping_Size(env);
5204 if (i < 0)
5205 return NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07005206 envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005207 if (envlist == NULL) {
5208 PyErr_NoMemory();
5209 return NULL;
5210 }
5211 envc = 0;
5212 keys = PyMapping_Keys(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005213 if (!keys)
5214 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00005215 vals = PyMapping_Values(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005216 if (!vals)
Victor Stinner8c62be82010-05-06 00:08:46 +00005217 goto error;
5218 if (!PyList_Check(keys) || !PyList_Check(vals)) {
5219 PyErr_Format(PyExc_TypeError,
5220 "env.keys() or env.values() is not a list");
5221 goto error;
5222 }
Victor Stinner13bb71c2010-04-23 21:41:56 +00005223
Victor Stinner8c62be82010-05-06 00:08:46 +00005224 for (pos = 0; pos < i; pos++) {
5225 key = PyList_GetItem(keys, pos);
5226 val = PyList_GetItem(vals, pos);
5227 if (!key || !val)
5228 goto error;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005229
Berker Peksag81816462016-09-15 20:19:47 +03005230#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5231 if (!PyUnicode_FSDecoder(key, &key2))
5232 goto error;
5233 if (!PyUnicode_FSDecoder(val, &val2)) {
5234 Py_DECREF(key2);
5235 goto error;
5236 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005237 /* Search from index 1 because on Windows starting '=' is allowed for
5238 defining hidden environment variables. */
5239 if (PyUnicode_GET_LENGTH(key2) == 0 ||
5240 PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
5241 {
5242 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005243 Py_DECREF(key2);
5244 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005245 goto error;
5246 }
Berker Peksag81816462016-09-15 20:19:47 +03005247 keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
5248#else
5249 if (!PyUnicode_FSConverter(key, &key2))
5250 goto error;
5251 if (!PyUnicode_FSConverter(val, &val2)) {
5252 Py_DECREF(key2);
5253 goto error;
5254 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005255 if (PyBytes_GET_SIZE(key2) == 0 ||
5256 strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
5257 {
5258 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005259 Py_DECREF(key2);
5260 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005261 goto error;
5262 }
Berker Peksag81816462016-09-15 20:19:47 +03005263 keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
5264 PyBytes_AS_STRING(val2));
5265#endif
5266 Py_DECREF(key2);
5267 Py_DECREF(val2);
Steve Dowercc16be82016-09-08 10:35:16 -07005268 if (!keyval)
Victor Stinner8c62be82010-05-06 00:08:46 +00005269 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -07005270
5271 if (!fsconvert_strdup(keyval, &envlist[envc++])) {
5272 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005273 goto error;
5274 }
Berker Peksag81816462016-09-15 20:19:47 +03005275
Steve Dowercc16be82016-09-08 10:35:16 -07005276 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005277 }
5278 Py_DECREF(vals);
5279 Py_DECREF(keys);
Victor Stinner13bb71c2010-04-23 21:41:56 +00005280
Victor Stinner8c62be82010-05-06 00:08:46 +00005281 envlist[envc] = 0;
5282 *envc_ptr = envc;
5283 return envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005284
5285error:
Victor Stinner8c62be82010-05-06 00:08:46 +00005286 Py_XDECREF(keys);
5287 Py_XDECREF(vals);
Steve Dowercc16be82016-09-08 10:35:16 -07005288 free_string_array(envlist, envc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005289 return NULL;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005290}
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005291
Steve Dowercc16be82016-09-08 10:35:16 -07005292static EXECV_CHAR**
Ross Lagerwall7807c352011-03-17 20:20:30 +02005293parse_arglist(PyObject* argv, Py_ssize_t *argc)
5294{
5295 int i;
Steve Dowercc16be82016-09-08 10:35:16 -07005296 EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005297 if (argvlist == NULL) {
5298 PyErr_NoMemory();
5299 return NULL;
5300 }
5301 for (i = 0; i < *argc; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005302 PyObject* item = PySequence_ITEM(argv, i);
5303 if (item == NULL)
5304 goto fail;
5305 if (!fsconvert_strdup(item, &argvlist[i])) {
5306 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005307 goto fail;
5308 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005309 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005310 }
5311 argvlist[*argc] = NULL;
5312 return argvlist;
5313fail:
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005314 *argc = i;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005315 free_string_array(argvlist, *argc);
5316 return NULL;
5317}
Steve Dowercc16be82016-09-08 10:35:16 -07005318
Ross Lagerwall7807c352011-03-17 20:20:30 +02005319#endif
5320
Larry Hastings2f936352014-08-05 14:04:04 +10005321
Ross Lagerwall7807c352011-03-17 20:20:30 +02005322#ifdef HAVE_EXECV
Larry Hastings2f936352014-08-05 14:04:04 +10005323/*[clinic input]
5324os.execv
5325
Steve Dowercc16be82016-09-08 10:35:16 -07005326 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005327 Path of executable file.
5328 argv: object
5329 Tuple or list of strings.
5330 /
5331
5332Execute an executable path with arguments, replacing current process.
5333[clinic start generated code]*/
5334
Larry Hastings2f936352014-08-05 14:04:04 +10005335static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005336os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
5337/*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005338{
Steve Dowercc16be82016-09-08 10:35:16 -07005339 EXECV_CHAR **argvlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005340 Py_ssize_t argc;
5341
5342 /* execv has two arguments: (path, argv), where
5343 argv is a list or tuple of strings. */
5344
Ross Lagerwall7807c352011-03-17 20:20:30 +02005345 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
5346 PyErr_SetString(PyExc_TypeError,
5347 "execv() arg 2 must be a tuple or list");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005348 return NULL;
5349 }
5350 argc = PySequence_Size(argv);
5351 if (argc < 1) {
5352 PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005353 return NULL;
5354 }
5355
5356 argvlist = parse_arglist(argv, &argc);
5357 if (argvlist == NULL) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02005358 return NULL;
5359 }
Steve Dowerbce26262016-11-19 19:17:26 -08005360 if (!argvlist[0][0]) {
5361 PyErr_SetString(PyExc_ValueError,
5362 "execv() arg 2 first element cannot be empty");
5363 free_string_array(argvlist, argc);
5364 return NULL;
5365 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005366
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005367 if (PySys_Audit("os.exec", "OOO", path->object, argv, Py_None) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -08005368 free_string_array(argvlist, argc);
5369 return NULL;
5370 }
5371
Steve Dowerbce26262016-11-19 19:17:26 -08005372 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005373#ifdef HAVE_WEXECV
5374 _wexecv(path->wide, argvlist);
5375#else
5376 execv(path->narrow, argvlist);
5377#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005378 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005379
5380 /* If we get here it's definitely an error */
5381
5382 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005383 return posix_error();
5384}
5385
Larry Hastings2f936352014-08-05 14:04:04 +10005386
5387/*[clinic input]
5388os.execve
5389
5390 path: path_t(allow_fd='PATH_HAVE_FEXECVE')
5391 Path of executable file.
5392 argv: object
5393 Tuple or list of strings.
5394 env: object
5395 Dictionary of strings mapping to strings.
5396
5397Execute an executable path with arguments, replacing current process.
5398[clinic start generated code]*/
5399
Larry Hastings2f936352014-08-05 14:04:04 +10005400static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005401os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
5402/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005403{
Steve Dowercc16be82016-09-08 10:35:16 -07005404 EXECV_CHAR **argvlist = NULL;
5405 EXECV_CHAR **envlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005406 Py_ssize_t argc, envc;
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005407
Victor Stinner8c62be82010-05-06 00:08:46 +00005408 /* execve has three arguments: (path, argv, env), where
5409 argv is a list or tuple of strings and env is a dictionary
5410 like posix.environ. */
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005411
Ross Lagerwall7807c352011-03-17 20:20:30 +02005412 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005413 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005414 "execve: argv must be a tuple or list");
Saiyang Gou95f60012020-02-04 16:15:00 -08005415 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005416 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005417 argc = PySequence_Size(argv);
Steve Dowerbce26262016-11-19 19:17:26 -08005418 if (argc < 1) {
5419 PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
5420 return NULL;
5421 }
5422
Victor Stinner8c62be82010-05-06 00:08:46 +00005423 if (!PyMapping_Check(env)) {
5424 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005425 "execve: environment must be a mapping object");
Saiyang Gou95f60012020-02-04 16:15:00 -08005426 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005427 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005428
Ross Lagerwall7807c352011-03-17 20:20:30 +02005429 argvlist = parse_arglist(argv, &argc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005430 if (argvlist == NULL) {
Saiyang Gou95f60012020-02-04 16:15:00 -08005431 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005432 }
Steve Dowerbce26262016-11-19 19:17:26 -08005433 if (!argvlist[0][0]) {
5434 PyErr_SetString(PyExc_ValueError,
5435 "execve: argv first element cannot be empty");
Saiyang Gou95f60012020-02-04 16:15:00 -08005436 goto fail_0;
Steve Dowerbce26262016-11-19 19:17:26 -08005437 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005438
Victor Stinner8c62be82010-05-06 00:08:46 +00005439 envlist = parse_envlist(env, &envc);
5440 if (envlist == NULL)
Saiyang Gou95f60012020-02-04 16:15:00 -08005441 goto fail_0;
5442
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005443 if (PySys_Audit("os.exec", "OOO", path->object, argv, env) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -08005444 goto fail_1;
5445 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005446
Steve Dowerbce26262016-11-19 19:17:26 -08005447 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07005448#ifdef HAVE_FEXECVE
Larry Hastings2f936352014-08-05 14:04:04 +10005449 if (path->fd > -1)
5450 fexecve(path->fd, argvlist, envlist);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005451 else
5452#endif
Steve Dowercc16be82016-09-08 10:35:16 -07005453#ifdef HAVE_WEXECV
5454 _wexecve(path->wide, argvlist, envlist);
5455#else
Larry Hastings2f936352014-08-05 14:04:04 +10005456 execve(path->narrow, argvlist, envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07005457#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005458 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005459
5460 /* If we get here it's definitely an error */
5461
Alexey Izbyshev83460312018-10-20 03:28:22 +03005462 posix_path_error(path);
Saiyang Gou95f60012020-02-04 16:15:00 -08005463 fail_1:
Steve Dowercc16be82016-09-08 10:35:16 -07005464 free_string_array(envlist, envc);
Saiyang Gou95f60012020-02-04 16:15:00 -08005465 fail_0:
Larry Hastings9cf065c2012-06-22 16:30:09 -07005466 if (argvlist)
5467 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005468 return NULL;
5469}
Steve Dowercc16be82016-09-08 10:35:16 -07005470
Larry Hastings9cf065c2012-06-22 16:30:09 -07005471#endif /* HAVE_EXECV */
5472
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005473#ifdef HAVE_POSIX_SPAWN
5474
5475enum posix_spawn_file_actions_identifier {
5476 POSIX_SPAWN_OPEN,
5477 POSIX_SPAWN_CLOSE,
5478 POSIX_SPAWN_DUP2
5479};
5480
William Orr81574b82018-10-01 22:19:56 -07005481#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005482static int
Victor Stinner1c2fa782020-05-10 11:05:29 +02005483convert_sched_param(PyObject *module, PyObject *param, struct sched_param *res);
William Orr81574b82018-10-01 22:19:56 -07005484#endif
Pablo Galindo254a4662018-09-07 16:44:24 +01005485
5486static int
Victor Stinner1c2fa782020-05-10 11:05:29 +02005487parse_posix_spawn_flags(PyObject *module, const char *func_name, PyObject *setpgroup,
Victor Stinner325e4ba2019-02-01 15:47:24 +01005488 int resetids, int setsid, PyObject *setsigmask,
Pablo Galindo254a4662018-09-07 16:44:24 +01005489 PyObject *setsigdef, PyObject *scheduler,
5490 posix_spawnattr_t *attrp)
5491{
5492 long all_flags = 0;
5493
5494 errno = posix_spawnattr_init(attrp);
5495 if (errno) {
5496 posix_error();
5497 return -1;
5498 }
5499
5500 if (setpgroup) {
5501 pid_t pgid = PyLong_AsPid(setpgroup);
5502 if (pgid == (pid_t)-1 && PyErr_Occurred()) {
5503 goto fail;
5504 }
5505 errno = posix_spawnattr_setpgroup(attrp, pgid);
5506 if (errno) {
5507 posix_error();
5508 goto fail;
5509 }
5510 all_flags |= POSIX_SPAWN_SETPGROUP;
5511 }
5512
5513 if (resetids) {
5514 all_flags |= POSIX_SPAWN_RESETIDS;
5515 }
5516
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005517 if (setsid) {
5518#ifdef POSIX_SPAWN_SETSID
5519 all_flags |= POSIX_SPAWN_SETSID;
5520#elif defined(POSIX_SPAWN_SETSID_NP)
5521 all_flags |= POSIX_SPAWN_SETSID_NP;
5522#else
5523 argument_unavailable_error(func_name, "setsid");
5524 return -1;
5525#endif
5526 }
5527
Pablo Galindo254a4662018-09-07 16:44:24 +01005528 if (setsigmask) {
5529 sigset_t set;
5530 if (!_Py_Sigset_Converter(setsigmask, &set)) {
5531 goto fail;
5532 }
5533 errno = posix_spawnattr_setsigmask(attrp, &set);
5534 if (errno) {
5535 posix_error();
5536 goto fail;
5537 }
5538 all_flags |= POSIX_SPAWN_SETSIGMASK;
5539 }
5540
5541 if (setsigdef) {
5542 sigset_t set;
5543 if (!_Py_Sigset_Converter(setsigdef, &set)) {
5544 goto fail;
5545 }
5546 errno = posix_spawnattr_setsigdefault(attrp, &set);
5547 if (errno) {
5548 posix_error();
5549 goto fail;
5550 }
5551 all_flags |= POSIX_SPAWN_SETSIGDEF;
5552 }
5553
5554 if (scheduler) {
5555#ifdef POSIX_SPAWN_SETSCHEDULER
5556 PyObject *py_schedpolicy;
Victor Stinner1c2fa782020-05-10 11:05:29 +02005557 PyObject *schedparam_obj;
Pablo Galindo254a4662018-09-07 16:44:24 +01005558 struct sched_param schedparam;
5559
Victor Stinner1c2fa782020-05-10 11:05:29 +02005560 if (!PyArg_ParseTuple(scheduler, "OO"
Pablo Galindo254a4662018-09-07 16:44:24 +01005561 ";A scheduler tuple must have two elements",
Victor Stinner1c2fa782020-05-10 11:05:29 +02005562 &py_schedpolicy, &schedparam_obj)) {
5563 goto fail;
5564 }
5565 if (!convert_sched_param(module, schedparam_obj, &schedparam)) {
Pablo Galindo254a4662018-09-07 16:44:24 +01005566 goto fail;
5567 }
5568 if (py_schedpolicy != Py_None) {
5569 int schedpolicy = _PyLong_AsInt(py_schedpolicy);
5570
5571 if (schedpolicy == -1 && PyErr_Occurred()) {
5572 goto fail;
5573 }
5574 errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
5575 if (errno) {
5576 posix_error();
5577 goto fail;
5578 }
5579 all_flags |= POSIX_SPAWN_SETSCHEDULER;
5580 }
5581 errno = posix_spawnattr_setschedparam(attrp, &schedparam);
5582 if (errno) {
5583 posix_error();
5584 goto fail;
5585 }
5586 all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
5587#else
5588 PyErr_SetString(PyExc_NotImplementedError,
5589 "The scheduler option is not supported in this system.");
5590 goto fail;
5591#endif
5592 }
5593
5594 errno = posix_spawnattr_setflags(attrp, all_flags);
5595 if (errno) {
5596 posix_error();
5597 goto fail;
5598 }
5599
5600 return 0;
5601
5602fail:
5603 (void)posix_spawnattr_destroy(attrp);
5604 return -1;
5605}
5606
5607static int
Serhiy Storchakaef347532018-05-01 16:45:04 +03005608parse_file_actions(PyObject *file_actions,
Pablo Galindocb970732018-06-19 09:19:50 +01005609 posix_spawn_file_actions_t *file_actionsp,
5610 PyObject *temp_buffer)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005611{
5612 PyObject *seq;
5613 PyObject *file_action = NULL;
5614 PyObject *tag_obj;
5615
5616 seq = PySequence_Fast(file_actions,
5617 "file_actions must be a sequence or None");
5618 if (seq == NULL) {
5619 return -1;
5620 }
5621
5622 errno = posix_spawn_file_actions_init(file_actionsp);
5623 if (errno) {
5624 posix_error();
5625 Py_DECREF(seq);
5626 return -1;
5627 }
5628
Zackery Spytzd52a83a2019-06-26 14:54:20 -06005629 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
Serhiy Storchakaef347532018-05-01 16:45:04 +03005630 file_action = PySequence_Fast_GET_ITEM(seq, i);
5631 Py_INCREF(file_action);
5632 if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
5633 PyErr_SetString(PyExc_TypeError,
5634 "Each file_actions element must be a non-empty tuple");
5635 goto fail;
5636 }
5637 long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
5638 if (tag == -1 && PyErr_Occurred()) {
5639 goto fail;
5640 }
5641
5642 /* Populate the file_actions object */
5643 switch (tag) {
5644 case POSIX_SPAWN_OPEN: {
5645 int fd, oflag;
5646 PyObject *path;
5647 unsigned long mode;
5648 if (!PyArg_ParseTuple(file_action, "OiO&ik"
5649 ";A open file_action tuple must have 5 elements",
5650 &tag_obj, &fd, PyUnicode_FSConverter, &path,
5651 &oflag, &mode))
5652 {
5653 goto fail;
5654 }
Pablo Galindocb970732018-06-19 09:19:50 +01005655 if (PyList_Append(temp_buffer, path)) {
5656 Py_DECREF(path);
5657 goto fail;
5658 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005659 errno = posix_spawn_file_actions_addopen(file_actionsp,
5660 fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
Pablo Galindocb970732018-06-19 09:19:50 +01005661 Py_DECREF(path);
Serhiy Storchakaef347532018-05-01 16:45:04 +03005662 if (errno) {
5663 posix_error();
5664 goto fail;
5665 }
5666 break;
5667 }
5668 case POSIX_SPAWN_CLOSE: {
5669 int fd;
5670 if (!PyArg_ParseTuple(file_action, "Oi"
5671 ";A close file_action tuple must have 2 elements",
5672 &tag_obj, &fd))
5673 {
5674 goto fail;
5675 }
5676 errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
5677 if (errno) {
5678 posix_error();
5679 goto fail;
5680 }
5681 break;
5682 }
5683 case POSIX_SPAWN_DUP2: {
5684 int fd1, fd2;
5685 if (!PyArg_ParseTuple(file_action, "Oii"
5686 ";A dup2 file_action tuple must have 3 elements",
5687 &tag_obj, &fd1, &fd2))
5688 {
5689 goto fail;
5690 }
5691 errno = posix_spawn_file_actions_adddup2(file_actionsp,
5692 fd1, fd2);
5693 if (errno) {
5694 posix_error();
5695 goto fail;
5696 }
5697 break;
5698 }
5699 default: {
5700 PyErr_SetString(PyExc_TypeError,
5701 "Unknown file_actions identifier");
5702 goto fail;
5703 }
5704 }
5705 Py_DECREF(file_action);
5706 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005707
Serhiy Storchakaef347532018-05-01 16:45:04 +03005708 Py_DECREF(seq);
5709 return 0;
5710
5711fail:
5712 Py_DECREF(seq);
5713 Py_DECREF(file_action);
5714 (void)posix_spawn_file_actions_destroy(file_actionsp);
5715 return -1;
5716}
5717
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005718
5719static PyObject *
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005720py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
5721 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005722 PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005723 PyObject *setsigdef, PyObject *scheduler)
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005724{
Victor Stinner325e4ba2019-02-01 15:47:24 +01005725 const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005726 EXECV_CHAR **argvlist = NULL;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005727 EXECV_CHAR **envlist = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005728 posix_spawn_file_actions_t file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005729 posix_spawn_file_actions_t *file_actionsp = NULL;
Pablo Galindo254a4662018-09-07 16:44:24 +01005730 posix_spawnattr_t attr;
5731 posix_spawnattr_t *attrp = NULL;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005732 Py_ssize_t argc, envc;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005733 PyObject *result = NULL;
Pablo Galindocb970732018-06-19 09:19:50 +01005734 PyObject *temp_buffer = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005735 pid_t pid;
5736 int err_code;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005737
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005738 /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
Serhiy Storchakaef347532018-05-01 16:45:04 +03005739 argv is a list or tuple of strings and env is a dictionary
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005740 like posix.environ. */
5741
Serhiy Storchakaef347532018-05-01 16:45:04 +03005742 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005743 PyErr_Format(PyExc_TypeError,
5744 "%s: argv must be a tuple or list", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005745 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005746 }
5747 argc = PySequence_Size(argv);
5748 if (argc < 1) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005749 PyErr_Format(PyExc_ValueError,
5750 "%s: argv must not be empty", func_name);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005751 return NULL;
5752 }
5753
5754 if (!PyMapping_Check(env)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005755 PyErr_Format(PyExc_TypeError,
5756 "%s: environment must be a mapping object", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005757 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005758 }
5759
5760 argvlist = parse_arglist(argv, &argc);
5761 if (argvlist == NULL) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005762 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005763 }
5764 if (!argvlist[0][0]) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005765 PyErr_Format(PyExc_ValueError,
5766 "%s: argv first element cannot be empty", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005767 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005768 }
5769
5770 envlist = parse_envlist(env, &envc);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005771 if (envlist == NULL) {
5772 goto exit;
5773 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005774
Anthony Shaw948ed8c2019-05-10 12:00:06 +10005775 if (file_actions != NULL && file_actions != Py_None) {
Pablo Galindocb970732018-06-19 09:19:50 +01005776 /* There is a bug in old versions of glibc that makes some of the
5777 * helper functions for manipulating file actions not copy the provided
5778 * buffers. The problem is that posix_spawn_file_actions_addopen does not
5779 * copy the value of path for some old versions of glibc (<2.20).
5780 * The use of temp_buffer here is a workaround that keeps the
5781 * python objects that own the buffers alive until posix_spawn gets called.
5782 * Check https://bugs.python.org/issue33630 and
5783 * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
5784 temp_buffer = PyList_New(0);
5785 if (!temp_buffer) {
5786 goto exit;
5787 }
5788 if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005789 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005790 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005791 file_actionsp = &file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005792 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005793
Victor Stinner1c2fa782020-05-10 11:05:29 +02005794 if (parse_posix_spawn_flags(module, func_name, setpgroup, resetids, setsid,
Victor Stinner325e4ba2019-02-01 15:47:24 +01005795 setsigmask, setsigdef, scheduler, &attr)) {
Pablo Galindo254a4662018-09-07 16:44:24 +01005796 goto exit;
5797 }
5798 attrp = &attr;
5799
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005800 if (PySys_Audit("os.posix_spawn", "OOO", path->object, argv, env) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -08005801 goto exit;
5802 }
5803
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005804 _Py_BEGIN_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005805#ifdef HAVE_POSIX_SPAWNP
5806 if (use_posix_spawnp) {
5807 err_code = posix_spawnp(&pid, path->narrow,
5808 file_actionsp, attrp, argvlist, envlist);
5809 }
5810 else
5811#endif /* HAVE_POSIX_SPAWNP */
5812 {
5813 err_code = posix_spawn(&pid, path->narrow,
5814 file_actionsp, attrp, argvlist, envlist);
5815 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005816 _Py_END_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005817
Serhiy Storchakaef347532018-05-01 16:45:04 +03005818 if (err_code) {
5819 errno = err_code;
5820 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005821 goto exit;
5822 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08005823#ifdef _Py_MEMORY_SANITIZER
5824 __msan_unpoison(&pid, sizeof(pid));
5825#endif
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005826 result = PyLong_FromPid(pid);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005827
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005828exit:
Serhiy Storchakaef347532018-05-01 16:45:04 +03005829 if (file_actionsp) {
5830 (void)posix_spawn_file_actions_destroy(file_actionsp);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005831 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005832 if (attrp) {
5833 (void)posix_spawnattr_destroy(attrp);
5834 }
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005835 if (envlist) {
5836 free_string_array(envlist, envc);
5837 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005838 if (argvlist) {
5839 free_string_array(argvlist, argc);
5840 }
Pablo Galindocb970732018-06-19 09:19:50 +01005841 Py_XDECREF(temp_buffer);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005842 return result;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005843}
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005844
5845
5846/*[clinic input]
5847
5848os.posix_spawn
5849 path: path_t
5850 Path of executable file.
5851 argv: object
5852 Tuple or list of strings.
5853 env: object
5854 Dictionary of strings mapping to strings.
5855 /
5856 *
5857 file_actions: object(c_default='NULL') = ()
5858 A sequence of file action tuples.
5859 setpgroup: object = NULL
5860 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5861 resetids: bool(accept={int}) = False
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005862 If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
5863 setsid: bool(accept={int}) = False
5864 If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005865 setsigmask: object(c_default='NULL') = ()
5866 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5867 setsigdef: object(c_default='NULL') = ()
5868 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5869 scheduler: object = NULL
5870 A tuple with the scheduler policy (optional) and parameters.
5871
5872Execute the program specified by path in a new process.
5873[clinic start generated code]*/
5874
5875static PyObject *
5876os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
5877 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005878 PyObject *setpgroup, int resetids, int setsid,
5879 PyObject *setsigmask, PyObject *setsigdef,
5880 PyObject *scheduler)
5881/*[clinic end generated code: output=14a1098c566bc675 input=8c6305619a00ad04]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005882{
5883 return py_posix_spawn(0, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005884 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005885 scheduler);
5886}
5887 #endif /* HAVE_POSIX_SPAWN */
5888
5889
5890
5891#ifdef HAVE_POSIX_SPAWNP
5892/*[clinic input]
5893
5894os.posix_spawnp
5895 path: path_t
5896 Path of executable file.
5897 argv: object
5898 Tuple or list of strings.
5899 env: object
5900 Dictionary of strings mapping to strings.
5901 /
5902 *
5903 file_actions: object(c_default='NULL') = ()
5904 A sequence of file action tuples.
5905 setpgroup: object = NULL
5906 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5907 resetids: bool(accept={int}) = False
5908 If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005909 setsid: bool(accept={int}) = False
5910 If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005911 setsigmask: object(c_default='NULL') = ()
5912 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5913 setsigdef: object(c_default='NULL') = ()
5914 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5915 scheduler: object = NULL
5916 A tuple with the scheduler policy (optional) and parameters.
5917
5918Execute the program specified by path in a new process.
5919[clinic start generated code]*/
5920
5921static PyObject *
5922os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
5923 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005924 PyObject *setpgroup, int resetids, int setsid,
5925 PyObject *setsigmask, PyObject *setsigdef,
5926 PyObject *scheduler)
5927/*[clinic end generated code: output=7b9aaefe3031238d input=c1911043a22028da]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005928{
5929 return py_posix_spawn(1, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005930 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005931 scheduler);
5932}
5933#endif /* HAVE_POSIX_SPAWNP */
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005934
pxinwrf2d7ac72019-05-21 18:46:37 +08005935#ifdef HAVE_RTPSPAWN
5936static intptr_t
5937_rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
5938 const char *envp[])
5939{
5940 RTP_ID rtpid;
5941 int status;
5942 pid_t res;
5943 int async_err = 0;
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005944
pxinwrf2d7ac72019-05-21 18:46:37 +08005945 /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
5946 uStackSize=0 cannot be used, the default stack size is too small for
5947 Python. */
5948 if (envp) {
5949 rtpid = rtpSpawn(rtpFileName, argv, envp,
5950 100, 0x1000000, 0, VX_FP_TASK);
5951 }
5952 else {
5953 rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
5954 100, 0x1000000, 0, VX_FP_TASK);
5955 }
5956 if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
5957 do {
5958 res = waitpid((pid_t)rtpid, &status, 0);
5959 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
5960
5961 if (res < 0)
5962 return RTP_ID_ERROR;
5963 return ((intptr_t)status);
5964 }
5965 return ((intptr_t)rtpid);
5966}
5967#endif
5968
5969#if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
Larry Hastings2f936352014-08-05 14:04:04 +10005970/*[clinic input]
5971os.spawnv
5972
5973 mode: int
5974 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005975 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005976 Path of executable file.
5977 argv: object
5978 Tuple or list of strings.
5979 /
5980
5981Execute the program specified by path in a new process.
5982[clinic start generated code]*/
5983
Larry Hastings2f936352014-08-05 14:04:04 +10005984static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005985os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
5986/*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005987{
Steve Dowercc16be82016-09-08 10:35:16 -07005988 EXECV_CHAR **argvlist;
Larry Hastings2f936352014-08-05 14:04:04 +10005989 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00005990 Py_ssize_t argc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005991 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005992 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Guido van Rossuma1065681999-01-25 23:20:23 +00005993
Victor Stinner8c62be82010-05-06 00:08:46 +00005994 /* spawnv has three arguments: (mode, path, argv), where
5995 argv is a list or tuple of strings. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005996
Victor Stinner8c62be82010-05-06 00:08:46 +00005997 if (PyList_Check(argv)) {
5998 argc = PyList_Size(argv);
5999 getitem = PyList_GetItem;
6000 }
6001 else if (PyTuple_Check(argv)) {
6002 argc = PyTuple_Size(argv);
6003 getitem = PyTuple_GetItem;
6004 }
6005 else {
6006 PyErr_SetString(PyExc_TypeError,
6007 "spawnv() arg 2 must be a tuple or list");
Victor Stinner8c62be82010-05-06 00:08:46 +00006008 return NULL;
6009 }
Steve Dower859fd7b2016-11-19 18:53:19 -08006010 if (argc == 0) {
6011 PyErr_SetString(PyExc_ValueError,
6012 "spawnv() arg 2 cannot be empty");
6013 return NULL;
6014 }
Guido van Rossuma1065681999-01-25 23:20:23 +00006015
Steve Dowercc16be82016-09-08 10:35:16 -07006016 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00006017 if (argvlist == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00006018 return PyErr_NoMemory();
6019 }
6020 for (i = 0; i < argc; i++) {
6021 if (!fsconvert_strdup((*getitem)(argv, i),
6022 &argvlist[i])) {
6023 free_string_array(argvlist, i);
6024 PyErr_SetString(
6025 PyExc_TypeError,
6026 "spawnv() arg 2 must contain only strings");
Victor Stinner8c62be82010-05-06 00:08:46 +00006027 return NULL;
6028 }
Steve Dower93ff8722016-11-19 19:03:54 -08006029 if (i == 0 && !argvlist[0][0]) {
Victor Stinner8acb4cf2017-06-15 15:30:40 +02006030 free_string_array(argvlist, i + 1);
Steve Dower93ff8722016-11-19 19:03:54 -08006031 PyErr_SetString(
6032 PyExc_ValueError,
6033 "spawnv() arg 2 first element cannot be empty");
6034 return NULL;
6035 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006036 }
6037 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00006038
pxinwrf2d7ac72019-05-21 18:46:37 +08006039#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00006040 if (mode == _OLD_P_OVERLAY)
6041 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08006042#endif
Tim Peters5aa91602002-01-30 05:46:57 +00006043
Saiyang Gou7514f4f2020-02-12 23:47:42 -08006044 if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv,
Saiyang Gou95f60012020-02-04 16:15:00 -08006045 Py_None) < 0) {
6046 free_string_array(argvlist, argc);
6047 return NULL;
6048 }
6049
Victor Stinner8c62be82010-05-06 00:08:46 +00006050 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07006051 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07006052#ifdef HAVE_WSPAWNV
6053 spawnval = _wspawnv(mode, path->wide, argvlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08006054#elif defined(HAVE_RTPSPAWN)
6055 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
Steve Dowercc16be82016-09-08 10:35:16 -07006056#else
6057 spawnval = _spawnv(mode, path->narrow, argvlist);
6058#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07006059 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00006060 Py_END_ALLOW_THREADS
Tim Peters5aa91602002-01-30 05:46:57 +00006061
Victor Stinner8c62be82010-05-06 00:08:46 +00006062 free_string_array(argvlist, argc);
Guido van Rossuma1065681999-01-25 23:20:23 +00006063
Victor Stinner8c62be82010-05-06 00:08:46 +00006064 if (spawnval == -1)
6065 return posix_error();
6066 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01006067 return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00006068}
6069
Larry Hastings2f936352014-08-05 14:04:04 +10006070/*[clinic input]
6071os.spawnve
6072
6073 mode: int
6074 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07006075 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10006076 Path of executable file.
6077 argv: object
6078 Tuple or list of strings.
6079 env: object
6080 Dictionary of strings mapping to strings.
6081 /
6082
6083Execute the program specified by path in a new process.
6084[clinic start generated code]*/
6085
Larry Hastings2f936352014-08-05 14:04:04 +10006086static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07006087os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006088 PyObject *env)
Steve Dowercc16be82016-09-08 10:35:16 -07006089/*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006090{
Steve Dowercc16be82016-09-08 10:35:16 -07006091 EXECV_CHAR **argvlist;
6092 EXECV_CHAR **envlist;
Victor Stinner8c62be82010-05-06 00:08:46 +00006093 PyObject *res = NULL;
Antoine Pitrou22e41552010-08-15 18:07:50 +00006094 Py_ssize_t argc, i, envc;
Benjamin Petersonca470632016-09-06 13:47:26 -07006095 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00006096 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006097 Py_ssize_t lastarg = 0;
Guido van Rossuma1065681999-01-25 23:20:23 +00006098
Victor Stinner8c62be82010-05-06 00:08:46 +00006099 /* spawnve has four arguments: (mode, path, argv, env), where
6100 argv is a list or tuple of strings and env is a dictionary
6101 like posix.environ. */
Guido van Rossuma1065681999-01-25 23:20:23 +00006102
Victor Stinner8c62be82010-05-06 00:08:46 +00006103 if (PyList_Check(argv)) {
6104 argc = PyList_Size(argv);
6105 getitem = PyList_GetItem;
6106 }
6107 else if (PyTuple_Check(argv)) {
6108 argc = PyTuple_Size(argv);
6109 getitem = PyTuple_GetItem;
6110 }
6111 else {
6112 PyErr_SetString(PyExc_TypeError,
6113 "spawnve() arg 2 must be a tuple or list");
6114 goto fail_0;
6115 }
Steve Dower859fd7b2016-11-19 18:53:19 -08006116 if (argc == 0) {
6117 PyErr_SetString(PyExc_ValueError,
6118 "spawnve() arg 2 cannot be empty");
6119 goto fail_0;
6120 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006121 if (!PyMapping_Check(env)) {
6122 PyErr_SetString(PyExc_TypeError,
6123 "spawnve() arg 3 must be a mapping object");
6124 goto fail_0;
6125 }
Guido van Rossuma1065681999-01-25 23:20:23 +00006126
Steve Dowercc16be82016-09-08 10:35:16 -07006127 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00006128 if (argvlist == NULL) {
6129 PyErr_NoMemory();
6130 goto fail_0;
6131 }
6132 for (i = 0; i < argc; i++) {
6133 if (!fsconvert_strdup((*getitem)(argv, i),
6134 &argvlist[i]))
6135 {
6136 lastarg = i;
6137 goto fail_1;
6138 }
Steve Dowerbce26262016-11-19 19:17:26 -08006139 if (i == 0 && !argvlist[0][0]) {
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006140 lastarg = i + 1;
Steve Dowerbce26262016-11-19 19:17:26 -08006141 PyErr_SetString(
6142 PyExc_ValueError,
6143 "spawnv() arg 2 first element cannot be empty");
6144 goto fail_1;
6145 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006146 }
6147 lastarg = argc;
6148 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00006149
Victor Stinner8c62be82010-05-06 00:08:46 +00006150 envlist = parse_envlist(env, &envc);
6151 if (envlist == NULL)
6152 goto fail_1;
Guido van Rossuma1065681999-01-25 23:20:23 +00006153
pxinwrf2d7ac72019-05-21 18:46:37 +08006154#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00006155 if (mode == _OLD_P_OVERLAY)
6156 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08006157#endif
Tim Peters25059d32001-12-07 20:35:43 +00006158
Saiyang Gou7514f4f2020-02-12 23:47:42 -08006159 if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv, env) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -08006160 goto fail_2;
6161 }
6162
Victor Stinner8c62be82010-05-06 00:08:46 +00006163 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07006164 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07006165#ifdef HAVE_WSPAWNV
6166 spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08006167#elif defined(HAVE_RTPSPAWN)
6168 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
6169 (const char **)envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07006170#else
6171 spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
6172#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07006173 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00006174 Py_END_ALLOW_THREADS
Tim Peters25059d32001-12-07 20:35:43 +00006175
Victor Stinner8c62be82010-05-06 00:08:46 +00006176 if (spawnval == -1)
6177 (void) posix_error();
6178 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01006179 res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00006180
Saiyang Gou95f60012020-02-04 16:15:00 -08006181 fail_2:
Victor Stinner8c62be82010-05-06 00:08:46 +00006182 while (--envc >= 0)
6183 PyMem_DEL(envlist[envc]);
6184 PyMem_DEL(envlist);
Guido van Rossum0847c5c2002-12-13 18:36:22 +00006185 fail_1:
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006186 free_string_array(argvlist, lastarg);
Martin v. Löwis114619e2002-10-07 06:44:21 +00006187 fail_0:
Victor Stinner8c62be82010-05-06 00:08:46 +00006188 return res;
Guido van Rossuma1065681999-01-25 23:20:23 +00006189}
Andrew MacIntyre69e18c92004-04-04 07:11:43 +00006190
Guido van Rossuma1065681999-01-25 23:20:23 +00006191#endif /* HAVE_SPAWNV */
6192
6193
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006194#ifdef HAVE_FORK
Gregory P. Smith163468a2017-05-29 10:03:41 -07006195
6196/* Helper function to validate arguments.
6197 Returns 0 on success. non-zero on failure with a TypeError raised.
6198 If obj is non-NULL it must be callable. */
6199static int
6200check_null_or_callable(PyObject *obj, const char* obj_name)
6201{
6202 if (obj && !PyCallable_Check(obj)) {
6203 PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
Eddie Elizondob3966632019-11-05 07:16:14 -08006204 obj_name, _PyType_Name(Py_TYPE(obj)));
Gregory P. Smith163468a2017-05-29 10:03:41 -07006205 return -1;
6206 }
6207 return 0;
6208}
6209
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006210/*[clinic input]
6211os.register_at_fork
6212
Gregory P. Smith163468a2017-05-29 10:03:41 -07006213 *
6214 before: object=NULL
6215 A callable to be called in the parent before the fork() syscall.
6216 after_in_child: object=NULL
6217 A callable to be called in the child after fork().
6218 after_in_parent: object=NULL
6219 A callable to be called in the parent after fork().
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006220
Gregory P. Smith163468a2017-05-29 10:03:41 -07006221Register callables to be called when forking a new process.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006222
Gregory P. Smith163468a2017-05-29 10:03:41 -07006223'before' callbacks are called in reverse order.
6224'after_in_child' and 'after_in_parent' callbacks are called in order.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006225
6226[clinic start generated code]*/
6227
6228static PyObject *
Gregory P. Smith163468a2017-05-29 10:03:41 -07006229os_register_at_fork_impl(PyObject *module, PyObject *before,
6230 PyObject *after_in_child, PyObject *after_in_parent)
6231/*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006232{
6233 PyInterpreterState *interp;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006234
Gregory P. Smith163468a2017-05-29 10:03:41 -07006235 if (!before && !after_in_child && !after_in_parent) {
6236 PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
6237 return NULL;
6238 }
6239 if (check_null_or_callable(before, "before") ||
6240 check_null_or_callable(after_in_child, "after_in_child") ||
6241 check_null_or_callable(after_in_parent, "after_in_parent")) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006242 return NULL;
6243 }
Victor Stinner81a7be32020-04-14 15:14:01 +02006244 interp = _PyInterpreterState_GET();
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006245
Gregory P. Smith163468a2017-05-29 10:03:41 -07006246 if (register_at_forker(&interp->before_forkers, before)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006247 return NULL;
6248 }
Gregory P. Smith163468a2017-05-29 10:03:41 -07006249 if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006250 return NULL;
Gregory P. Smith163468a2017-05-29 10:03:41 -07006251 }
6252 if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
6253 return NULL;
6254 }
6255 Py_RETURN_NONE;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006256}
6257#endif /* HAVE_FORK */
6258
6259
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006260#ifdef HAVE_FORK1
Larry Hastings2f936352014-08-05 14:04:04 +10006261/*[clinic input]
6262os.fork1
6263
6264Fork a child process with a single multiplexed (i.e., not bound) thread.
6265
6266Return 0 to child process and PID of child to parent process.
6267[clinic start generated code]*/
6268
Larry Hastings2f936352014-08-05 14:04:04 +10006269static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006270os_fork1_impl(PyObject *module)
6271/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006272{
Victor Stinner8c62be82010-05-06 00:08:46 +00006273 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006274
Victor Stinner81a7be32020-04-14 15:14:01 +02006275 if (_PyInterpreterState_GET() != PyInterpreterState_Main()) {
Eric Snow59032962018-09-14 14:17:20 -07006276 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6277 return NULL;
6278 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006279 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006280 pid = fork1();
6281 if (pid == 0) {
6282 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006283 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006284 } else {
6285 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006286 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006287 }
6288 if (pid == -1)
6289 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006290 return PyLong_FromPid(pid);
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006291}
Larry Hastings2f936352014-08-05 14:04:04 +10006292#endif /* HAVE_FORK1 */
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006293
6294
Guido van Rossumad0ee831995-03-01 10:34:45 +00006295#ifdef HAVE_FORK
Larry Hastings2f936352014-08-05 14:04:04 +10006296/*[clinic input]
6297os.fork
6298
6299Fork a child process.
6300
6301Return 0 to child process and PID of child to parent process.
6302[clinic start generated code]*/
6303
Larry Hastings2f936352014-08-05 14:04:04 +10006304static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006305os_fork_impl(PyObject *module)
6306/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006307{
Victor Stinner8c62be82010-05-06 00:08:46 +00006308 pid_t pid;
Victor Stinner252346a2020-05-01 11:33:44 +02006309 PyInterpreterState *interp = _PyInterpreterState_GET();
6310 if (interp->config._isolated_interpreter) {
6311 PyErr_SetString(PyExc_RuntimeError,
6312 "fork not supported for isolated subinterpreters");
Eric Snow59032962018-09-14 14:17:20 -07006313 return NULL;
6314 }
Saiyang Gou7514f4f2020-02-12 23:47:42 -08006315 if (PySys_Audit("os.fork", NULL) < 0) {
6316 return NULL;
6317 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006318 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006319 pid = fork();
6320 if (pid == 0) {
6321 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006322 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006323 } else {
6324 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006325 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006326 }
6327 if (pid == -1)
6328 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006329 return PyLong_FromPid(pid);
Guido van Rossum85e3b011991-06-03 12:42:10 +00006330}
Larry Hastings2f936352014-08-05 14:04:04 +10006331#endif /* HAVE_FORK */
6332
Guido van Rossum85e3b011991-06-03 12:42:10 +00006333
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006334#ifdef HAVE_SCHED_H
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006335#ifdef HAVE_SCHED_GET_PRIORITY_MAX
Larry Hastings2f936352014-08-05 14:04:04 +10006336/*[clinic input]
6337os.sched_get_priority_max
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006338
Larry Hastings2f936352014-08-05 14:04:04 +10006339 policy: int
6340
6341Get the maximum scheduling priority for policy.
6342[clinic start generated code]*/
6343
Larry Hastings2f936352014-08-05 14:04:04 +10006344static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006345os_sched_get_priority_max_impl(PyObject *module, int policy)
6346/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006347{
6348 int max;
6349
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006350 max = sched_get_priority_max(policy);
6351 if (max < 0)
6352 return posix_error();
6353 return PyLong_FromLong(max);
6354}
6355
Larry Hastings2f936352014-08-05 14:04:04 +10006356
6357/*[clinic input]
6358os.sched_get_priority_min
6359
6360 policy: int
6361
6362Get the minimum scheduling priority for policy.
6363[clinic start generated code]*/
6364
Larry Hastings2f936352014-08-05 14:04:04 +10006365static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006366os_sched_get_priority_min_impl(PyObject *module, int policy)
6367/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006368{
6369 int min = sched_get_priority_min(policy);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006370 if (min < 0)
6371 return posix_error();
6372 return PyLong_FromLong(min);
6373}
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006374#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
6375
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006376
Larry Hastings2f936352014-08-05 14:04:04 +10006377#ifdef HAVE_SCHED_SETSCHEDULER
6378/*[clinic input]
6379os.sched_getscheduler
6380 pid: pid_t
6381 /
6382
Min ho Kimc4cacc82019-07-31 08:16:13 +10006383Get the scheduling policy for the process identified by pid.
Larry Hastings2f936352014-08-05 14:04:04 +10006384
6385Passing 0 for pid returns the scheduling policy for the calling process.
6386[clinic start generated code]*/
6387
Larry Hastings2f936352014-08-05 14:04:04 +10006388static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006389os_sched_getscheduler_impl(PyObject *module, pid_t pid)
Min ho Kimc4cacc82019-07-31 08:16:13 +10006390/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=8d99dac505485ac8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006391{
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006392 int policy;
6393
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006394 policy = sched_getscheduler(pid);
6395 if (policy < 0)
6396 return posix_error();
6397 return PyLong_FromLong(policy);
6398}
Larry Hastings2f936352014-08-05 14:04:04 +10006399#endif /* HAVE_SCHED_SETSCHEDULER */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006400
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006401
William Orr81574b82018-10-01 22:19:56 -07006402#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Larry Hastings2f936352014-08-05 14:04:04 +10006403/*[clinic input]
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006404class os.sched_param "PyObject *" "SchedParamType"
Larry Hastings2f936352014-08-05 14:04:04 +10006405
6406@classmethod
6407os.sched_param.__new__
6408
6409 sched_priority: object
6410 A scheduling parameter.
6411
Eddie Elizondob3966632019-11-05 07:16:14 -08006412Currently has only one field: sched_priority
Larry Hastings2f936352014-08-05 14:04:04 +10006413[clinic start generated code]*/
6414
Larry Hastings2f936352014-08-05 14:04:04 +10006415static PyObject *
6416os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
Eddie Elizondob3966632019-11-05 07:16:14 -08006417/*[clinic end generated code: output=48f4067d60f48c13 input=eb42909a2c0e3e6c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006418{
6419 PyObject *res;
6420
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006421 res = PyStructSequence_New(type);
6422 if (!res)
6423 return NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10006424 Py_INCREF(sched_priority);
6425 PyStructSequence_SET_ITEM(res, 0, sched_priority);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006426 return res;
6427}
6428
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03006429PyDoc_VAR(os_sched_param__doc__);
6430
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006431static PyStructSequence_Field sched_param_fields[] = {
6432 {"sched_priority", "the scheduling priority"},
6433 {0}
6434};
6435
6436static PyStructSequence_Desc sched_param_desc = {
6437 "sched_param", /* name */
Larry Hastings2f936352014-08-05 14:04:04 +10006438 os_sched_param__doc__, /* doc */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006439 sched_param_fields,
6440 1
6441};
6442
6443static int
Victor Stinner1c2fa782020-05-10 11:05:29 +02006444convert_sched_param(PyObject *module, PyObject *param, struct sched_param *res)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006445{
6446 long priority;
6447
Victor Stinner1c2fa782020-05-10 11:05:29 +02006448 if (!Py_IS_TYPE(param, (PyTypeObject *)get_posix_state(module)->SchedParamType)) {
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006449 PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
6450 return 0;
6451 }
6452 priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
6453 if (priority == -1 && PyErr_Occurred())
6454 return 0;
6455 if (priority > INT_MAX || priority < INT_MIN) {
6456 PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
6457 return 0;
6458 }
6459 res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
6460 return 1;
6461}
William Orr81574b82018-10-01 22:19:56 -07006462#endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006463
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006464
6465#ifdef HAVE_SCHED_SETSCHEDULER
Larry Hastings2f936352014-08-05 14:04:04 +10006466/*[clinic input]
6467os.sched_setscheduler
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006468
Larry Hastings2f936352014-08-05 14:04:04 +10006469 pid: pid_t
6470 policy: int
Victor Stinner1c2fa782020-05-10 11:05:29 +02006471 param as param_obj: object
Larry Hastings2f936352014-08-05 14:04:04 +10006472 /
6473
6474Set the scheduling policy for the process identified by pid.
6475
6476If pid is 0, the calling process is changed.
6477param is an instance of sched_param.
6478[clinic start generated code]*/
6479
Larry Hastings2f936352014-08-05 14:04:04 +10006480static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006481os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
Victor Stinner1c2fa782020-05-10 11:05:29 +02006482 PyObject *param_obj)
6483/*[clinic end generated code: output=cde27faa55dc993e input=73013d731bd8fbe9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006484{
Victor Stinner1c2fa782020-05-10 11:05:29 +02006485 struct sched_param param;
6486 if (!convert_sched_param(module, param_obj, &param)) {
6487 return NULL;
6488 }
6489
Jesus Cea9c822272011-09-10 01:40:52 +02006490 /*
Jesus Cea54b01492011-09-10 01:53:19 +02006491 ** sched_setscheduler() returns 0 in Linux, but the previous
6492 ** scheduling policy under Solaris/Illumos, and others.
6493 ** On error, -1 is returned in all Operating Systems.
Jesus Cea9c822272011-09-10 01:40:52 +02006494 */
Victor Stinner1c2fa782020-05-10 11:05:29 +02006495 if (sched_setscheduler(pid, policy, &param) == -1)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006496 return posix_error();
6497 Py_RETURN_NONE;
6498}
Larry Hastings2f936352014-08-05 14:04:04 +10006499#endif /* HAVE_SCHED_SETSCHEDULER*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006500
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006501
6502#ifdef HAVE_SCHED_SETPARAM
Larry Hastings2f936352014-08-05 14:04:04 +10006503/*[clinic input]
6504os.sched_getparam
6505 pid: pid_t
6506 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006507
Larry Hastings2f936352014-08-05 14:04:04 +10006508Returns scheduling parameters for the process identified by pid.
6509
6510If pid is 0, returns parameters for the calling process.
6511Return value is an instance of sched_param.
6512[clinic start generated code]*/
6513
Larry Hastings2f936352014-08-05 14:04:04 +10006514static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006515os_sched_getparam_impl(PyObject *module, pid_t pid)
6516/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006517{
6518 struct sched_param param;
6519 PyObject *result;
6520 PyObject *priority;
6521
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006522 if (sched_getparam(pid, &param))
6523 return posix_error();
Victor Stinner1c2fa782020-05-10 11:05:29 +02006524 PyObject *SchedParamType = get_posix_state(module)->SchedParamType;
Eddie Elizondob3966632019-11-05 07:16:14 -08006525 result = PyStructSequence_New((PyTypeObject *)SchedParamType);
Larry Hastings2f936352014-08-05 14:04:04 +10006526 if (!result)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006527 return NULL;
6528 priority = PyLong_FromLong(param.sched_priority);
6529 if (!priority) {
Larry Hastings2f936352014-08-05 14:04:04 +10006530 Py_DECREF(result);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006531 return NULL;
6532 }
Larry Hastings2f936352014-08-05 14:04:04 +10006533 PyStructSequence_SET_ITEM(result, 0, priority);
6534 return result;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006535}
6536
Larry Hastings2f936352014-08-05 14:04:04 +10006537
6538/*[clinic input]
6539os.sched_setparam
6540 pid: pid_t
Victor Stinner1c2fa782020-05-10 11:05:29 +02006541 param as param_obj: object
Larry Hastings2f936352014-08-05 14:04:04 +10006542 /
6543
6544Set scheduling parameters for the process identified by pid.
6545
6546If pid is 0, sets parameters for the calling process.
6547param should be an instance of sched_param.
6548[clinic start generated code]*/
6549
Larry Hastings2f936352014-08-05 14:04:04 +10006550static PyObject *
Victor Stinner1c2fa782020-05-10 11:05:29 +02006551os_sched_setparam_impl(PyObject *module, pid_t pid, PyObject *param_obj)
6552/*[clinic end generated code: output=f19fe020a53741c1 input=27b98337c8b2dcc7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006553{
Victor Stinner1c2fa782020-05-10 11:05:29 +02006554 struct sched_param param;
6555 if (!convert_sched_param(module, param_obj, &param)) {
6556 return NULL;
6557 }
6558
6559 if (sched_setparam(pid, &param))
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006560 return posix_error();
6561 Py_RETURN_NONE;
6562}
Larry Hastings2f936352014-08-05 14:04:04 +10006563#endif /* HAVE_SCHED_SETPARAM */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006564
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006565
6566#ifdef HAVE_SCHED_RR_GET_INTERVAL
Larry Hastings2f936352014-08-05 14:04:04 +10006567/*[clinic input]
6568os.sched_rr_get_interval -> double
6569 pid: pid_t
6570 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006571
Larry Hastings2f936352014-08-05 14:04:04 +10006572Return the round-robin quantum for the process identified by pid, in seconds.
6573
6574Value returned is a float.
6575[clinic start generated code]*/
6576
Larry Hastings2f936352014-08-05 14:04:04 +10006577static double
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006578os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
6579/*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006580{
6581 struct timespec interval;
6582 if (sched_rr_get_interval(pid, &interval)) {
6583 posix_error();
6584 return -1.0;
6585 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006586#ifdef _Py_MEMORY_SANITIZER
6587 __msan_unpoison(&interval, sizeof(interval));
6588#endif
Larry Hastings2f936352014-08-05 14:04:04 +10006589 return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
6590}
6591#endif /* HAVE_SCHED_RR_GET_INTERVAL */
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006592
Larry Hastings2f936352014-08-05 14:04:04 +10006593
6594/*[clinic input]
6595os.sched_yield
6596
6597Voluntarily relinquish the CPU.
6598[clinic start generated code]*/
6599
Larry Hastings2f936352014-08-05 14:04:04 +10006600static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006601os_sched_yield_impl(PyObject *module)
6602/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006603{
6604 if (sched_yield())
6605 return posix_error();
6606 Py_RETURN_NONE;
6607}
6608
Benjamin Peterson2740af82011-08-02 17:41:34 -05006609#ifdef HAVE_SCHED_SETAFFINITY
Antoine Pitrou84869872012-08-04 16:16:35 +02006610/* The minimum number of CPUs allocated in a cpu_set_t */
6611static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006612
Larry Hastings2f936352014-08-05 14:04:04 +10006613/*[clinic input]
6614os.sched_setaffinity
6615 pid: pid_t
6616 mask : object
6617 /
6618
6619Set the CPU affinity of the process identified by pid to mask.
6620
6621mask should be an iterable of integers identifying CPUs.
6622[clinic start generated code]*/
6623
Larry Hastings2f936352014-08-05 14:04:04 +10006624static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006625os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
6626/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006627{
Antoine Pitrou84869872012-08-04 16:16:35 +02006628 int ncpus;
6629 size_t setsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006630 cpu_set_t *cpu_set = NULL;
6631 PyObject *iterator = NULL, *item;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006632
Larry Hastings2f936352014-08-05 14:04:04 +10006633 iterator = PyObject_GetIter(mask);
Antoine Pitrou84869872012-08-04 16:16:35 +02006634 if (iterator == NULL)
6635 return NULL;
6636
6637 ncpus = NCPUS_START;
6638 setsize = CPU_ALLOC_SIZE(ncpus);
Larry Hastings2f936352014-08-05 14:04:04 +10006639 cpu_set = CPU_ALLOC(ncpus);
6640 if (cpu_set == NULL) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006641 PyErr_NoMemory();
6642 goto error;
6643 }
Larry Hastings2f936352014-08-05 14:04:04 +10006644 CPU_ZERO_S(setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006645
6646 while ((item = PyIter_Next(iterator))) {
6647 long cpu;
6648 if (!PyLong_Check(item)) {
6649 PyErr_Format(PyExc_TypeError,
6650 "expected an iterator of ints, "
6651 "but iterator yielded %R",
6652 Py_TYPE(item));
6653 Py_DECREF(item);
6654 goto error;
6655 }
6656 cpu = PyLong_AsLong(item);
6657 Py_DECREF(item);
6658 if (cpu < 0) {
6659 if (!PyErr_Occurred())
6660 PyErr_SetString(PyExc_ValueError, "negative CPU number");
6661 goto error;
6662 }
6663 if (cpu > INT_MAX - 1) {
6664 PyErr_SetString(PyExc_OverflowError, "CPU number too large");
6665 goto error;
6666 }
6667 if (cpu >= ncpus) {
6668 /* Grow CPU mask to fit the CPU number */
6669 int newncpus = ncpus;
6670 cpu_set_t *newmask;
6671 size_t newsetsize;
6672 while (newncpus <= cpu) {
6673 if (newncpus > INT_MAX / 2)
6674 newncpus = cpu + 1;
6675 else
6676 newncpus = newncpus * 2;
6677 }
6678 newmask = CPU_ALLOC(newncpus);
6679 if (newmask == NULL) {
6680 PyErr_NoMemory();
6681 goto error;
6682 }
6683 newsetsize = CPU_ALLOC_SIZE(newncpus);
6684 CPU_ZERO_S(newsetsize, newmask);
Larry Hastings2f936352014-08-05 14:04:04 +10006685 memcpy(newmask, cpu_set, setsize);
6686 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006687 setsize = newsetsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006688 cpu_set = newmask;
Antoine Pitrou84869872012-08-04 16:16:35 +02006689 ncpus = newncpus;
6690 }
Larry Hastings2f936352014-08-05 14:04:04 +10006691 CPU_SET_S(cpu, setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006692 }
Brandt Bucher45a30af2019-06-27 09:10:57 -07006693 if (PyErr_Occurred()) {
6694 goto error;
6695 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006696 Py_CLEAR(iterator);
6697
Larry Hastings2f936352014-08-05 14:04:04 +10006698 if (sched_setaffinity(pid, setsize, cpu_set)) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006699 posix_error();
6700 goto error;
6701 }
Larry Hastings2f936352014-08-05 14:04:04 +10006702 CPU_FREE(cpu_set);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006703 Py_RETURN_NONE;
Antoine Pitrou84869872012-08-04 16:16:35 +02006704
6705error:
Larry Hastings2f936352014-08-05 14:04:04 +10006706 if (cpu_set)
6707 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006708 Py_XDECREF(iterator);
6709 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006710}
6711
Larry Hastings2f936352014-08-05 14:04:04 +10006712
6713/*[clinic input]
6714os.sched_getaffinity
6715 pid: pid_t
6716 /
6717
Charles-François Natalidc87e4b2015-07-13 21:01:39 +01006718Return the affinity of the process identified by pid (or the current process if zero).
Larry Hastings2f936352014-08-05 14:04:04 +10006719
6720The affinity is returned as a set of CPU identifiers.
6721[clinic start generated code]*/
6722
Larry Hastings2f936352014-08-05 14:04:04 +10006723static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006724os_sched_getaffinity_impl(PyObject *module, pid_t pid)
Serhiy Storchaka2954f832016-07-07 18:20:03 +03006725/*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006726{
Antoine Pitrou84869872012-08-04 16:16:35 +02006727 int cpu, ncpus, count;
6728 size_t setsize;
6729 cpu_set_t *mask = NULL;
6730 PyObject *res = NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006731
Antoine Pitrou84869872012-08-04 16:16:35 +02006732 ncpus = NCPUS_START;
6733 while (1) {
6734 setsize = CPU_ALLOC_SIZE(ncpus);
6735 mask = CPU_ALLOC(ncpus);
6736 if (mask == NULL)
6737 return PyErr_NoMemory();
6738 if (sched_getaffinity(pid, setsize, mask) == 0)
6739 break;
6740 CPU_FREE(mask);
6741 if (errno != EINVAL)
6742 return posix_error();
6743 if (ncpus > INT_MAX / 2) {
6744 PyErr_SetString(PyExc_OverflowError, "could not allocate "
6745 "a large enough CPU set");
6746 return NULL;
6747 }
6748 ncpus = ncpus * 2;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006749 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006750
6751 res = PySet_New(NULL);
6752 if (res == NULL)
6753 goto error;
6754 for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
6755 if (CPU_ISSET_S(cpu, setsize, mask)) {
6756 PyObject *cpu_num = PyLong_FromLong(cpu);
6757 --count;
6758 if (cpu_num == NULL)
6759 goto error;
6760 if (PySet_Add(res, cpu_num)) {
6761 Py_DECREF(cpu_num);
6762 goto error;
6763 }
6764 Py_DECREF(cpu_num);
6765 }
6766 }
6767 CPU_FREE(mask);
6768 return res;
6769
6770error:
6771 if (mask)
6772 CPU_FREE(mask);
6773 Py_XDECREF(res);
6774 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006775}
6776
Benjamin Peterson2740af82011-08-02 17:41:34 -05006777#endif /* HAVE_SCHED_SETAFFINITY */
6778
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006779#endif /* HAVE_SCHED_H */
6780
Larry Hastings2f936352014-08-05 14:04:04 +10006781
Neal Norwitzb59798b2003-03-21 01:43:31 +00006782/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
Neal Norwitz2deaddb2003-03-21 03:08:31 +00006783/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
6784#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
Neal Norwitzb59798b2003-03-21 01:43:31 +00006785#define DEV_PTY_FILE "/dev/ptc"
6786#define HAVE_DEV_PTMX
6787#else
6788#define DEV_PTY_FILE "/dev/ptmx"
6789#endif
6790
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006791#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
Fred Drake8cef4cf2000-06-28 16:40:38 +00006792#ifdef HAVE_PTY_H
6793#include <pty.h>
6794#else
6795#ifdef HAVE_LIBUTIL_H
6796#include <libutil.h>
Ronald Oussoren755740f2010-02-07 19:56:39 +00006797#else
6798#ifdef HAVE_UTIL_H
6799#include <util.h>
6800#endif /* HAVE_UTIL_H */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006801#endif /* HAVE_LIBUTIL_H */
6802#endif /* HAVE_PTY_H */
Martin v. Löwis14e73b12003-01-01 09:51:12 +00006803#ifdef HAVE_STROPTS_H
6804#include <stropts.h>
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006805#endif
ngie-eign7745ec42018-02-14 11:54:28 -08006806#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006807
Larry Hastings2f936352014-08-05 14:04:04 +10006808
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006809#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
Larry Hastings2f936352014-08-05 14:04:04 +10006810/*[clinic input]
6811os.openpty
6812
6813Open a pseudo-terminal.
6814
6815Return a tuple of (master_fd, slave_fd) containing open file descriptors
6816for both the master and slave ends.
6817[clinic start generated code]*/
6818
Larry Hastings2f936352014-08-05 14:04:04 +10006819static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006820os_openpty_impl(PyObject *module)
6821/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006822{
Victor Stinnerdaf45552013-08-28 00:53:59 +02006823 int master_fd = -1, slave_fd = -1;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006824#ifndef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006825 char * slave_name;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006826#endif
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006827#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006828 PyOS_sighandler_t sig_saved;
Jakub Kulík6f9bc722018-12-31 03:16:40 +01006829#if defined(__sun) && defined(__SVR4)
Victor Stinner8c62be82010-05-06 00:08:46 +00006830 extern char *ptsname(int fildes);
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006831#endif
6832#endif
Thomas Wouters70c21a12000-07-14 14:28:33 +00006833
Thomas Wouters70c21a12000-07-14 14:28:33 +00006834#ifdef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006835 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006836 goto posix_error;
6837
6838 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6839 goto error;
6840 if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
6841 goto error;
6842
Neal Norwitzb59798b2003-03-21 01:43:31 +00006843#elif defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006844 slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
6845 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006846 goto posix_error;
6847 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6848 goto error;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006849
Victor Stinnerdaf45552013-08-28 00:53:59 +02006850 slave_fd = _Py_open(slave_name, O_RDWR);
Victor Stinner8c62be82010-05-06 00:08:46 +00006851 if (slave_fd < 0)
Victor Stinnera555cfc2015-03-18 00:22:14 +01006852 goto error;
Victor Stinnerdaf45552013-08-28 00:53:59 +02006853
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006854#else
Victor Stinner000de532013-11-25 23:19:58 +01006855 master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
Victor Stinner8c62be82010-05-06 00:08:46 +00006856 if (master_fd < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006857 goto posix_error;
6858
Victor Stinner8c62be82010-05-06 00:08:46 +00006859 sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006860
Victor Stinner8c62be82010-05-06 00:08:46 +00006861 /* change permission of slave */
6862 if (grantpt(master_fd) < 0) {
6863 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006864 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006865 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006866
Victor Stinner8c62be82010-05-06 00:08:46 +00006867 /* unlock slave */
6868 if (unlockpt(master_fd) < 0) {
6869 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006870 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006871 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006872
Victor Stinner8c62be82010-05-06 00:08:46 +00006873 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006874
Victor Stinner8c62be82010-05-06 00:08:46 +00006875 slave_name = ptsname(master_fd); /* get name of slave */
6876 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006877 goto posix_error;
6878
6879 slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
Victor Stinnera555cfc2015-03-18 00:22:14 +01006880 if (slave_fd == -1)
6881 goto error;
Victor Stinner000de532013-11-25 23:19:58 +01006882
6883 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6884 goto posix_error;
6885
Stefan Krahfb7c8ae2016-04-26 17:04:18 +02006886#if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
Victor Stinner8c62be82010-05-06 00:08:46 +00006887 ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
6888 ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
Neal Norwitz6700e472002-12-31 16:16:07 +00006889#ifndef __hpux
Victor Stinner8c62be82010-05-06 00:08:46 +00006890 ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
Neal Norwitz6700e472002-12-31 16:16:07 +00006891#endif /* __hpux */
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006892#endif /* HAVE_CYGWIN */
Thomas Wouters1e0c2f42000-07-24 16:06:23 +00006893#endif /* HAVE_OPENPTY */
Thomas Wouters70c21a12000-07-14 14:28:33 +00006894
Victor Stinner8c62be82010-05-06 00:08:46 +00006895 return Py_BuildValue("(ii)", master_fd, slave_fd);
Thomas Wouters70c21a12000-07-14 14:28:33 +00006896
Victor Stinnerdaf45552013-08-28 00:53:59 +02006897posix_error:
6898 posix_error();
6899error:
6900 if (master_fd != -1)
6901 close(master_fd);
6902 if (slave_fd != -1)
6903 close(slave_fd);
6904 return NULL;
Fred Drake8cef4cf2000-06-28 16:40:38 +00006905}
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006906#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006907
Larry Hastings2f936352014-08-05 14:04:04 +10006908
Fred Drake8cef4cf2000-06-28 16:40:38 +00006909#ifdef HAVE_FORKPTY
Larry Hastings2f936352014-08-05 14:04:04 +10006910/*[clinic input]
6911os.forkpty
6912
6913Fork a new process with a new pseudo-terminal as controlling tty.
6914
6915Returns a tuple of (pid, master_fd).
6916Like fork(), return pid of 0 to the child process,
6917and pid of child to the parent process.
6918To both, return fd of newly opened pseudo-terminal.
6919[clinic start generated code]*/
6920
Larry Hastings2f936352014-08-05 14:04:04 +10006921static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006922os_forkpty_impl(PyObject *module)
6923/*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006924{
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006925 int master_fd = -1;
Victor Stinner8c62be82010-05-06 00:08:46 +00006926 pid_t pid;
Tim Peters5aa91602002-01-30 05:46:57 +00006927
Victor Stinner81a7be32020-04-14 15:14:01 +02006928 if (_PyInterpreterState_GET() != PyInterpreterState_Main()) {
Eric Snow59032962018-09-14 14:17:20 -07006929 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6930 return NULL;
6931 }
Saiyang Gou7514f4f2020-02-12 23:47:42 -08006932 if (PySys_Audit("os.forkpty", NULL) < 0) {
6933 return NULL;
6934 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006935 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006936 pid = forkpty(&master_fd, NULL, NULL, NULL);
6937 if (pid == 0) {
6938 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006939 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006940 } else {
6941 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006942 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006943 }
6944 if (pid == -1)
6945 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006946 return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
Fred Drake8cef4cf2000-06-28 16:40:38 +00006947}
Larry Hastings2f936352014-08-05 14:04:04 +10006948#endif /* HAVE_FORKPTY */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006949
Ross Lagerwall7807c352011-03-17 20:20:30 +02006950
Guido van Rossumad0ee831995-03-01 10:34:45 +00006951#ifdef HAVE_GETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10006952/*[clinic input]
6953os.getegid
6954
6955Return the current process's effective group id.
6956[clinic start generated code]*/
6957
Larry Hastings2f936352014-08-05 14:04:04 +10006958static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006959os_getegid_impl(PyObject *module)
6960/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006961{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006962 return _PyLong_FromGid(getegid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006963}
Larry Hastings2f936352014-08-05 14:04:04 +10006964#endif /* HAVE_GETEGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006965
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006966
Guido van Rossumad0ee831995-03-01 10:34:45 +00006967#ifdef HAVE_GETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10006968/*[clinic input]
6969os.geteuid
6970
6971Return the current process's effective user id.
6972[clinic start generated code]*/
6973
Larry Hastings2f936352014-08-05 14:04:04 +10006974static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006975os_geteuid_impl(PyObject *module)
6976/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006977{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006978 return _PyLong_FromUid(geteuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006979}
Larry Hastings2f936352014-08-05 14:04:04 +10006980#endif /* HAVE_GETEUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006981
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006982
Guido van Rossumad0ee831995-03-01 10:34:45 +00006983#ifdef HAVE_GETGID
Larry Hastings2f936352014-08-05 14:04:04 +10006984/*[clinic input]
6985os.getgid
6986
6987Return the current process's group id.
6988[clinic start generated code]*/
6989
Larry Hastings2f936352014-08-05 14:04:04 +10006990static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006991os_getgid_impl(PyObject *module)
6992/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006993{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006994 return _PyLong_FromGid(getgid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006995}
Larry Hastings2f936352014-08-05 14:04:04 +10006996#endif /* HAVE_GETGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006997
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006998
Berker Peksag39404992016-09-15 20:45:16 +03006999#ifdef HAVE_GETPID
Larry Hastings2f936352014-08-05 14:04:04 +10007000/*[clinic input]
7001os.getpid
7002
7003Return the current process id.
7004[clinic start generated code]*/
7005
Larry Hastings2f936352014-08-05 14:04:04 +10007006static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007007os_getpid_impl(PyObject *module)
7008/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00007009{
Victor Stinner8c62be82010-05-06 00:08:46 +00007010 return PyLong_FromPid(getpid());
Guido van Rossum85e3b011991-06-03 12:42:10 +00007011}
Berker Peksag39404992016-09-15 20:45:16 +03007012#endif /* HAVE_GETPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007013
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07007014#ifdef NGROUPS_MAX
7015#define MAX_GROUPS NGROUPS_MAX
7016#else
7017 /* defined to be 16 on Solaris7, so this should be a small number */
7018#define MAX_GROUPS 64
7019#endif
7020
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007021#ifdef HAVE_GETGROUPLIST
Larry Hastings2f936352014-08-05 14:04:04 +10007022
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007023#ifdef __APPLE__
7024/*[clinic input]
7025os.getgrouplist
7026
7027 user: str
7028 username to lookup
7029 group as basegid: int
7030 base group id of the user
7031 /
7032
7033Returns a list of groups to which a user belongs.
7034[clinic start generated code]*/
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007035
7036static PyObject *
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007037os_getgrouplist_impl(PyObject *module, const char *user, int basegid)
7038/*[clinic end generated code: output=6e734697b8c26de0 input=f8d870374b09a490]*/
7039#else
7040/*[clinic input]
7041os.getgrouplist
7042
7043 user: str
7044 username to lookup
7045 group as basegid: gid_t
7046 base group id of the user
7047 /
7048
7049Returns a list of groups to which a user belongs.
7050[clinic start generated code]*/
7051
7052static PyObject *
7053os_getgrouplist_impl(PyObject *module, const char *user, gid_t basegid)
7054/*[clinic end generated code: output=0ebd7fb70115575b input=cc61d5c20b08958d]*/
7055#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007056{
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007057 int i, ngroups;
7058 PyObject *list;
7059#ifdef __APPLE__
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007060 int *groups;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007061#else
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007062 gid_t *groups;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007063#endif
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07007064
7065 /*
7066 * NGROUPS_MAX is defined by POSIX.1 as the maximum
7067 * number of supplimental groups a users can belong to.
7068 * We have to increment it by one because
7069 * getgrouplist() returns both the supplemental groups
7070 * and the primary group, i.e. all of the groups the
7071 * user belongs to.
7072 */
7073 ngroups = 1 + MAX_GROUPS;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007074
Victor Stinnerf5c7cab2020-03-24 18:22:10 +01007075 while (1) {
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007076#ifdef __APPLE__
Victor Stinner8ec73702020-03-23 20:00:57 +01007077 groups = PyMem_New(int, ngroups);
Victor Stinnerf5c7cab2020-03-24 18:22:10 +01007078#else
7079 groups = PyMem_New(gid_t, ngroups);
7080#endif
Victor Stinner8ec73702020-03-23 20:00:57 +01007081 if (groups == NULL) {
7082 return PyErr_NoMemory();
7083 }
Victor Stinnerf5c7cab2020-03-24 18:22:10 +01007084
7085 int old_ngroups = ngroups;
7086 if (getgrouplist(user, basegid, groups, &ngroups) != -1) {
7087 /* Success */
7088 break;
7089 }
7090
7091 /* getgrouplist() fails if the group list is too small */
7092 PyMem_Free(groups);
7093
7094 if (ngroups > old_ngroups) {
7095 /* If the group list is too small, the glibc implementation of
7096 getgrouplist() sets ngroups to the total number of groups and
7097 returns -1. */
7098 }
7099 else {
7100 /* Double the group list size */
7101 if (ngroups > INT_MAX / 2) {
7102 return PyErr_NoMemory();
7103 }
7104 ngroups *= 2;
7105 }
7106
7107 /* Retry getgrouplist() with a larger group list */
Victor Stinner8ec73702020-03-23 20:00:57 +01007108 }
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007109
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08007110#ifdef _Py_MEMORY_SANITIZER
7111 /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
7112 __msan_unpoison(&ngroups, sizeof(ngroups));
7113 __msan_unpoison(groups, ngroups*sizeof(*groups));
7114#endif
7115
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007116 list = PyList_New(ngroups);
7117 if (list == NULL) {
7118 PyMem_Del(groups);
7119 return NULL;
7120 }
7121
7122 for (i = 0; i < ngroups; i++) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007123#ifdef __APPLE__
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007124 PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007125#else
7126 PyObject *o = _PyLong_FromGid(groups[i]);
7127#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007128 if (o == NULL) {
7129 Py_DECREF(list);
7130 PyMem_Del(groups);
7131 return NULL;
7132 }
7133 PyList_SET_ITEM(list, i, o);
7134 }
7135
7136 PyMem_Del(groups);
7137
7138 return list;
7139}
Larry Hastings2f936352014-08-05 14:04:04 +10007140#endif /* HAVE_GETGROUPLIST */
7141
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007142
Fred Drakec9680921999-12-13 16:37:25 +00007143#ifdef HAVE_GETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007144/*[clinic input]
7145os.getgroups
7146
7147Return list of supplemental group IDs for the process.
7148[clinic start generated code]*/
7149
Larry Hastings2f936352014-08-05 14:04:04 +10007150static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007151os_getgroups_impl(PyObject *module)
7152/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
Fred Drakec9680921999-12-13 16:37:25 +00007153{
7154 PyObject *result = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00007155 gid_t grouplist[MAX_GROUPS];
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007156
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007157 /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007158 * This is a helper variable to store the intermediate result when
7159 * that happens.
7160 *
7161 * To keep the code readable the OSX behaviour is unconditional,
7162 * according to the POSIX spec this should be safe on all unix-y
7163 * systems.
7164 */
7165 gid_t* alt_grouplist = grouplist;
Victor Stinner8c62be82010-05-06 00:08:46 +00007166 int n;
Fred Drakec9680921999-12-13 16:37:25 +00007167
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007168#ifdef __APPLE__
7169 /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
7170 * there are more groups than can fit in grouplist. Therefore, on OS X
7171 * always first call getgroups with length 0 to get the actual number
7172 * of groups.
7173 */
7174 n = getgroups(0, NULL);
7175 if (n < 0) {
7176 return posix_error();
7177 } else if (n <= MAX_GROUPS) {
7178 /* groups will fit in existing array */
7179 alt_grouplist = grouplist;
7180 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02007181 alt_grouplist = PyMem_New(gid_t, n);
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007182 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07007183 return PyErr_NoMemory();
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007184 }
7185 }
7186
7187 n = getgroups(n, alt_grouplist);
7188 if (n == -1) {
7189 if (alt_grouplist != grouplist) {
7190 PyMem_Free(alt_grouplist);
7191 }
7192 return posix_error();
7193 }
7194#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007195 n = getgroups(MAX_GROUPS, grouplist);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007196 if (n < 0) {
7197 if (errno == EINVAL) {
7198 n = getgroups(0, NULL);
7199 if (n == -1) {
7200 return posix_error();
7201 }
7202 if (n == 0) {
7203 /* Avoid malloc(0) */
7204 alt_grouplist = grouplist;
7205 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02007206 alt_grouplist = PyMem_New(gid_t, n);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007207 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07007208 return PyErr_NoMemory();
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007209 }
7210 n = getgroups(n, alt_grouplist);
7211 if (n == -1) {
7212 PyMem_Free(alt_grouplist);
7213 return posix_error();
7214 }
7215 }
7216 } else {
7217 return posix_error();
7218 }
7219 }
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007220#endif
7221
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007222 result = PyList_New(n);
7223 if (result != NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007224 int i;
7225 for (i = 0; i < n; ++i) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007226 PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
Victor Stinner8c62be82010-05-06 00:08:46 +00007227 if (o == NULL) {
Stefan Krah0e803b32010-11-26 16:16:47 +00007228 Py_DECREF(result);
7229 result = NULL;
7230 break;
Fred Drakec9680921999-12-13 16:37:25 +00007231 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007232 PyList_SET_ITEM(result, i, o);
Fred Drakec9680921999-12-13 16:37:25 +00007233 }
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007234 }
7235
7236 if (alt_grouplist != grouplist) {
7237 PyMem_Free(alt_grouplist);
Victor Stinner8c62be82010-05-06 00:08:46 +00007238 }
Neal Norwitze241ce82003-02-17 18:17:05 +00007239
Fred Drakec9680921999-12-13 16:37:25 +00007240 return result;
7241}
Larry Hastings2f936352014-08-05 14:04:04 +10007242#endif /* HAVE_GETGROUPS */
Fred Drakec9680921999-12-13 16:37:25 +00007243
Antoine Pitroub7572f02009-12-02 20:46:48 +00007244#ifdef HAVE_INITGROUPS
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007245#ifdef __APPLE__
7246/*[clinic input]
7247os.initgroups
Antoine Pitroub7572f02009-12-02 20:46:48 +00007248
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007249 username as oname: FSConverter
7250 gid: int
7251 /
7252
7253Initialize the group access list.
7254
7255Call the system initgroups() to initialize the group access list with all of
7256the groups of which the specified username is a member, plus the specified
7257group id.
7258[clinic start generated code]*/
7259
Antoine Pitroub7572f02009-12-02 20:46:48 +00007260static PyObject *
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007261os_initgroups_impl(PyObject *module, PyObject *oname, int gid)
7262/*[clinic end generated code: output=7f074d30a425fd3a input=df3d54331b0af204]*/
7263#else
7264/*[clinic input]
7265os.initgroups
7266
7267 username as oname: FSConverter
7268 gid: gid_t
7269 /
7270
7271Initialize the group access list.
7272
7273Call the system initgroups() to initialize the group access list with all of
7274the groups of which the specified username is a member, plus the specified
7275group id.
7276[clinic start generated code]*/
7277
7278static PyObject *
7279os_initgroups_impl(PyObject *module, PyObject *oname, gid_t gid)
7280/*[clinic end generated code: output=59341244521a9e3f input=0cb91bdc59a4c564]*/
7281#endif
Antoine Pitroub7572f02009-12-02 20:46:48 +00007282{
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007283 const char *username = PyBytes_AS_STRING(oname);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007284
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007285 if (initgroups(username, gid) == -1)
Victor Stinner8c62be82010-05-06 00:08:46 +00007286 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007287
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007288 Py_RETURN_NONE;
Antoine Pitroub7572f02009-12-02 20:46:48 +00007289}
Larry Hastings2f936352014-08-05 14:04:04 +10007290#endif /* HAVE_INITGROUPS */
7291
Antoine Pitroub7572f02009-12-02 20:46:48 +00007292
Martin v. Löwis606edc12002-06-13 21:09:11 +00007293#ifdef HAVE_GETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10007294/*[clinic input]
7295os.getpgid
7296
7297 pid: pid_t
7298
7299Call the system call getpgid(), and return the result.
7300[clinic start generated code]*/
7301
Larry Hastings2f936352014-08-05 14:04:04 +10007302static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007303os_getpgid_impl(PyObject *module, pid_t pid)
7304/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007305{
7306 pid_t pgid = getpgid(pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007307 if (pgid < 0)
7308 return posix_error();
7309 return PyLong_FromPid(pgid);
Martin v. Löwis606edc12002-06-13 21:09:11 +00007310}
7311#endif /* HAVE_GETPGID */
7312
7313
Guido van Rossumb6775db1994-08-01 11:34:53 +00007314#ifdef HAVE_GETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007315/*[clinic input]
7316os.getpgrp
7317
7318Return the current process group id.
7319[clinic start generated code]*/
7320
Larry Hastings2f936352014-08-05 14:04:04 +10007321static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007322os_getpgrp_impl(PyObject *module)
7323/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
Guido van Rossum04814471991-06-04 20:23:49 +00007324{
Guido van Rossumb6775db1994-08-01 11:34:53 +00007325#ifdef GETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007326 return PyLong_FromPid(getpgrp(0));
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007327#else /* GETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007328 return PyLong_FromPid(getpgrp());
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007329#endif /* GETPGRP_HAVE_ARG */
Guido van Rossum04814471991-06-04 20:23:49 +00007330}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007331#endif /* HAVE_GETPGRP */
Guido van Rossum04814471991-06-04 20:23:49 +00007332
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007333
Guido van Rossumb6775db1994-08-01 11:34:53 +00007334#ifdef HAVE_SETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007335/*[clinic input]
7336os.setpgrp
7337
7338Make the current process the leader of its process group.
7339[clinic start generated code]*/
7340
Larry Hastings2f936352014-08-05 14:04:04 +10007341static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007342os_setpgrp_impl(PyObject *module)
7343/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00007344{
Guido van Rossum64933891994-10-20 21:56:42 +00007345#ifdef SETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007346 if (setpgrp(0, 0) < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007347#else /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007348 if (setpgrp() < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007349#endif /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007350 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007351 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00007352}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007353#endif /* HAVE_SETPGRP */
7354
Guido van Rossumad0ee831995-03-01 10:34:45 +00007355#ifdef HAVE_GETPPID
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007356
7357#ifdef MS_WINDOWS
7358#include <tlhelp32.h>
7359
7360static PyObject*
7361win32_getppid()
7362{
7363 HANDLE snapshot;
7364 pid_t mypid;
7365 PyObject* result = NULL;
7366 BOOL have_record;
7367 PROCESSENTRY32 pe;
7368
7369 mypid = getpid(); /* This function never fails */
7370
7371 snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
7372 if (snapshot == INVALID_HANDLE_VALUE)
7373 return PyErr_SetFromWindowsErr(GetLastError());
7374
7375 pe.dwSize = sizeof(pe);
7376 have_record = Process32First(snapshot, &pe);
7377 while (have_record) {
7378 if (mypid == (pid_t)pe.th32ProcessID) {
7379 /* We could cache the ulong value in a static variable. */
7380 result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
7381 break;
7382 }
7383
7384 have_record = Process32Next(snapshot, &pe);
7385 }
7386
7387 /* If our loop exits and our pid was not found (result will be NULL)
7388 * then GetLastError will return ERROR_NO_MORE_FILES. This is an
7389 * error anyway, so let's raise it. */
7390 if (!result)
7391 result = PyErr_SetFromWindowsErr(GetLastError());
7392
7393 CloseHandle(snapshot);
7394
7395 return result;
7396}
7397#endif /*MS_WINDOWS*/
7398
Larry Hastings2f936352014-08-05 14:04:04 +10007399
7400/*[clinic input]
7401os.getppid
7402
7403Return the parent's process id.
7404
7405If the parent process has already exited, Windows machines will still
7406return its id; others systems will return the id of the 'init' process (1).
7407[clinic start generated code]*/
7408
Larry Hastings2f936352014-08-05 14:04:04 +10007409static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007410os_getppid_impl(PyObject *module)
7411/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00007412{
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007413#ifdef MS_WINDOWS
7414 return win32_getppid();
7415#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007416 return PyLong_FromPid(getppid());
Guido van Rossumad0ee831995-03-01 10:34:45 +00007417#endif
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007418}
7419#endif /* HAVE_GETPPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007420
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007421
Fred Drake12c6e2d1999-12-14 21:25:03 +00007422#ifdef HAVE_GETLOGIN
Larry Hastings2f936352014-08-05 14:04:04 +10007423/*[clinic input]
7424os.getlogin
7425
7426Return the actual login name.
7427[clinic start generated code]*/
7428
Larry Hastings2f936352014-08-05 14:04:04 +10007429static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007430os_getlogin_impl(PyObject *module)
7431/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
Fred Drake12c6e2d1999-12-14 21:25:03 +00007432{
Victor Stinner8c62be82010-05-06 00:08:46 +00007433 PyObject *result = NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007434#ifdef MS_WINDOWS
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007435 wchar_t user_name[UNLEN + 1];
Victor Stinner63941882011-09-29 00:42:28 +02007436 DWORD num_chars = Py_ARRAY_LENGTH(user_name);
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007437
7438 if (GetUserNameW(user_name, &num_chars)) {
7439 /* num_chars is the number of unicode chars plus null terminator */
7440 result = PyUnicode_FromWideChar(user_name, num_chars - 1);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007441 }
7442 else
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007443 result = PyErr_SetFromWindowsErr(GetLastError());
7444#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007445 char *name;
7446 int old_errno = errno;
Fred Drake12c6e2d1999-12-14 21:25:03 +00007447
Victor Stinner8c62be82010-05-06 00:08:46 +00007448 errno = 0;
7449 name = getlogin();
7450 if (name == NULL) {
7451 if (errno)
Victor Stinnere039ffe2010-08-15 09:33:08 +00007452 posix_error();
Fred Drake12c6e2d1999-12-14 21:25:03 +00007453 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007454 PyErr_SetString(PyExc_OSError, "unable to determine login name");
Victor Stinner8c62be82010-05-06 00:08:46 +00007455 }
7456 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007457 result = PyUnicode_DecodeFSDefault(name);
Victor Stinner8c62be82010-05-06 00:08:46 +00007458 errno = old_errno;
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007459#endif
Fred Drake12c6e2d1999-12-14 21:25:03 +00007460 return result;
7461}
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007462#endif /* HAVE_GETLOGIN */
Fred Drake12c6e2d1999-12-14 21:25:03 +00007463
Larry Hastings2f936352014-08-05 14:04:04 +10007464
Guido van Rossumad0ee831995-03-01 10:34:45 +00007465#ifdef HAVE_GETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007466/*[clinic input]
7467os.getuid
7468
7469Return the current process's user id.
7470[clinic start generated code]*/
7471
Larry Hastings2f936352014-08-05 14:04:04 +10007472static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007473os_getuid_impl(PyObject *module)
7474/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00007475{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007476 return _PyLong_FromUid(getuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00007477}
Larry Hastings2f936352014-08-05 14:04:04 +10007478#endif /* HAVE_GETUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00007479
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007480
Brian Curtineb24d742010-04-12 17:16:38 +00007481#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007482#define HAVE_KILL
7483#endif /* MS_WINDOWS */
7484
7485#ifdef HAVE_KILL
7486/*[clinic input]
7487os.kill
7488
7489 pid: pid_t
7490 signal: Py_ssize_t
7491 /
7492
7493Kill a process with a signal.
7494[clinic start generated code]*/
7495
Larry Hastings2f936352014-08-05 14:04:04 +10007496static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007497os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
7498/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007499{
Saiyang Gou7514f4f2020-02-12 23:47:42 -08007500 if (PySys_Audit("os.kill", "in", pid, signal) < 0) {
7501 return NULL;
7502 }
7503#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007504 if (kill(pid, (int)signal) == -1)
7505 return posix_error();
7506 Py_RETURN_NONE;
Larry Hastings2f936352014-08-05 14:04:04 +10007507#else /* !MS_WINDOWS */
Amaury Forgeot d'Arc0a589c92010-05-15 20:35:12 +00007508 PyObject *result;
Larry Hastings2f936352014-08-05 14:04:04 +10007509 DWORD sig = (DWORD)signal;
7510 DWORD err;
Victor Stinner8c62be82010-05-06 00:08:46 +00007511 HANDLE handle;
Brian Curtineb24d742010-04-12 17:16:38 +00007512
Victor Stinner8c62be82010-05-06 00:08:46 +00007513 /* Console processes which share a common console can be sent CTRL+C or
7514 CTRL+BREAK events, provided they handle said events. */
7515 if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007516 if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007517 err = GetLastError();
7518 PyErr_SetFromWindowsErr(err);
7519 }
7520 else
7521 Py_RETURN_NONE;
7522 }
Brian Curtineb24d742010-04-12 17:16:38 +00007523
Victor Stinner8c62be82010-05-06 00:08:46 +00007524 /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
7525 attempt to open and terminate the process. */
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007526 handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007527 if (handle == NULL) {
7528 err = GetLastError();
7529 return PyErr_SetFromWindowsErr(err);
7530 }
Brian Curtineb24d742010-04-12 17:16:38 +00007531
Victor Stinner8c62be82010-05-06 00:08:46 +00007532 if (TerminateProcess(handle, sig) == 0) {
7533 err = GetLastError();
7534 result = PyErr_SetFromWindowsErr(err);
7535 } else {
7536 Py_INCREF(Py_None);
7537 result = Py_None;
7538 }
Brian Curtineb24d742010-04-12 17:16:38 +00007539
Victor Stinner8c62be82010-05-06 00:08:46 +00007540 CloseHandle(handle);
7541 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10007542#endif /* !MS_WINDOWS */
Saiyang Gou7514f4f2020-02-12 23:47:42 -08007543}
Larry Hastings2f936352014-08-05 14:04:04 +10007544#endif /* HAVE_KILL */
7545
7546
7547#ifdef HAVE_KILLPG
7548/*[clinic input]
7549os.killpg
7550
7551 pgid: pid_t
7552 signal: int
7553 /
7554
7555Kill a process group with a signal.
7556[clinic start generated code]*/
7557
Larry Hastings2f936352014-08-05 14:04:04 +10007558static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007559os_killpg_impl(PyObject *module, pid_t pgid, int signal)
7560/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007561{
Saiyang Gou7514f4f2020-02-12 23:47:42 -08007562 if (PySys_Audit("os.killpg", "ii", pgid, signal) < 0) {
7563 return NULL;
7564 }
Larry Hastings2f936352014-08-05 14:04:04 +10007565 /* XXX some man pages make the `pgid` parameter an int, others
7566 a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
7567 take the same type. Moreover, pid_t is always at least as wide as
7568 int (else compilation of this module fails), which is safe. */
7569 if (killpg(pgid, signal) == -1)
7570 return posix_error();
7571 Py_RETURN_NONE;
7572}
7573#endif /* HAVE_KILLPG */
7574
Brian Curtineb24d742010-04-12 17:16:38 +00007575
Guido van Rossumc0125471996-06-28 18:55:32 +00007576#ifdef HAVE_PLOCK
Guido van Rossumc0125471996-06-28 18:55:32 +00007577#ifdef HAVE_SYS_LOCK_H
7578#include <sys/lock.h>
7579#endif
7580
Larry Hastings2f936352014-08-05 14:04:04 +10007581/*[clinic input]
7582os.plock
7583 op: int
7584 /
7585
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007586Lock program segments into memory.");
Larry Hastings2f936352014-08-05 14:04:04 +10007587[clinic start generated code]*/
7588
Larry Hastings2f936352014-08-05 14:04:04 +10007589static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007590os_plock_impl(PyObject *module, int op)
7591/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007592{
Victor Stinner8c62be82010-05-06 00:08:46 +00007593 if (plock(op) == -1)
7594 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007595 Py_RETURN_NONE;
Guido van Rossumc0125471996-06-28 18:55:32 +00007596}
Larry Hastings2f936352014-08-05 14:04:04 +10007597#endif /* HAVE_PLOCK */
7598
Guido van Rossumc0125471996-06-28 18:55:32 +00007599
Guido van Rossumb6775db1994-08-01 11:34:53 +00007600#ifdef HAVE_SETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007601/*[clinic input]
7602os.setuid
7603
7604 uid: uid_t
7605 /
7606
7607Set the current process's user id.
7608[clinic start generated code]*/
7609
Larry Hastings2f936352014-08-05 14:04:04 +10007610static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007611os_setuid_impl(PyObject *module, uid_t uid)
7612/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007613{
Victor Stinner8c62be82010-05-06 00:08:46 +00007614 if (setuid(uid) < 0)
7615 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007616 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007617}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007618#endif /* HAVE_SETUID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007619
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007620
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007621#ifdef HAVE_SETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10007622/*[clinic input]
7623os.seteuid
7624
7625 euid: uid_t
7626 /
7627
7628Set the current process's effective user id.
7629[clinic start generated code]*/
7630
Larry Hastings2f936352014-08-05 14:04:04 +10007631static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007632os_seteuid_impl(PyObject *module, uid_t euid)
7633/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007634{
7635 if (seteuid(euid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007636 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007637 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007638}
7639#endif /* HAVE_SETEUID */
7640
Larry Hastings2f936352014-08-05 14:04:04 +10007641
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007642#ifdef HAVE_SETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10007643/*[clinic input]
7644os.setegid
7645
7646 egid: gid_t
7647 /
7648
7649Set the current process's effective group id.
7650[clinic start generated code]*/
7651
Larry Hastings2f936352014-08-05 14:04:04 +10007652static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007653os_setegid_impl(PyObject *module, gid_t egid)
7654/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007655{
7656 if (setegid(egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007657 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007658 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007659}
7660#endif /* HAVE_SETEGID */
7661
Larry Hastings2f936352014-08-05 14:04:04 +10007662
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007663#ifdef HAVE_SETREUID
Larry Hastings2f936352014-08-05 14:04:04 +10007664/*[clinic input]
7665os.setreuid
7666
7667 ruid: uid_t
7668 euid: uid_t
7669 /
7670
7671Set the current process's real and effective user ids.
7672[clinic start generated code]*/
7673
Larry Hastings2f936352014-08-05 14:04:04 +10007674static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007675os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
7676/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007677{
Victor Stinner8c62be82010-05-06 00:08:46 +00007678 if (setreuid(ruid, euid) < 0) {
7679 return posix_error();
7680 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007681 Py_RETURN_NONE;
Victor Stinner8c62be82010-05-06 00:08:46 +00007682 }
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007683}
7684#endif /* HAVE_SETREUID */
7685
Larry Hastings2f936352014-08-05 14:04:04 +10007686
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007687#ifdef HAVE_SETREGID
Larry Hastings2f936352014-08-05 14:04:04 +10007688/*[clinic input]
7689os.setregid
7690
7691 rgid: gid_t
7692 egid: gid_t
7693 /
7694
7695Set the current process's real and effective group ids.
7696[clinic start generated code]*/
7697
Larry Hastings2f936352014-08-05 14:04:04 +10007698static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007699os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
7700/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007701{
7702 if (setregid(rgid, egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007703 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007704 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007705}
7706#endif /* HAVE_SETREGID */
7707
Larry Hastings2f936352014-08-05 14:04:04 +10007708
Guido van Rossumb6775db1994-08-01 11:34:53 +00007709#ifdef HAVE_SETGID
Larry Hastings2f936352014-08-05 14:04:04 +10007710/*[clinic input]
7711os.setgid
7712 gid: gid_t
7713 /
7714
7715Set the current process's group id.
7716[clinic start generated code]*/
7717
Larry Hastings2f936352014-08-05 14:04:04 +10007718static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007719os_setgid_impl(PyObject *module, gid_t gid)
7720/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007721{
Victor Stinner8c62be82010-05-06 00:08:46 +00007722 if (setgid(gid) < 0)
7723 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007724 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007725}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007726#endif /* HAVE_SETGID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007727
Larry Hastings2f936352014-08-05 14:04:04 +10007728
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007729#ifdef HAVE_SETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007730/*[clinic input]
7731os.setgroups
7732
7733 groups: object
7734 /
7735
7736Set the groups of the current process to list.
7737[clinic start generated code]*/
7738
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007739static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007740os_setgroups(PyObject *module, PyObject *groups)
7741/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007742{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007743 Py_ssize_t i, len;
Victor Stinner8c62be82010-05-06 00:08:46 +00007744 gid_t grouplist[MAX_GROUPS];
Tim Peters5aa91602002-01-30 05:46:57 +00007745
Victor Stinner8c62be82010-05-06 00:08:46 +00007746 if (!PySequence_Check(groups)) {
7747 PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
7748 return NULL;
7749 }
7750 len = PySequence_Size(groups);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007751 if (len < 0) {
7752 return NULL;
7753 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007754 if (len > MAX_GROUPS) {
7755 PyErr_SetString(PyExc_ValueError, "too many groups");
7756 return NULL;
7757 }
7758 for(i = 0; i < len; i++) {
7759 PyObject *elem;
7760 elem = PySequence_GetItem(groups, i);
7761 if (!elem)
7762 return NULL;
7763 if (!PyLong_Check(elem)) {
7764 PyErr_SetString(PyExc_TypeError,
7765 "groups must be integers");
7766 Py_DECREF(elem);
7767 return NULL;
7768 } else {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007769 if (!_Py_Gid_Converter(elem, &grouplist[i])) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007770 Py_DECREF(elem);
7771 return NULL;
7772 }
7773 }
7774 Py_DECREF(elem);
7775 }
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007776
Victor Stinner8c62be82010-05-06 00:08:46 +00007777 if (setgroups(len, grouplist) < 0)
7778 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007779 Py_RETURN_NONE;
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007780}
7781#endif /* HAVE_SETGROUPS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007782
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007783#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
7784static PyObject *
Victor Stinner1c2fa782020-05-10 11:05:29 +02007785wait_helper(PyObject *module, pid_t pid, int status, struct rusage *ru)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007786{
Victor Stinner8c62be82010-05-06 00:08:46 +00007787 PyObject *result;
Eddie Elizondob3966632019-11-05 07:16:14 -08007788 PyObject *struct_rusage;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007789
Victor Stinner8c62be82010-05-06 00:08:46 +00007790 if (pid == -1)
7791 return posix_error();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007792
Zackery Spytz682107c2019-09-09 09:48:32 -06007793 // If wait succeeded but no child was ready to report status, ru will not
7794 // have been populated.
7795 if (pid == 0) {
7796 memset(ru, 0, sizeof(*ru));
7797 }
7798
Eddie Elizondob3966632019-11-05 07:16:14 -08007799 PyObject *m = PyImport_ImportModuleNoBlock("resource");
7800 if (m == NULL)
7801 return NULL;
Victor Stinner1c2fa782020-05-10 11:05:29 +02007802 struct_rusage = PyObject_GetAttr(m, get_posix_state(module)->struct_rusage);
Eddie Elizondob3966632019-11-05 07:16:14 -08007803 Py_DECREF(m);
7804 if (struct_rusage == NULL)
7805 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007806
Victor Stinner8c62be82010-05-06 00:08:46 +00007807 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
7808 result = PyStructSequence_New((PyTypeObject*) struct_rusage);
Eddie Elizondoe4db1f02019-11-25 19:07:37 -08007809 Py_DECREF(struct_rusage);
Victor Stinner8c62be82010-05-06 00:08:46 +00007810 if (!result)
7811 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007812
7813#ifndef doubletime
7814#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
7815#endif
7816
Victor Stinner8c62be82010-05-06 00:08:46 +00007817 PyStructSequence_SET_ITEM(result, 0,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007818 PyFloat_FromDouble(doubletime(ru->ru_utime)));
Victor Stinner8c62be82010-05-06 00:08:46 +00007819 PyStructSequence_SET_ITEM(result, 1,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007820 PyFloat_FromDouble(doubletime(ru->ru_stime)));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007821#define SET_INT(result, index, value)\
Victor Stinner8c62be82010-05-06 00:08:46 +00007822 PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
7823 SET_INT(result, 2, ru->ru_maxrss);
7824 SET_INT(result, 3, ru->ru_ixrss);
7825 SET_INT(result, 4, ru->ru_idrss);
7826 SET_INT(result, 5, ru->ru_isrss);
7827 SET_INT(result, 6, ru->ru_minflt);
7828 SET_INT(result, 7, ru->ru_majflt);
7829 SET_INT(result, 8, ru->ru_nswap);
7830 SET_INT(result, 9, ru->ru_inblock);
7831 SET_INT(result, 10, ru->ru_oublock);
7832 SET_INT(result, 11, ru->ru_msgsnd);
7833 SET_INT(result, 12, ru->ru_msgrcv);
7834 SET_INT(result, 13, ru->ru_nsignals);
7835 SET_INT(result, 14, ru->ru_nvcsw);
7836 SET_INT(result, 15, ru->ru_nivcsw);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007837#undef SET_INT
7838
Victor Stinner8c62be82010-05-06 00:08:46 +00007839 if (PyErr_Occurred()) {
7840 Py_DECREF(result);
7841 return NULL;
7842 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007843
Victor Stinner8c62be82010-05-06 00:08:46 +00007844 return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007845}
7846#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
7847
Larry Hastings2f936352014-08-05 14:04:04 +10007848
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007849#ifdef HAVE_WAIT3
Larry Hastings2f936352014-08-05 14:04:04 +10007850/*[clinic input]
7851os.wait3
7852
7853 options: int
7854Wait for completion of a child process.
7855
7856Returns a tuple of information about the child process:
7857 (pid, status, rusage)
7858[clinic start generated code]*/
7859
Larry Hastings2f936352014-08-05 14:04:04 +10007860static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007861os_wait3_impl(PyObject *module, int options)
7862/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007863{
Victor Stinner8c62be82010-05-06 00:08:46 +00007864 pid_t pid;
Victor Stinner8c62be82010-05-06 00:08:46 +00007865 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007866 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007867 WAIT_TYPE status;
7868 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007869
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007870 do {
7871 Py_BEGIN_ALLOW_THREADS
7872 pid = wait3(&status, options, &ru);
7873 Py_END_ALLOW_THREADS
7874 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7875 if (pid < 0)
7876 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007877
Victor Stinner1c2fa782020-05-10 11:05:29 +02007878 return wait_helper(module, pid, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007879}
7880#endif /* HAVE_WAIT3 */
7881
Larry Hastings2f936352014-08-05 14:04:04 +10007882
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007883#ifdef HAVE_WAIT4
Larry Hastings2f936352014-08-05 14:04:04 +10007884/*[clinic input]
7885
7886os.wait4
7887
7888 pid: pid_t
7889 options: int
7890
7891Wait for completion of a specific child process.
7892
7893Returns a tuple of information about the child process:
7894 (pid, status, rusage)
7895[clinic start generated code]*/
7896
Larry Hastings2f936352014-08-05 14:04:04 +10007897static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007898os_wait4_impl(PyObject *module, pid_t pid, int options)
7899/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007900{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007901 pid_t res;
Victor Stinner8c62be82010-05-06 00:08:46 +00007902 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007903 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007904 WAIT_TYPE status;
7905 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007906
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007907 do {
7908 Py_BEGIN_ALLOW_THREADS
7909 res = wait4(pid, &status, options, &ru);
7910 Py_END_ALLOW_THREADS
7911 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7912 if (res < 0)
7913 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007914
Victor Stinner1c2fa782020-05-10 11:05:29 +02007915 return wait_helper(module, res, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007916}
7917#endif /* HAVE_WAIT4 */
7918
Larry Hastings2f936352014-08-05 14:04:04 +10007919
Ross Lagerwall7807c352011-03-17 20:20:30 +02007920#if defined(HAVE_WAITID) && !defined(__APPLE__)
Larry Hastings2f936352014-08-05 14:04:04 +10007921/*[clinic input]
7922os.waitid
7923
7924 idtype: idtype_t
7925 Must be one of be P_PID, P_PGID or P_ALL.
7926 id: id_t
7927 The id to wait on.
7928 options: int
7929 Constructed from the ORing of one or more of WEXITED, WSTOPPED
7930 or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
7931 /
7932
7933Returns the result of waiting for a process or processes.
7934
7935Returns either waitid_result or None if WNOHANG is specified and there are
7936no children in a waitable state.
7937[clinic start generated code]*/
7938
Larry Hastings2f936352014-08-05 14:04:04 +10007939static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007940os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
7941/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007942{
7943 PyObject *result;
7944 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007945 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007946 siginfo_t si;
7947 si.si_pid = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007948
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007949 do {
7950 Py_BEGIN_ALLOW_THREADS
7951 res = waitid(idtype, id, &si, options);
7952 Py_END_ALLOW_THREADS
7953 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7954 if (res < 0)
7955 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007956
7957 if (si.si_pid == 0)
7958 Py_RETURN_NONE;
7959
Hai Shif707d942020-03-16 21:15:01 +08007960 PyObject *WaitidResultType = get_posix_state(module)->WaitidResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -08007961 result = PyStructSequence_New((PyTypeObject *)WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +02007962 if (!result)
7963 return NULL;
7964
7965 PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007966 PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
Ross Lagerwall7807c352011-03-17 20:20:30 +02007967 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
7968 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
7969 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
7970 if (PyErr_Occurred()) {
7971 Py_DECREF(result);
7972 return NULL;
7973 }
7974
7975 return result;
7976}
Larry Hastings2f936352014-08-05 14:04:04 +10007977#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
Ross Lagerwall7807c352011-03-17 20:20:30 +02007978
Larry Hastings2f936352014-08-05 14:04:04 +10007979
7980#if defined(HAVE_WAITPID)
7981/*[clinic input]
7982os.waitpid
7983 pid: pid_t
7984 options: int
7985 /
7986
7987Wait for completion of a given child process.
7988
7989Returns a tuple of information regarding the child process:
7990 (pid, status)
7991
7992The options argument is ignored on Windows.
7993[clinic start generated code]*/
7994
Larry Hastings2f936352014-08-05 14:04:04 +10007995static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007996os_waitpid_impl(PyObject *module, pid_t pid, int options)
7997/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007998{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007999 pid_t res;
8000 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00008001 WAIT_TYPE status;
8002 WAIT_STATUS_INT(status) = 0;
Guido van Rossum54ecc3d1999-01-27 17:53:11 +00008003
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008004 do {
8005 Py_BEGIN_ALLOW_THREADS
8006 res = waitpid(pid, &status, options);
8007 Py_END_ALLOW_THREADS
8008 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8009 if (res < 0)
8010 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008011
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008012 return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
Guido van Rossum21803b81992-08-09 12:55:27 +00008013}
Tim Petersab034fa2002-02-01 11:27:43 +00008014#elif defined(HAVE_CWAIT)
Tim Petersab034fa2002-02-01 11:27:43 +00008015/* MS C has a variant of waitpid() that's usable for most purposes. */
Larry Hastings2f936352014-08-05 14:04:04 +10008016/*[clinic input]
8017os.waitpid
Benjamin Petersonca470632016-09-06 13:47:26 -07008018 pid: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +10008019 options: int
8020 /
8021
8022Wait for completion of a given process.
8023
8024Returns a tuple of information regarding the process:
8025 (pid, status << 8)
8026
8027The options argument is ignored on Windows.
8028[clinic start generated code]*/
8029
Larry Hastings2f936352014-08-05 14:04:04 +10008030static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -07008031os_waitpid_impl(PyObject *module, intptr_t pid, int options)
Victor Stinner581139c2016-09-06 15:54:20 -07008032/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008033{
8034 int status;
Benjamin Petersonca470632016-09-06 13:47:26 -07008035 intptr_t res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008036 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008037
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008038 do {
8039 Py_BEGIN_ALLOW_THREADS
Steve Dower11f43262016-11-19 18:33:39 -08008040 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008041 res = _cwait(&status, pid, options);
Steve Dower11f43262016-11-19 18:33:39 -08008042 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008043 Py_END_ALLOW_THREADS
8044 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinnerd3ffd322015-09-15 10:11:03 +02008045 if (res < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008046 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008047
Victor Stinner9bee32b2020-04-22 16:30:35 +02008048 unsigned long long ustatus = (unsigned int)status;
8049
Victor Stinner8c62be82010-05-06 00:08:46 +00008050 /* shift the status left a byte so this is more like the POSIX waitpid */
Victor Stinner9bee32b2020-04-22 16:30:35 +02008051 return Py_BuildValue(_Py_PARSE_INTPTR "K", res, ustatus << 8);
Tim Petersab034fa2002-02-01 11:27:43 +00008052}
Larry Hastings2f936352014-08-05 14:04:04 +10008053#endif
8054
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008055
Guido van Rossumad0ee831995-03-01 10:34:45 +00008056#ifdef HAVE_WAIT
Larry Hastings2f936352014-08-05 14:04:04 +10008057/*[clinic input]
8058os.wait
8059
8060Wait for completion of a child process.
8061
8062Returns a tuple of information about the child process:
8063 (pid, status)
8064[clinic start generated code]*/
8065
Larry Hastings2f936352014-08-05 14:04:04 +10008066static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008067os_wait_impl(PyObject *module)
8068/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
Guido van Rossum21803b81992-08-09 12:55:27 +00008069{
Victor Stinner8c62be82010-05-06 00:08:46 +00008070 pid_t pid;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008071 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00008072 WAIT_TYPE status;
8073 WAIT_STATUS_INT(status) = 0;
Neal Norwitze241ce82003-02-17 18:17:05 +00008074
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008075 do {
8076 Py_BEGIN_ALLOW_THREADS
8077 pid = wait(&status);
8078 Py_END_ALLOW_THREADS
8079 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8080 if (pid < 0)
8081 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008082
Victor Stinner8c62be82010-05-06 00:08:46 +00008083 return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
Guido van Rossum85e3b011991-06-03 12:42:10 +00008084}
Larry Hastings2f936352014-08-05 14:04:04 +10008085#endif /* HAVE_WAIT */
Guido van Rossum85e3b011991-06-03 12:42:10 +00008086
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -08008087#if defined(__linux__) && defined(__NR_pidfd_open)
8088/*[clinic input]
8089os.pidfd_open
8090 pid: pid_t
8091 flags: unsigned_int = 0
8092
8093Return a file descriptor referring to the process *pid*.
8094
8095The descriptor can be used to perform process management without races and
8096signals.
8097[clinic start generated code]*/
8098
8099static PyObject *
8100os_pidfd_open_impl(PyObject *module, pid_t pid, unsigned int flags)
8101/*[clinic end generated code: output=5c7252698947dc41 input=c3fd99ce947ccfef]*/
8102{
8103 int fd = syscall(__NR_pidfd_open, pid, flags);
8104 if (fd < 0) {
8105 return posix_error();
8106 }
8107 return PyLong_FromLong(fd);
8108}
8109#endif
8110
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008111
Larry Hastings9cf065c2012-06-22 16:30:09 -07008112#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008113/*[clinic input]
8114os.readlink
8115
8116 path: path_t
8117 *
8118 dir_fd: dir_fd(requires='readlinkat') = None
8119
8120Return a string representing the path to which the symbolic link points.
8121
8122If dir_fd is not None, it should be a file descriptor open to a directory,
8123and path should be relative; path will then be relative to that directory.
8124
8125dir_fd may not be implemented on your platform. If it is unavailable,
8126using it will raise a NotImplementedError.
8127[clinic start generated code]*/
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008128
Barry Warsaw53699e91996-12-10 23:23:01 +00008129static PyObject *
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008130os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
8131/*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008132{
Berker Peksage0b5b202018-08-15 13:03:41 +03008133#if defined(HAVE_READLINK)
Christian Heimes3cb091e2016-09-23 20:24:28 +02008134 char buffer[MAXPATHLEN+1];
Larry Hastings9cf065c2012-06-22 16:30:09 -07008135 ssize_t length;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008136
8137 Py_BEGIN_ALLOW_THREADS
8138#ifdef HAVE_READLINKAT
8139 if (dir_fd != DEFAULT_DIR_FD)
8140 length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
8141 else
8142#endif
8143 length = readlink(path->narrow, buffer, MAXPATHLEN);
8144 Py_END_ALLOW_THREADS
8145
8146 if (length < 0) {
8147 return path_error(path);
8148 }
8149 buffer[length] = '\0';
8150
8151 if (PyUnicode_Check(path->object))
8152 return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
8153 else
8154 return PyBytes_FromStringAndSize(buffer, length);
Berker Peksage0b5b202018-08-15 13:03:41 +03008155#elif defined(MS_WINDOWS)
8156 DWORD n_bytes_returned;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008157 DWORD io_result = 0;
Berker Peksage0b5b202018-08-15 13:03:41 +03008158 HANDLE reparse_point_handle;
Berker Peksage0b5b202018-08-15 13:03:41 +03008159 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
8160 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Steve Dower993ac922019-09-03 12:50:51 -07008161 PyObject *result = NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00008162
Larry Hastings2f936352014-08-05 14:04:04 +10008163 /* First get a handle to the reparse point */
8164 Py_BEGIN_ALLOW_THREADS
8165 reparse_point_handle = CreateFileW(
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008166 path->wide,
Larry Hastings2f936352014-08-05 14:04:04 +10008167 0,
8168 0,
8169 0,
8170 OPEN_EXISTING,
8171 FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
8172 0);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008173 if (reparse_point_handle != INVALID_HANDLE_VALUE) {
8174 /* New call DeviceIoControl to read the reparse point */
8175 io_result = DeviceIoControl(
8176 reparse_point_handle,
8177 FSCTL_GET_REPARSE_POINT,
8178 0, 0, /* in buffer */
8179 target_buffer, sizeof(target_buffer),
8180 &n_bytes_returned,
8181 0 /* we're not using OVERLAPPED_IO */
8182 );
8183 CloseHandle(reparse_point_handle);
Berker Peksage0b5b202018-08-15 13:03:41 +03008184 }
Larry Hastings2f936352014-08-05 14:04:04 +10008185 Py_END_ALLOW_THREADS
8186
Berker Peksage0b5b202018-08-15 13:03:41 +03008187 if (io_result == 0) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008188 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03008189 }
Larry Hastings2f936352014-08-05 14:04:04 +10008190
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008191 wchar_t *name = NULL;
8192 Py_ssize_t nameLen = 0;
8193 if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
Larry Hastings2f936352014-08-05 14:04:04 +10008194 {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008195 name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
8196 rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
8197 nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
Larry Hastings2f936352014-08-05 14:04:04 +10008198 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008199 else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
8200 {
8201 name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
8202 rdb->MountPointReparseBuffer.SubstituteNameOffset);
8203 nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
8204 }
8205 else
8206 {
8207 PyErr_SetString(PyExc_ValueError, "not a symbolic link");
8208 }
8209 if (name) {
8210 if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
8211 /* Our buffer is mutable, so this is okay */
8212 name[1] = L'\\';
8213 }
8214 result = PyUnicode_FromWideChar(name, nameLen);
Steve Dower993ac922019-09-03 12:50:51 -07008215 if (result && path->narrow) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008216 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
8217 }
Berker Peksage0b5b202018-08-15 13:03:41 +03008218 }
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008219 return result;
Berker Peksage0b5b202018-08-15 13:03:41 +03008220#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008221}
Berker Peksage0b5b202018-08-15 13:03:41 +03008222#endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008223
Larry Hastings9cf065c2012-06-22 16:30:09 -07008224#if defined(MS_WINDOWS)
8225
Steve Dower6921e732018-03-05 14:26:08 -08008226/* Remove the last portion of the path - return 0 on success */
8227static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008228_dirnameW(WCHAR *path)
8229{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008230 WCHAR *ptr;
Steve Dower6921e732018-03-05 14:26:08 -08008231 size_t length = wcsnlen_s(path, MAX_PATH);
8232 if (length == MAX_PATH) {
8233 return -1;
8234 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008235
8236 /* walk the path from the end until a backslash is encountered */
Steve Dower6921e732018-03-05 14:26:08 -08008237 for(ptr = path + length; ptr != path; ptr--) {
8238 if (*ptr == L'\\' || *ptr == L'/') {
Jason R. Coombs3a092862013-05-27 23:21:28 -04008239 break;
Steve Dower6921e732018-03-05 14:26:08 -08008240 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008241 }
8242 *ptr = 0;
Steve Dower6921e732018-03-05 14:26:08 -08008243 return 0;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008244}
8245
Minmin Gong7f21c9a2020-05-18 09:17:19 -07008246#endif
8247
8248#ifdef HAVE_SYMLINK
8249
8250#if defined(MS_WINDOWS)
8251
Victor Stinner31b3b922013-06-05 01:49:17 +02008252/* Is this path absolute? */
8253static int
8254_is_absW(const WCHAR *path)
8255{
Steve Dower6921e732018-03-05 14:26:08 -08008256 return path[0] == L'\\' || path[0] == L'/' ||
8257 (path[0] && path[1] == L':');
Jason R. Coombs3a092862013-05-27 23:21:28 -04008258}
8259
Steve Dower6921e732018-03-05 14:26:08 -08008260/* join root and rest with a backslash - return 0 on success */
8261static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008262_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
8263{
Victor Stinner31b3b922013-06-05 01:49:17 +02008264 if (_is_absW(rest)) {
Steve Dower6921e732018-03-05 14:26:08 -08008265 return wcscpy_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008266 }
8267
Steve Dower6921e732018-03-05 14:26:08 -08008268 if (wcscpy_s(dest_path, MAX_PATH, root)) {
8269 return -1;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008270 }
Steve Dower6921e732018-03-05 14:26:08 -08008271
8272 if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
8273 return -1;
8274 }
8275
8276 return wcscat_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008277}
8278
Victor Stinner31b3b922013-06-05 01:49:17 +02008279/* Return True if the path at src relative to dest is a directory */
8280static int
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03008281_check_dirW(LPCWSTR src, LPCWSTR dest)
Jason R. Coombs3a092862013-05-27 23:21:28 -04008282{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008283 WIN32_FILE_ATTRIBUTE_DATA src_info;
8284 WCHAR dest_parent[MAX_PATH];
8285 WCHAR src_resolved[MAX_PATH] = L"";
8286
8287 /* dest_parent = os.path.dirname(dest) */
Steve Dower6921e732018-03-05 14:26:08 -08008288 if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
8289 _dirnameW(dest_parent)) {
8290 return 0;
8291 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008292 /* src_resolved = os.path.join(dest_parent, src) */
Steve Dower6921e732018-03-05 14:26:08 -08008293 if (_joinW(src_resolved, dest_parent, src)) {
8294 return 0;
8295 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008296 return (
8297 GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
8298 && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
8299 );
8300}
Larry Hastings9cf065c2012-06-22 16:30:09 -07008301#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008302
Larry Hastings2f936352014-08-05 14:04:04 +10008303
8304/*[clinic input]
8305os.symlink
8306 src: path_t
8307 dst: path_t
8308 target_is_directory: bool = False
8309 *
8310 dir_fd: dir_fd(requires='symlinkat')=None
8311
8312# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
8313
8314Create a symbolic link pointing to src named dst.
8315
8316target_is_directory is required on Windows if the target is to be
8317 interpreted as a directory. (On Windows, symlink requires
8318 Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
8319 target_is_directory is ignored on non-Windows platforms.
8320
8321If dir_fd is not None, it should be a file descriptor open to a directory,
8322 and path should be relative; path will then be relative to that directory.
8323dir_fd may not be implemented on your platform.
8324 If it is unavailable, using it will raise a NotImplementedError.
8325
8326[clinic start generated code]*/
8327
Larry Hastings2f936352014-08-05 14:04:04 +10008328static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008329os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
Larry Hastings89964c42015-04-14 18:07:59 -04008330 int target_is_directory, int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008331/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008332{
Larry Hastings9cf065c2012-06-22 16:30:09 -07008333#ifdef MS_WINDOWS
8334 DWORD result;
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008335 DWORD flags = 0;
8336
8337 /* Assumed true, set to false if detected to not be available. */
8338 static int windows_has_symlink_unprivileged_flag = TRUE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008339#else
8340 int result;
8341#endif
8342
Saiyang Gou7514f4f2020-02-12 23:47:42 -08008343 if (PySys_Audit("os.symlink", "OOi", src->object, dst->object,
8344 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
8345 return NULL;
8346 }
8347
Larry Hastings9cf065c2012-06-22 16:30:09 -07008348#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008349
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008350 if (windows_has_symlink_unprivileged_flag) {
8351 /* Allow non-admin symlinks if system allows it. */
8352 flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
8353 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008354
Larry Hastings9cf065c2012-06-22 16:30:09 -07008355 Py_BEGIN_ALLOW_THREADS
Steve Dower6921e732018-03-05 14:26:08 -08008356 _Py_BEGIN_SUPPRESS_IPH
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008357 /* if src is a directory, ensure flags==1 (target_is_directory bit) */
8358 if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
8359 flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
8360 }
8361
8362 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
Steve Dower6921e732018-03-05 14:26:08 -08008363 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07008364 Py_END_ALLOW_THREADS
8365
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008366 if (windows_has_symlink_unprivileged_flag && !result &&
8367 ERROR_INVALID_PARAMETER == GetLastError()) {
8368
8369 Py_BEGIN_ALLOW_THREADS
8370 _Py_BEGIN_SUPPRESS_IPH
8371 /* This error might be caused by
8372 SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
8373 Try again, and update windows_has_symlink_unprivileged_flag if we
8374 are successful this time.
8375
8376 NOTE: There is a risk of a race condition here if there are other
8377 conditions than the flag causing ERROR_INVALID_PARAMETER, and
8378 another process (or thread) changes that condition in between our
8379 calls to CreateSymbolicLink.
8380 */
8381 flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
8382 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
8383 _Py_END_SUPPRESS_IPH
8384 Py_END_ALLOW_THREADS
8385
8386 if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
8387 windows_has_symlink_unprivileged_flag = FALSE;
8388 }
8389 }
8390
Larry Hastings2f936352014-08-05 14:04:04 +10008391 if (!result)
8392 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008393
8394#else
8395
Steve Dower6921e732018-03-05 14:26:08 -08008396 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
8397 PyErr_SetString(PyExc_ValueError,
8398 "symlink: src and dst must be the same type");
8399 return NULL;
8400 }
8401
Larry Hastings9cf065c2012-06-22 16:30:09 -07008402 Py_BEGIN_ALLOW_THREADS
8403#if HAVE_SYMLINKAT
8404 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10008405 result = symlinkat(src->narrow, dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008406 else
8407#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008408 result = symlink(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008409 Py_END_ALLOW_THREADS
8410
Larry Hastings2f936352014-08-05 14:04:04 +10008411 if (result)
8412 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008413#endif
8414
Larry Hastings2f936352014-08-05 14:04:04 +10008415 Py_RETURN_NONE;
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008416}
8417#endif /* HAVE_SYMLINK */
8418
Larry Hastings9cf065c2012-06-22 16:30:09 -07008419
Brian Curtind40e6f72010-07-08 21:39:08 +00008420
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008421
Larry Hastings605a62d2012-06-24 04:33:36 -07008422static PyStructSequence_Field times_result_fields[] = {
8423 {"user", "user time"},
8424 {"system", "system time"},
8425 {"children_user", "user time of children"},
8426 {"children_system", "system time of children"},
8427 {"elapsed", "elapsed time since an arbitrary point in the past"},
8428 {NULL}
8429};
8430
8431PyDoc_STRVAR(times_result__doc__,
8432"times_result: Result from os.times().\n\n\
8433This object may be accessed either as a tuple of\n\
8434 (user, system, children_user, children_system, elapsed),\n\
8435or via the attributes user, system, children_user, children_system,\n\
8436and elapsed.\n\
8437\n\
8438See os.times for more information.");
8439
8440static PyStructSequence_Desc times_result_desc = {
8441 "times_result", /* name */
8442 times_result__doc__, /* doc */
8443 times_result_fields,
8444 5
8445};
8446
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008447#ifdef MS_WINDOWS
8448#define HAVE_TIMES /* mandatory, for the method table */
8449#endif
Larry Hastings605a62d2012-06-24 04:33:36 -07008450
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008451#ifdef HAVE_TIMES
Larry Hastings605a62d2012-06-24 04:33:36 -07008452
8453static PyObject *
Victor Stinner1c2fa782020-05-10 11:05:29 +02008454build_times_result(PyObject *module, double user, double system,
Larry Hastings605a62d2012-06-24 04:33:36 -07008455 double children_user, double children_system,
8456 double elapsed)
8457{
Victor Stinner1c2fa782020-05-10 11:05:29 +02008458 PyObject *TimesResultType = get_posix_state(module)->TimesResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -08008459 PyObject *value = PyStructSequence_New((PyTypeObject *)TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07008460 if (value == NULL)
8461 return NULL;
8462
8463#define SET(i, field) \
8464 { \
8465 PyObject *o = PyFloat_FromDouble(field); \
8466 if (!o) { \
8467 Py_DECREF(value); \
8468 return NULL; \
8469 } \
8470 PyStructSequence_SET_ITEM(value, i, o); \
8471 } \
8472
8473 SET(0, user);
8474 SET(1, system);
8475 SET(2, children_user);
8476 SET(3, children_system);
8477 SET(4, elapsed);
8478
8479#undef SET
8480
8481 return value;
8482}
8483
Larry Hastings605a62d2012-06-24 04:33:36 -07008484
Larry Hastings2f936352014-08-05 14:04:04 +10008485#ifndef MS_WINDOWS
8486#define NEED_TICKS_PER_SECOND
8487static long ticks_per_second = -1;
8488#endif /* MS_WINDOWS */
8489
8490/*[clinic input]
8491os.times
8492
8493Return a collection containing process timing information.
8494
8495The object returned behaves like a named tuple with these fields:
8496 (utime, stime, cutime, cstime, elapsed_time)
8497All fields are floating point numbers.
8498[clinic start generated code]*/
8499
Larry Hastings2f936352014-08-05 14:04:04 +10008500static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008501os_times_impl(PyObject *module)
8502/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008503#ifdef MS_WINDOWS
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008504{
Victor Stinner8c62be82010-05-06 00:08:46 +00008505 FILETIME create, exit, kernel, user;
8506 HANDLE hProc;
8507 hProc = GetCurrentProcess();
8508 GetProcessTimes(hProc, &create, &exit, &kernel, &user);
8509 /* The fields of a FILETIME structure are the hi and lo part
8510 of a 64-bit value expressed in 100 nanosecond units.
8511 1e7 is one second in such units; 1e-7 the inverse.
8512 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
8513 */
Victor Stinner1c2fa782020-05-10 11:05:29 +02008514 return build_times_result(module,
Victor Stinner8c62be82010-05-06 00:08:46 +00008515 (double)(user.dwHighDateTime*429.4967296 +
8516 user.dwLowDateTime*1e-7),
8517 (double)(kernel.dwHighDateTime*429.4967296 +
8518 kernel.dwLowDateTime*1e-7),
8519 (double)0,
8520 (double)0,
8521 (double)0);
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008522}
Larry Hastings2f936352014-08-05 14:04:04 +10008523#else /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008524{
Larry Hastings2f936352014-08-05 14:04:04 +10008525
8526
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008527 struct tms t;
8528 clock_t c;
8529 errno = 0;
8530 c = times(&t);
8531 if (c == (clock_t) -1)
8532 return posix_error();
Victor Stinner1c2fa782020-05-10 11:05:29 +02008533 return build_times_result(module,
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008534 (double)t.tms_utime / ticks_per_second,
8535 (double)t.tms_stime / ticks_per_second,
8536 (double)t.tms_cutime / ticks_per_second,
8537 (double)t.tms_cstime / ticks_per_second,
8538 (double)c / ticks_per_second);
8539}
Larry Hastings2f936352014-08-05 14:04:04 +10008540#endif /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008541#endif /* HAVE_TIMES */
8542
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008543
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008544#ifdef HAVE_GETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008545/*[clinic input]
8546os.getsid
8547
8548 pid: pid_t
8549 /
8550
8551Call the system call getsid(pid) and return the result.
8552[clinic start generated code]*/
8553
Larry Hastings2f936352014-08-05 14:04:04 +10008554static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008555os_getsid_impl(PyObject *module, pid_t pid)
8556/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008557{
Victor Stinner8c62be82010-05-06 00:08:46 +00008558 int sid;
Victor Stinner8c62be82010-05-06 00:08:46 +00008559 sid = getsid(pid);
8560 if (sid < 0)
8561 return posix_error();
8562 return PyLong_FromLong((long)sid);
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008563}
8564#endif /* HAVE_GETSID */
8565
8566
Guido van Rossumb6775db1994-08-01 11:34:53 +00008567#ifdef HAVE_SETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008568/*[clinic input]
8569os.setsid
8570
8571Call the system call setsid().
8572[clinic start generated code]*/
8573
Larry Hastings2f936352014-08-05 14:04:04 +10008574static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008575os_setsid_impl(PyObject *module)
8576/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00008577{
Victor Stinner8c62be82010-05-06 00:08:46 +00008578 if (setsid() < 0)
8579 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008580 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008581}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008582#endif /* HAVE_SETSID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008583
Larry Hastings2f936352014-08-05 14:04:04 +10008584
Guido van Rossumb6775db1994-08-01 11:34:53 +00008585#ifdef HAVE_SETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10008586/*[clinic input]
8587os.setpgid
8588
8589 pid: pid_t
8590 pgrp: pid_t
8591 /
8592
8593Call the system call setpgid(pid, pgrp).
8594[clinic start generated code]*/
8595
Larry Hastings2f936352014-08-05 14:04:04 +10008596static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008597os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
8598/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008599{
Victor Stinner8c62be82010-05-06 00:08:46 +00008600 if (setpgid(pid, pgrp) < 0)
8601 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008602 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008603}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008604#endif /* HAVE_SETPGID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008605
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008606
Guido van Rossumb6775db1994-08-01 11:34:53 +00008607#ifdef HAVE_TCGETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008608/*[clinic input]
8609os.tcgetpgrp
8610
8611 fd: int
8612 /
8613
8614Return the process group associated with the terminal specified by fd.
8615[clinic start generated code]*/
8616
Larry Hastings2f936352014-08-05 14:04:04 +10008617static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008618os_tcgetpgrp_impl(PyObject *module, int fd)
8619/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008620{
8621 pid_t pgid = tcgetpgrp(fd);
Victor Stinner8c62be82010-05-06 00:08:46 +00008622 if (pgid < 0)
8623 return posix_error();
8624 return PyLong_FromPid(pgid);
Guido van Rossum7066dd71992-09-17 17:54:56 +00008625}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008626#endif /* HAVE_TCGETPGRP */
Guido van Rossum7066dd71992-09-17 17:54:56 +00008627
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008628
Guido van Rossumb6775db1994-08-01 11:34:53 +00008629#ifdef HAVE_TCSETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008630/*[clinic input]
8631os.tcsetpgrp
8632
8633 fd: int
8634 pgid: pid_t
8635 /
8636
8637Set the process group associated with the terminal specified by fd.
8638[clinic start generated code]*/
8639
Larry Hastings2f936352014-08-05 14:04:04 +10008640static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008641os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
8642/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008643{
Victor Stinner8c62be82010-05-06 00:08:46 +00008644 if (tcsetpgrp(fd, pgid) < 0)
8645 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008646 Py_RETURN_NONE;
Guido van Rossum7066dd71992-09-17 17:54:56 +00008647}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008648#endif /* HAVE_TCSETPGRP */
Guido van Rossum22db57e1992-04-05 14:25:30 +00008649
Guido van Rossum687dd131993-05-17 08:34:16 +00008650/* Functions acting on file descriptors */
8651
Victor Stinnerdaf45552013-08-28 00:53:59 +02008652#ifdef O_CLOEXEC
8653extern int _Py_open_cloexec_works;
8654#endif
8655
Larry Hastings2f936352014-08-05 14:04:04 +10008656
8657/*[clinic input]
8658os.open -> int
8659 path: path_t
8660 flags: int
8661 mode: int = 0o777
8662 *
8663 dir_fd: dir_fd(requires='openat') = None
8664
8665# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
8666
8667Open a file for low level IO. Returns a file descriptor (integer).
8668
8669If dir_fd is not None, it should be a file descriptor open to a directory,
8670 and path should be relative; path will then be relative to that directory.
8671dir_fd may not be implemented on your platform.
8672 If it is unavailable, using it will raise a NotImplementedError.
8673[clinic start generated code]*/
8674
Larry Hastings2f936352014-08-05 14:04:04 +10008675static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008676os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
8677/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008678{
8679 int fd;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008680 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008681
Victor Stinnerdaf45552013-08-28 00:53:59 +02008682#ifdef O_CLOEXEC
8683 int *atomic_flag_works = &_Py_open_cloexec_works;
8684#elif !defined(MS_WINDOWS)
8685 int *atomic_flag_works = NULL;
8686#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +00008687
Victor Stinnerdaf45552013-08-28 00:53:59 +02008688#ifdef MS_WINDOWS
8689 flags |= O_NOINHERIT;
8690#elif defined(O_CLOEXEC)
8691 flags |= O_CLOEXEC;
8692#endif
8693
Steve Dowerb82e17e2019-05-23 08:45:22 -07008694 if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
8695 return -1;
8696 }
8697
Steve Dower8fc89802015-04-12 00:26:27 -04008698 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008699 do {
8700 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008701#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07008702 fd = _wopen(path->wide, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008703#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07008704#ifdef HAVE_OPENAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008705 if (dir_fd != DEFAULT_DIR_FD)
8706 fd = openat(dir_fd, path->narrow, flags, mode);
8707 else
Steve Dower6230aaf2016-09-09 09:03:15 -07008708#endif /* HAVE_OPENAT */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008709 fd = open(path->narrow, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008710#endif /* !MS_WINDOWS */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008711 Py_END_ALLOW_THREADS
8712 } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04008713 _Py_END_SUPPRESS_IPH
Guido van Rossum687dd131993-05-17 08:34:16 +00008714
Victor Stinnerd3ffd322015-09-15 10:11:03 +02008715 if (fd < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008716 if (!async_err)
8717 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Larry Hastings2f936352014-08-05 14:04:04 +10008718 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008719 }
8720
Victor Stinnerdaf45552013-08-28 00:53:59 +02008721#ifndef MS_WINDOWS
8722 if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
8723 close(fd);
Larry Hastings2f936352014-08-05 14:04:04 +10008724 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008725 }
8726#endif
8727
Larry Hastings2f936352014-08-05 14:04:04 +10008728 return fd;
8729}
8730
8731
8732/*[clinic input]
8733os.close
8734
8735 fd: int
8736
8737Close a file descriptor.
8738[clinic start generated code]*/
8739
Barry Warsaw53699e91996-12-10 23:23:01 +00008740static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008741os_close_impl(PyObject *module, int fd)
8742/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00008743{
Larry Hastings2f936352014-08-05 14:04:04 +10008744 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008745 /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
8746 * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
8747 * for more details.
8748 */
Victor Stinner8c62be82010-05-06 00:08:46 +00008749 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008750 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008751 res = close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04008752 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008753 Py_END_ALLOW_THREADS
8754 if (res < 0)
8755 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008756 Py_RETURN_NONE;
Guido van Rossum687dd131993-05-17 08:34:16 +00008757}
8758
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008759
Jakub Kulíke20134f2019-09-11 17:11:57 +02008760#ifdef HAVE_FDWALK
8761static int
8762_fdwalk_close_func(void *lohi, int fd)
8763{
8764 int lo = ((int *)lohi)[0];
8765 int hi = ((int *)lohi)[1];
8766
Victor Stinner162c5672020-04-24 12:00:51 +02008767 if (fd >= hi) {
Jakub Kulíke20134f2019-09-11 17:11:57 +02008768 return 1;
Victor Stinner162c5672020-04-24 12:00:51 +02008769 }
8770 else if (fd >= lo) {
8771 /* Ignore errors */
8772 (void)close(fd);
8773 }
Jakub Kulíke20134f2019-09-11 17:11:57 +02008774 return 0;
8775}
8776#endif /* HAVE_FDWALK */
8777
Larry Hastings2f936352014-08-05 14:04:04 +10008778/*[clinic input]
8779os.closerange
8780
8781 fd_low: int
8782 fd_high: int
8783 /
8784
8785Closes all file descriptors in [fd_low, fd_high), ignoring errors.
8786[clinic start generated code]*/
8787
Larry Hastings2f936352014-08-05 14:04:04 +10008788static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008789os_closerange_impl(PyObject *module, int fd_low, int fd_high)
8790/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008791{
Jakub Kulíke20134f2019-09-11 17:11:57 +02008792#ifdef HAVE_FDWALK
8793 int lohi[2];
Jakub Kulíke20134f2019-09-11 17:11:57 +02008794#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00008795 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008796 _Py_BEGIN_SUPPRESS_IPH
Jakub Kulíke20134f2019-09-11 17:11:57 +02008797#ifdef HAVE_FDWALK
8798 lohi[0] = Py_MAX(fd_low, 0);
8799 lohi[1] = fd_high;
8800 fdwalk(_fdwalk_close_func, lohi);
8801#else
Victor Stinner162c5672020-04-24 12:00:51 +02008802 fd_low = Py_MAX(fd_low, 0);
8803#ifdef __FreeBSD__
8804 if (fd_high >= sysconf(_SC_OPEN_MAX)) {
8805 /* Any errors encountered while closing file descriptors are ignored */
8806 closefrom(fd_low);
8807 }
8808 else
8809#endif
8810 {
8811 for (int i = fd_low; i < fd_high; i++) {
8812 /* Ignore errors */
8813 (void)close(i);
8814 }
8815 }
Jakub Kulíke20134f2019-09-11 17:11:57 +02008816#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008817 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008818 Py_END_ALLOW_THREADS
8819 Py_RETURN_NONE;
Christian Heimesfdab48e2008-01-20 09:06:41 +00008820}
8821
8822
Larry Hastings2f936352014-08-05 14:04:04 +10008823/*[clinic input]
8824os.dup -> int
8825
8826 fd: int
8827 /
8828
8829Return a duplicate of a file descriptor.
8830[clinic start generated code]*/
8831
Larry Hastings2f936352014-08-05 14:04:04 +10008832static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008833os_dup_impl(PyObject *module, int fd)
8834/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008835{
8836 return _Py_dup(fd);
Guido van Rossum687dd131993-05-17 08:34:16 +00008837}
8838
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008839
Larry Hastings2f936352014-08-05 14:04:04 +10008840/*[clinic input]
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008841os.dup2 -> int
Larry Hastings2f936352014-08-05 14:04:04 +10008842 fd: int
8843 fd2: int
8844 inheritable: bool=True
8845
8846Duplicate file descriptor.
8847[clinic start generated code]*/
8848
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008849static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008850os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008851/*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008852{
Stéphane Wirtel3d86e482018-01-30 07:04:36 +01008853 int res = 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008854#if defined(HAVE_DUP3) && \
8855 !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
8856 /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
Alexey Izbyshevb3caf382018-02-20 10:25:46 +03008857 static int dup3_works = -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008858#endif
8859
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008860 if (fd < 0 || fd2 < 0) {
8861 posix_error();
8862 return -1;
8863 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008864
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008865 /* dup2() can fail with EINTR if the target FD is already open, because it
8866 * then has to be closed. See os_close_impl() for why we don't handle EINTR
8867 * upon close(), and therefore below.
8868 */
Victor Stinnerdaf45552013-08-28 00:53:59 +02008869#ifdef MS_WINDOWS
8870 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008871 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008872 res = dup2(fd, fd2);
Steve Dower8fc89802015-04-12 00:26:27 -04008873 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02008874 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008875 if (res < 0) {
8876 posix_error();
8877 return -1;
8878 }
8879 res = fd2; // msvcrt dup2 returns 0 on success.
Victor Stinnerdaf45552013-08-28 00:53:59 +02008880
8881 /* Character files like console cannot be make non-inheritable */
8882 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8883 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008884 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008885 }
8886
8887#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
8888 Py_BEGIN_ALLOW_THREADS
8889 if (!inheritable)
8890 res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
8891 else
8892 res = dup2(fd, fd2);
8893 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008894 if (res < 0) {
8895 posix_error();
8896 return -1;
8897 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008898
8899#else
8900
8901#ifdef HAVE_DUP3
8902 if (!inheritable && dup3_works != 0) {
8903 Py_BEGIN_ALLOW_THREADS
8904 res = dup3(fd, fd2, O_CLOEXEC);
8905 Py_END_ALLOW_THREADS
8906 if (res < 0) {
8907 if (dup3_works == -1)
8908 dup3_works = (errno != ENOSYS);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008909 if (dup3_works) {
8910 posix_error();
8911 return -1;
8912 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008913 }
8914 }
8915
8916 if (inheritable || dup3_works == 0)
8917 {
8918#endif
8919 Py_BEGIN_ALLOW_THREADS
8920 res = dup2(fd, fd2);
8921 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008922 if (res < 0) {
8923 posix_error();
8924 return -1;
8925 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008926
8927 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8928 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008929 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008930 }
8931#ifdef HAVE_DUP3
8932 }
8933#endif
8934
8935#endif
8936
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008937 return res;
Guido van Rossum687dd131993-05-17 08:34:16 +00008938}
8939
Larry Hastings2f936352014-08-05 14:04:04 +10008940
Ross Lagerwall7807c352011-03-17 20:20:30 +02008941#ifdef HAVE_LOCKF
Larry Hastings2f936352014-08-05 14:04:04 +10008942/*[clinic input]
8943os.lockf
8944
8945 fd: int
8946 An open file descriptor.
8947 command: int
8948 One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
8949 length: Py_off_t
8950 The number of bytes to lock, starting at the current position.
8951 /
8952
8953Apply, test or remove a POSIX lock on an open file descriptor.
8954
8955[clinic start generated code]*/
8956
Larry Hastings2f936352014-08-05 14:04:04 +10008957static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008958os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
8959/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008960{
8961 int res;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008962
Saiyang Gou7514f4f2020-02-12 23:47:42 -08008963 if (PySys_Audit("os.lockf", "iiL", fd, command, length) < 0) {
8964 return NULL;
8965 }
8966
Ross Lagerwall7807c352011-03-17 20:20:30 +02008967 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008968 res = lockf(fd, command, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008969 Py_END_ALLOW_THREADS
8970
8971 if (res < 0)
8972 return posix_error();
8973
8974 Py_RETURN_NONE;
8975}
Larry Hastings2f936352014-08-05 14:04:04 +10008976#endif /* HAVE_LOCKF */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008977
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008978
Larry Hastings2f936352014-08-05 14:04:04 +10008979/*[clinic input]
8980os.lseek -> Py_off_t
8981
8982 fd: int
8983 position: Py_off_t
8984 how: int
8985 /
8986
8987Set the position of a file descriptor. Return the new position.
8988
8989Return the new cursor position in number of bytes
8990relative to the beginning of the file.
8991[clinic start generated code]*/
8992
Larry Hastings2f936352014-08-05 14:04:04 +10008993static Py_off_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008994os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
8995/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008996{
8997 Py_off_t result;
8998
Guido van Rossum687dd131993-05-17 08:34:16 +00008999#ifdef SEEK_SET
Victor Stinner8c62be82010-05-06 00:08:46 +00009000 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
9001 switch (how) {
Larry Hastings2f936352014-08-05 14:04:04 +10009002 case 0: how = SEEK_SET; break;
9003 case 1: how = SEEK_CUR; break;
9004 case 2: how = SEEK_END; break;
Victor Stinner8c62be82010-05-06 00:08:46 +00009005 }
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00009006#endif /* SEEK_END */
Guido van Rossum94f6f721999-01-06 18:42:14 +00009007
Victor Stinner8c62be82010-05-06 00:08:46 +00009008 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009009 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner14b9b112013-06-25 00:37:25 +02009010#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009011 result = _lseeki64(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00009012#else
Larry Hastings2f936352014-08-05 14:04:04 +10009013 result = lseek(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00009014#endif
Steve Dower8fc89802015-04-12 00:26:27 -04009015 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00009016 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009017 if (result < 0)
9018 posix_error();
Guido van Rossum94f6f721999-01-06 18:42:14 +00009019
Larry Hastings2f936352014-08-05 14:04:04 +10009020 return result;
Guido van Rossum687dd131993-05-17 08:34:16 +00009021}
9022
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009023
Larry Hastings2f936352014-08-05 14:04:04 +10009024/*[clinic input]
9025os.read
9026 fd: int
9027 length: Py_ssize_t
9028 /
9029
9030Read from a file descriptor. Returns a bytes object.
9031[clinic start generated code]*/
9032
Larry Hastings2f936352014-08-05 14:04:04 +10009033static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009034os_read_impl(PyObject *module, int fd, Py_ssize_t length)
9035/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009036{
Victor Stinner8c62be82010-05-06 00:08:46 +00009037 Py_ssize_t n;
9038 PyObject *buffer;
Larry Hastings2f936352014-08-05 14:04:04 +10009039
9040 if (length < 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00009041 errno = EINVAL;
9042 return posix_error();
9043 }
Larry Hastings2f936352014-08-05 14:04:04 +10009044
Victor Stinner9a0d7a72018-11-22 15:03:40 +01009045 length = Py_MIN(length, _PY_READ_MAX);
Larry Hastings2f936352014-08-05 14:04:04 +10009046
9047 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Victor Stinner8c62be82010-05-06 00:08:46 +00009048 if (buffer == NULL)
9049 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009050
Victor Stinner66aab0c2015-03-19 22:53:20 +01009051 n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
9052 if (n == -1) {
Victor Stinner8c62be82010-05-06 00:08:46 +00009053 Py_DECREF(buffer);
Victor Stinner66aab0c2015-03-19 22:53:20 +01009054 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00009055 }
Larry Hastings2f936352014-08-05 14:04:04 +10009056
9057 if (n != length)
Victor Stinner8c62be82010-05-06 00:08:46 +00009058 _PyBytes_Resize(&buffer, n);
Larry Hastings2f936352014-08-05 14:04:04 +10009059
Victor Stinner8c62be82010-05-06 00:08:46 +00009060 return buffer;
Guido van Rossum687dd131993-05-17 08:34:16 +00009061}
9062
Ross Lagerwall7807c352011-03-17 20:20:30 +02009063#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009064 || defined(__APPLE__))) \
9065 || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
9066 || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
9067static int
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009068iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009069{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009070 Py_ssize_t i, j;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009071
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009072 *iov = PyMem_New(struct iovec, cnt);
9073 if (*iov == NULL) {
9074 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01009075 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009076 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009077
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009078 *buf = PyMem_New(Py_buffer, cnt);
9079 if (*buf == NULL) {
9080 PyMem_Del(*iov);
9081 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01009082 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009083 }
9084
9085 for (i = 0; i < cnt; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02009086 PyObject *item = PySequence_GetItem(seq, i);
9087 if (item == NULL)
9088 goto fail;
9089 if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
9090 Py_DECREF(item);
9091 goto fail;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009092 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02009093 Py_DECREF(item);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009094 (*iov)[i].iov_base = (*buf)[i].buf;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009095 (*iov)[i].iov_len = (*buf)[i].len;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009096 }
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009097 return 0;
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02009098
9099fail:
9100 PyMem_Del(*iov);
9101 for (j = 0; j < i; j++) {
9102 PyBuffer_Release(&(*buf)[j]);
9103 }
9104 PyMem_Del(*buf);
Victor Stinner57ddf782014-01-08 15:21:28 +01009105 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009106}
9107
9108static void
9109iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
9110{
9111 int i;
9112 PyMem_Del(iov);
9113 for (i = 0; i < cnt; i++) {
9114 PyBuffer_Release(&buf[i]);
9115 }
9116 PyMem_Del(buf);
9117}
9118#endif
9119
Larry Hastings2f936352014-08-05 14:04:04 +10009120
Ross Lagerwall7807c352011-03-17 20:20:30 +02009121#ifdef HAVE_READV
Larry Hastings2f936352014-08-05 14:04:04 +10009122/*[clinic input]
9123os.readv -> Py_ssize_t
9124
9125 fd: int
9126 buffers: object
9127 /
9128
9129Read from a file descriptor fd into an iterable of buffers.
9130
9131The buffers should be mutable buffers accepting bytes.
9132readv will transfer data into each buffer until it is full
9133and then move on to the next buffer in the sequence to hold
9134the rest of the data.
9135
9136readv returns the total number of bytes read,
9137which may be less than the total capacity of all the buffers.
9138[clinic start generated code]*/
9139
Larry Hastings2f936352014-08-05 14:04:04 +10009140static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009141os_readv_impl(PyObject *module, int fd, PyObject *buffers)
9142/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009143{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009144 Py_ssize_t cnt, n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009145 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009146 struct iovec *iov;
9147 Py_buffer *buf;
9148
Larry Hastings2f936352014-08-05 14:04:04 +10009149 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009150 PyErr_SetString(PyExc_TypeError,
9151 "readv() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009152 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009153 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02009154
Larry Hastings2f936352014-08-05 14:04:04 +10009155 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009156 if (cnt < 0)
9157 return -1;
Larry Hastings2f936352014-08-05 14:04:04 +10009158
9159 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
9160 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009161
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009162 do {
9163 Py_BEGIN_ALLOW_THREADS
9164 n = readv(fd, iov, cnt);
9165 Py_END_ALLOW_THREADS
9166 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009167
9168 iov_cleanup(iov, buf, cnt);
Larry Hastings2f936352014-08-05 14:04:04 +10009169 if (n < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009170 if (!async_err)
9171 posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10009172 return -1;
9173 }
Victor Stinner57ddf782014-01-08 15:21:28 +01009174
Larry Hastings2f936352014-08-05 14:04:04 +10009175 return n;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009176}
Larry Hastings2f936352014-08-05 14:04:04 +10009177#endif /* HAVE_READV */
9178
Ross Lagerwall7807c352011-03-17 20:20:30 +02009179
9180#ifdef HAVE_PREAD
Larry Hastings2f936352014-08-05 14:04:04 +10009181/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10009182os.pread
9183
9184 fd: int
Dong-hee Naad7736f2019-09-25 14:47:04 +09009185 length: Py_ssize_t
Larry Hastings2f936352014-08-05 14:04:04 +10009186 offset: Py_off_t
9187 /
9188
9189Read a number of bytes from a file descriptor starting at a particular offset.
9190
9191Read length bytes from file descriptor fd, starting at offset bytes from
9192the beginning of the file. The file offset remains unchanged.
9193[clinic start generated code]*/
9194
Larry Hastings2f936352014-08-05 14:04:04 +10009195static PyObject *
Dong-hee Naad7736f2019-09-25 14:47:04 +09009196os_pread_impl(PyObject *module, int fd, Py_ssize_t length, Py_off_t offset)
9197/*[clinic end generated code: output=3f875c1eef82e32f input=85cb4a5589627144]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009198{
Ross Lagerwall7807c352011-03-17 20:20:30 +02009199 Py_ssize_t n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009200 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009201 PyObject *buffer;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009202
Larry Hastings2f936352014-08-05 14:04:04 +10009203 if (length < 0) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009204 errno = EINVAL;
9205 return posix_error();
9206 }
Larry Hastings2f936352014-08-05 14:04:04 +10009207 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02009208 if (buffer == NULL)
9209 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009210
9211 do {
9212 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009213 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009214 n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009215 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009216 Py_END_ALLOW_THREADS
9217 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9218
Ross Lagerwall7807c352011-03-17 20:20:30 +02009219 if (n < 0) {
9220 Py_DECREF(buffer);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009221 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009222 }
Larry Hastings2f936352014-08-05 14:04:04 +10009223 if (n != length)
Ross Lagerwall7807c352011-03-17 20:20:30 +02009224 _PyBytes_Resize(&buffer, n);
9225 return buffer;
9226}
Larry Hastings2f936352014-08-05 14:04:04 +10009227#endif /* HAVE_PREAD */
Ross Lagerwall7807c352011-03-17 20:20:30 +02009228
Pablo Galindo4defba32018-01-27 16:16:37 +00009229#if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
9230/*[clinic input]
9231os.preadv -> Py_ssize_t
9232
9233 fd: int
9234 buffers: object
9235 offset: Py_off_t
9236 flags: int = 0
9237 /
9238
9239Reads from a file descriptor into a number of mutable bytes-like objects.
9240
9241Combines the functionality of readv() and pread(). As readv(), it will
9242transfer data into each buffer until it is full and then move on to the next
9243buffer in the sequence to hold the rest of the data. Its fourth argument,
9244specifies the file offset at which the input operation is to be performed. It
9245will return the total number of bytes read (which can be less than the total
9246capacity of all the objects).
9247
9248The flags argument contains a bitwise OR of zero or more of the following flags:
9249
9250- RWF_HIPRI
9251- RWF_NOWAIT
9252
9253Using non-zero flags requires Linux 4.6 or newer.
9254[clinic start generated code]*/
9255
9256static Py_ssize_t
9257os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9258 int flags)
9259/*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
9260{
9261 Py_ssize_t cnt, n;
9262 int async_err = 0;
9263 struct iovec *iov;
9264 Py_buffer *buf;
9265
9266 if (!PySequence_Check(buffers)) {
9267 PyErr_SetString(PyExc_TypeError,
9268 "preadv2() arg 2 must be a sequence");
9269 return -1;
9270 }
9271
9272 cnt = PySequence_Size(buffers);
9273 if (cnt < 0) {
9274 return -1;
9275 }
9276
9277#ifndef HAVE_PREADV2
9278 if(flags != 0) {
9279 argument_unavailable_error("preadv2", "flags");
9280 return -1;
9281 }
9282#endif
9283
9284 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
9285 return -1;
9286 }
9287#ifdef HAVE_PREADV2
9288 do {
9289 Py_BEGIN_ALLOW_THREADS
9290 _Py_BEGIN_SUPPRESS_IPH
9291 n = preadv2(fd, iov, cnt, offset, flags);
9292 _Py_END_SUPPRESS_IPH
9293 Py_END_ALLOW_THREADS
9294 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9295#else
9296 do {
9297 Py_BEGIN_ALLOW_THREADS
9298 _Py_BEGIN_SUPPRESS_IPH
9299 n = preadv(fd, iov, cnt, offset);
9300 _Py_END_SUPPRESS_IPH
9301 Py_END_ALLOW_THREADS
9302 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9303#endif
9304
9305 iov_cleanup(iov, buf, cnt);
9306 if (n < 0) {
9307 if (!async_err) {
9308 posix_error();
9309 }
9310 return -1;
9311 }
9312
9313 return n;
9314}
9315#endif /* HAVE_PREADV */
9316
Larry Hastings2f936352014-08-05 14:04:04 +10009317
9318/*[clinic input]
9319os.write -> Py_ssize_t
9320
9321 fd: int
9322 data: Py_buffer
9323 /
9324
9325Write a bytes object to a file descriptor.
9326[clinic start generated code]*/
9327
Larry Hastings2f936352014-08-05 14:04:04 +10009328static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009329os_write_impl(PyObject *module, int fd, Py_buffer *data)
9330/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009331{
Victor Stinner66aab0c2015-03-19 22:53:20 +01009332 return _Py_write(fd, data->buf, data->len);
Ross Lagerwall7807c352011-03-17 20:20:30 +02009333}
9334
9335#ifdef HAVE_SENDFILE
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009336#ifdef __APPLE__
9337/*[clinic input]
9338os.sendfile
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009339
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009340 out_fd: int
9341 in_fd: int
9342 offset: Py_off_t
9343 count as sbytes: Py_off_t
9344 headers: object(c_default="NULL") = ()
9345 trailers: object(c_default="NULL") = ()
9346 flags: int = 0
9347
9348Copy count bytes from file descriptor in_fd to file descriptor out_fd.
9349[clinic start generated code]*/
9350
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009351static PyObject *
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009352os_sendfile_impl(PyObject *module, int out_fd, int in_fd, Py_off_t offset,
9353 Py_off_t sbytes, PyObject *headers, PyObject *trailers,
9354 int flags)
9355/*[clinic end generated code: output=81c4bcd143f5c82b input=b0d72579d4c69afa]*/
9356#elif defined(__FreeBSD__) || defined(__DragonFly__)
9357/*[clinic input]
9358os.sendfile
9359
9360 out_fd: int
9361 in_fd: int
9362 offset: Py_off_t
9363 count: Py_ssize_t
9364 headers: object(c_default="NULL") = ()
9365 trailers: object(c_default="NULL") = ()
9366 flags: int = 0
9367
9368Copy count bytes from file descriptor in_fd to file descriptor out_fd.
9369[clinic start generated code]*/
9370
9371static PyObject *
9372os_sendfile_impl(PyObject *module, int out_fd, int in_fd, Py_off_t offset,
9373 Py_ssize_t count, PyObject *headers, PyObject *trailers,
9374 int flags)
9375/*[clinic end generated code: output=329ea009bdd55afc input=338adb8ff84ae8cd]*/
9376#else
9377/*[clinic input]
9378os.sendfile
9379
9380 out_fd: int
9381 in_fd: int
9382 offset as offobj: object
9383 count: Py_ssize_t
9384
9385Copy count bytes from file descriptor in_fd to file descriptor out_fd.
9386[clinic start generated code]*/
9387
9388static PyObject *
9389os_sendfile_impl(PyObject *module, int out_fd, int in_fd, PyObject *offobj,
9390 Py_ssize_t count)
9391/*[clinic end generated code: output=ae81216e40f167d8 input=76d64058c74477ba]*/
9392#endif
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009393{
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009394 Py_ssize_t ret;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009395 int async_err = 0;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009396
9397#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
9398#ifndef __APPLE__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009399 off_t sbytes;
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009400#endif
9401 Py_buffer *hbuf, *tbuf;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009402 struct sf_hdtr sf;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009403
Victor Stinner6ce0dbf2013-07-07 16:32:36 +02009404 sf.headers = NULL;
9405 sf.trailers = NULL;
9406
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009407 if (headers != NULL) {
9408 if (!PySequence_Check(headers)) {
9409 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009410 "sendfile() headers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009411 return NULL;
9412 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009413 Py_ssize_t i = PySequence_Size(headers);
9414 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009415 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009416 if (i > INT_MAX) {
9417 PyErr_SetString(PyExc_OverflowError,
9418 "sendfile() header is too large");
9419 return NULL;
9420 }
9421 if (i > 0) {
9422 sf.hdr_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009423 if (iov_setup(&(sf.headers), &hbuf,
9424 headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009425 return NULL;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009426#ifdef __APPLE__
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009427 for (i = 0; i < sf.hdr_cnt; i++) {
9428 Py_ssize_t blen = sf.headers[i].iov_len;
9429# define OFF_T_MAX 0x7fffffffffffffff
9430 if (sbytes >= OFF_T_MAX - blen) {
9431 PyErr_SetString(PyExc_OverflowError,
9432 "sendfile() header is too large");
9433 return NULL;
9434 }
9435 sbytes += blen;
9436 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009437#endif
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009438 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009439 }
9440 }
9441 if (trailers != NULL) {
9442 if (!PySequence_Check(trailers)) {
9443 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009444 "sendfile() trailers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009445 return NULL;
9446 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009447 Py_ssize_t i = PySequence_Size(trailers);
9448 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009449 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009450 if (i > INT_MAX) {
9451 PyErr_SetString(PyExc_OverflowError,
9452 "sendfile() trailer is too large");
9453 return NULL;
9454 }
9455 if (i > 0) {
9456 sf.trl_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009457 if (iov_setup(&(sf.trailers), &tbuf,
9458 trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009459 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009460 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009461 }
9462 }
9463
Steve Dower8fc89802015-04-12 00:26:27 -04009464 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009465 do {
9466 Py_BEGIN_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009467#ifdef __APPLE__
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009468 ret = sendfile(in_fd, out_fd, offset, &sbytes, &sf, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009469#else
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009470 ret = sendfile(in_fd, out_fd, offset, count, &sf, &sbytes, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009471#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009472 Py_END_ALLOW_THREADS
9473 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04009474 _Py_END_SUPPRESS_IPH
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009475
9476 if (sf.headers != NULL)
9477 iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
9478 if (sf.trailers != NULL)
9479 iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
9480
9481 if (ret < 0) {
9482 if ((errno == EAGAIN) || (errno == EBUSY)) {
9483 if (sbytes != 0) {
9484 // some data has been sent
9485 goto done;
9486 }
9487 else {
9488 // no data has been sent; upper application is supposed
9489 // to retry on EAGAIN or EBUSY
9490 return posix_error();
9491 }
9492 }
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009493 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009494 }
9495 goto done;
9496
9497done:
9498 #if !defined(HAVE_LARGEFILE_SUPPORT)
9499 return Py_BuildValue("l", sbytes);
9500 #else
9501 return Py_BuildValue("L", sbytes);
9502 #endif
9503
9504#else
Benjamin Peterson840ef8f2016-09-07 14:45:10 -07009505#ifdef __linux__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009506 if (offobj == Py_None) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009507 do {
9508 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009509 ret = sendfile(out_fd, in_fd, NULL, count);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009510 Py_END_ALLOW_THREADS
9511 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009512 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009513 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodola'ff1a7352011-04-19 09:47:16 +02009514 return Py_BuildValue("n", ret);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009515 }
9516#endif
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009517 off_t offset;
Larry Hastings2f936352014-08-05 14:04:04 +10009518 if (!Py_off_t_converter(offobj, &offset))
Antoine Pitroudcc20b82011-02-26 13:38:35 +00009519 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009520
Jakub Kulík8c0be6f2020-09-05 21:10:01 +02009521#if defined(__sun) && defined(__SVR4)
9522 // On Solaris, sendfile raises EINVAL rather than returning 0
9523 // when the offset is equal or bigger than the in_fd size.
9524 int res;
9525 struct stat st;
9526
9527 do {
9528 Py_BEGIN_ALLOW_THREADS
9529 res = fstat(in_fd, &st);
9530 Py_END_ALLOW_THREADS
9531 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9532 if (ret < 0)
9533 return (!async_err) ? posix_error() : NULL;
9534
9535 if (offset >= st.st_size) {
9536 return Py_BuildValue("i", 0);
9537 }
9538#endif
9539
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009540 do {
9541 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009542 ret = sendfile(out_fd, in_fd, &offset, count);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009543 Py_END_ALLOW_THREADS
9544 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009545 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009546 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009547 return Py_BuildValue("n", ret);
9548#endif
9549}
Larry Hastings2f936352014-08-05 14:04:04 +10009550#endif /* HAVE_SENDFILE */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009551
Larry Hastings2f936352014-08-05 14:04:04 +10009552
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009553#if defined(__APPLE__)
9554/*[clinic input]
9555os._fcopyfile
9556
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009557 in_fd: int
9558 out_fd: int
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009559 flags: int
9560 /
9561
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009562Efficiently copy content or metadata of 2 regular file descriptors (macOS).
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009563[clinic start generated code]*/
9564
9565static PyObject *
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009566os__fcopyfile_impl(PyObject *module, int in_fd, int out_fd, int flags)
9567/*[clinic end generated code: output=c9d1a35a992e401b input=1e34638a86948795]*/
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009568{
9569 int ret;
9570
9571 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009572 ret = fcopyfile(in_fd, out_fd, NULL, flags);
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009573 Py_END_ALLOW_THREADS
9574 if (ret < 0)
9575 return posix_error();
9576 Py_RETURN_NONE;
9577}
9578#endif
9579
9580
Larry Hastings2f936352014-08-05 14:04:04 +10009581/*[clinic input]
9582os.fstat
9583
9584 fd : int
9585
9586Perform a stat system call on the given file descriptor.
9587
9588Like stat(), but for an open file descriptor.
9589Equivalent to os.stat(fd).
9590[clinic start generated code]*/
9591
Larry Hastings2f936352014-08-05 14:04:04 +10009592static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009593os_fstat_impl(PyObject *module, int fd)
9594/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009595{
Victor Stinner8c62be82010-05-06 00:08:46 +00009596 STRUCT_STAT st;
9597 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009598 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009599
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009600 do {
9601 Py_BEGIN_ALLOW_THREADS
9602 res = FSTAT(fd, &st);
9603 Py_END_ALLOW_THREADS
9604 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner8c62be82010-05-06 00:08:46 +00009605 if (res != 0) {
Martin v. Löwis14694662006-02-03 12:54:16 +00009606#ifdef MS_WINDOWS
Victor Stinnerb024e842012-10-31 22:24:06 +01009607 return PyErr_SetFromWindowsErr(0);
Martin v. Löwis14694662006-02-03 12:54:16 +00009608#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009609 return (!async_err) ? posix_error() : NULL;
Martin v. Löwis14694662006-02-03 12:54:16 +00009610#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00009611 }
Tim Peters5aa91602002-01-30 05:46:57 +00009612
Victor Stinner1c2fa782020-05-10 11:05:29 +02009613 return _pystat_fromstructstat(module, &st);
Guido van Rossum687dd131993-05-17 08:34:16 +00009614}
9615
Larry Hastings2f936352014-08-05 14:04:04 +10009616
9617/*[clinic input]
9618os.isatty -> bool
9619 fd: int
9620 /
9621
9622Return True if the fd is connected to a terminal.
9623
9624Return True if the file descriptor is an open file descriptor
9625connected to the slave end of a terminal.
9626[clinic start generated code]*/
9627
Larry Hastings2f936352014-08-05 14:04:04 +10009628static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009629os_isatty_impl(PyObject *module, int fd)
9630/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009631{
Steve Dower8fc89802015-04-12 00:26:27 -04009632 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -04009633 _Py_BEGIN_SUPPRESS_IPH
9634 return_value = isatty(fd);
9635 _Py_END_SUPPRESS_IPH
9636 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +10009637}
9638
9639
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009640#ifdef HAVE_PIPE
Larry Hastings2f936352014-08-05 14:04:04 +10009641/*[clinic input]
9642os.pipe
9643
9644Create a pipe.
9645
9646Returns a tuple of two file descriptors:
9647 (read_fd, write_fd)
9648[clinic start generated code]*/
9649
Larry Hastings2f936352014-08-05 14:04:04 +10009650static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009651os_pipe_impl(PyObject *module)
9652/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00009653{
Victor Stinner8c62be82010-05-06 00:08:46 +00009654 int fds[2];
Victor Stinnerdaf45552013-08-28 00:53:59 +02009655#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00009656 HANDLE read, write;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009657 SECURITY_ATTRIBUTES attr;
Victor Stinner8c62be82010-05-06 00:08:46 +00009658 BOOL ok;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009659#else
9660 int res;
9661#endif
9662
9663#ifdef MS_WINDOWS
9664 attr.nLength = sizeof(attr);
9665 attr.lpSecurityDescriptor = NULL;
9666 attr.bInheritHandle = FALSE;
9667
9668 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08009669 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009670 ok = CreatePipe(&read, &write, &attr, 0);
9671 if (ok) {
Benjamin Petersonca470632016-09-06 13:47:26 -07009672 fds[0] = _open_osfhandle((intptr_t)read, _O_RDONLY);
9673 fds[1] = _open_osfhandle((intptr_t)write, _O_WRONLY);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009674 if (fds[0] == -1 || fds[1] == -1) {
9675 CloseHandle(read);
9676 CloseHandle(write);
9677 ok = 0;
9678 }
9679 }
Steve Dowerc3630612016-11-19 18:41:16 -08009680 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009681 Py_END_ALLOW_THREADS
9682
Victor Stinner8c62be82010-05-06 00:08:46 +00009683 if (!ok)
Victor Stinnerb024e842012-10-31 22:24:06 +01009684 return PyErr_SetFromWindowsErr(0);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009685#else
9686
9687#ifdef HAVE_PIPE2
9688 Py_BEGIN_ALLOW_THREADS
9689 res = pipe2(fds, O_CLOEXEC);
9690 Py_END_ALLOW_THREADS
9691
9692 if (res != 0 && errno == ENOSYS)
9693 {
9694#endif
9695 Py_BEGIN_ALLOW_THREADS
9696 res = pipe(fds);
9697 Py_END_ALLOW_THREADS
9698
9699 if (res == 0) {
9700 if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
9701 close(fds[0]);
9702 close(fds[1]);
9703 return NULL;
9704 }
9705 if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
9706 close(fds[0]);
9707 close(fds[1]);
9708 return NULL;
9709 }
9710 }
9711#ifdef HAVE_PIPE2
9712 }
9713#endif
9714
9715 if (res != 0)
9716 return PyErr_SetFromErrno(PyExc_OSError);
9717#endif /* !MS_WINDOWS */
9718 return Py_BuildValue("(ii)", fds[0], fds[1]);
Guido van Rossum687dd131993-05-17 08:34:16 +00009719}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009720#endif /* HAVE_PIPE */
9721
Larry Hastings2f936352014-08-05 14:04:04 +10009722
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009723#ifdef HAVE_PIPE2
Larry Hastings2f936352014-08-05 14:04:04 +10009724/*[clinic input]
9725os.pipe2
9726
9727 flags: int
9728 /
9729
9730Create a pipe with flags set atomically.
9731
9732Returns a tuple of two file descriptors:
9733 (read_fd, write_fd)
9734
9735flags can be constructed by ORing together one or more of these values:
9736O_NONBLOCK, O_CLOEXEC.
9737[clinic start generated code]*/
9738
Larry Hastings2f936352014-08-05 14:04:04 +10009739static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009740os_pipe2_impl(PyObject *module, int flags)
9741/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009742{
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009743 int fds[2];
9744 int res;
9745
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009746 res = pipe2(fds, flags);
9747 if (res != 0)
9748 return posix_error();
9749 return Py_BuildValue("(ii)", fds[0], fds[1]);
9750}
9751#endif /* HAVE_PIPE2 */
9752
Larry Hastings2f936352014-08-05 14:04:04 +10009753
Ross Lagerwall7807c352011-03-17 20:20:30 +02009754#ifdef HAVE_WRITEV
Larry Hastings2f936352014-08-05 14:04:04 +10009755/*[clinic input]
9756os.writev -> Py_ssize_t
9757 fd: int
9758 buffers: object
9759 /
9760
9761Iterate over buffers, and write the contents of each to a file descriptor.
9762
9763Returns the total number of bytes written.
9764buffers must be a sequence of bytes-like objects.
9765[clinic start generated code]*/
9766
Larry Hastings2f936352014-08-05 14:04:04 +10009767static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009768os_writev_impl(PyObject *module, int fd, PyObject *buffers)
9769/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009770{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009771 Py_ssize_t cnt;
Larry Hastings2f936352014-08-05 14:04:04 +10009772 Py_ssize_t result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009773 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009774 struct iovec *iov;
9775 Py_buffer *buf;
Larry Hastings2f936352014-08-05 14:04:04 +10009776
9777 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009778 PyErr_SetString(PyExc_TypeError,
9779 "writev() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009780 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009781 }
Larry Hastings2f936352014-08-05 14:04:04 +10009782 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009783 if (cnt < 0)
9784 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009785
Larry Hastings2f936352014-08-05 14:04:04 +10009786 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9787 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009788 }
9789
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009790 do {
9791 Py_BEGIN_ALLOW_THREADS
9792 result = writev(fd, iov, cnt);
9793 Py_END_ALLOW_THREADS
9794 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009795
9796 iov_cleanup(iov, buf, cnt);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009797 if (result < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009798 posix_error();
Victor Stinner57ddf782014-01-08 15:21:28 +01009799
Georg Brandl306336b2012-06-24 12:55:33 +02009800 return result;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009801}
Larry Hastings2f936352014-08-05 14:04:04 +10009802#endif /* HAVE_WRITEV */
9803
9804
9805#ifdef HAVE_PWRITE
9806/*[clinic input]
9807os.pwrite -> Py_ssize_t
9808
9809 fd: int
9810 buffer: Py_buffer
9811 offset: Py_off_t
9812 /
9813
9814Write bytes to a file descriptor starting at a particular offset.
9815
9816Write buffer to fd, starting at offset bytes from the beginning of
9817the file. Returns the number of bytes writte. Does not change the
9818current file offset.
9819[clinic start generated code]*/
9820
Larry Hastings2f936352014-08-05 14:04:04 +10009821static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009822os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
9823/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009824{
9825 Py_ssize_t size;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009826 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009827
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009828 do {
9829 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009830 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009831 size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009832 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009833 Py_END_ALLOW_THREADS
9834 } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +10009835
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009836 if (size < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009837 posix_error();
9838 return size;
9839}
9840#endif /* HAVE_PWRITE */
9841
Pablo Galindo4defba32018-01-27 16:16:37 +00009842#if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
9843/*[clinic input]
9844os.pwritev -> Py_ssize_t
9845
9846 fd: int
9847 buffers: object
9848 offset: Py_off_t
9849 flags: int = 0
9850 /
9851
9852Writes the contents of bytes-like objects to a file descriptor at a given offset.
9853
9854Combines the functionality of writev() and pwrite(). All buffers must be a sequence
9855of bytes-like objects. Buffers are processed in array order. Entire contents of first
9856buffer is written before proceeding to second, and so on. The operating system may
9857set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
9858This function writes the contents of each object to the file descriptor and returns
9859the total number of bytes written.
9860
9861The flags argument contains a bitwise OR of zero or more of the following flags:
9862
9863- RWF_DSYNC
9864- RWF_SYNC
YoSTEALTH76ef2552020-05-27 15:32:22 -06009865- RWF_APPEND
Pablo Galindo4defba32018-01-27 16:16:37 +00009866
9867Using non-zero flags requires Linux 4.7 or newer.
9868[clinic start generated code]*/
9869
9870static Py_ssize_t
9871os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9872 int flags)
YoSTEALTH76ef2552020-05-27 15:32:22 -06009873/*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=35358c327e1a2a8e]*/
Pablo Galindo4defba32018-01-27 16:16:37 +00009874{
9875 Py_ssize_t cnt;
9876 Py_ssize_t result;
9877 int async_err = 0;
9878 struct iovec *iov;
9879 Py_buffer *buf;
9880
9881 if (!PySequence_Check(buffers)) {
9882 PyErr_SetString(PyExc_TypeError,
9883 "pwritev() arg 2 must be a sequence");
9884 return -1;
9885 }
9886
9887 cnt = PySequence_Size(buffers);
9888 if (cnt < 0) {
9889 return -1;
9890 }
9891
9892#ifndef HAVE_PWRITEV2
9893 if(flags != 0) {
9894 argument_unavailable_error("pwritev2", "flags");
9895 return -1;
9896 }
9897#endif
9898
9899 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9900 return -1;
9901 }
9902#ifdef HAVE_PWRITEV2
9903 do {
9904 Py_BEGIN_ALLOW_THREADS
9905 _Py_BEGIN_SUPPRESS_IPH
9906 result = pwritev2(fd, iov, cnt, offset, flags);
9907 _Py_END_SUPPRESS_IPH
9908 Py_END_ALLOW_THREADS
9909 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9910#else
9911 do {
9912 Py_BEGIN_ALLOW_THREADS
9913 _Py_BEGIN_SUPPRESS_IPH
9914 result = pwritev(fd, iov, cnt, offset);
9915 _Py_END_SUPPRESS_IPH
9916 Py_END_ALLOW_THREADS
9917 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9918#endif
9919
9920 iov_cleanup(iov, buf, cnt);
9921 if (result < 0) {
9922 if (!async_err) {
9923 posix_error();
9924 }
9925 return -1;
9926 }
9927
9928 return result;
9929}
9930#endif /* HAVE_PWRITEV */
9931
Pablo Galindoaac4d032019-05-31 19:39:47 +01009932#ifdef HAVE_COPY_FILE_RANGE
9933/*[clinic input]
9934
9935os.copy_file_range
9936 src: int
9937 Source file descriptor.
9938 dst: int
9939 Destination file descriptor.
9940 count: Py_ssize_t
9941 Number of bytes to copy.
9942 offset_src: object = None
9943 Starting offset in src.
9944 offset_dst: object = None
9945 Starting offset in dst.
9946
9947Copy count bytes from one file descriptor to another.
9948
9949If offset_src is None, then src is read from the current position;
9950respectively for offset_dst.
9951[clinic start generated code]*/
9952
9953static PyObject *
9954os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
9955 PyObject *offset_src, PyObject *offset_dst)
9956/*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
9957{
9958 off_t offset_src_val, offset_dst_val;
9959 off_t *p_offset_src = NULL;
9960 off_t *p_offset_dst = NULL;
9961 Py_ssize_t ret;
9962 int async_err = 0;
9963 /* The flags argument is provided to allow
9964 * for future extensions and currently must be to 0. */
9965 int flags = 0;
Pablo Galindo4defba32018-01-27 16:16:37 +00009966
9967
Pablo Galindoaac4d032019-05-31 19:39:47 +01009968 if (count < 0) {
9969 PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
9970 return NULL;
9971 }
9972
9973 if (offset_src != Py_None) {
9974 if (!Py_off_t_converter(offset_src, &offset_src_val)) {
9975 return NULL;
9976 }
9977 p_offset_src = &offset_src_val;
9978 }
9979
9980 if (offset_dst != Py_None) {
9981 if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
9982 return NULL;
9983 }
9984 p_offset_dst = &offset_dst_val;
9985 }
9986
9987 do {
9988 Py_BEGIN_ALLOW_THREADS
9989 ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
9990 Py_END_ALLOW_THREADS
9991 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9992
9993 if (ret < 0) {
9994 return (!async_err) ? posix_error() : NULL;
9995 }
9996
9997 return PyLong_FromSsize_t(ret);
9998}
9999#endif /* HAVE_COPY_FILE_RANGE*/
Larry Hastings2f936352014-08-05 14:04:04 +100010000
10001#ifdef HAVE_MKFIFO
10002/*[clinic input]
10003os.mkfifo
10004
10005 path: path_t
10006 mode: int=0o666
10007 *
10008 dir_fd: dir_fd(requires='mkfifoat')=None
10009
10010Create a "fifo" (a POSIX named pipe).
10011
10012If dir_fd is not None, it should be a file descriptor open to a directory,
10013 and path should be relative; path will then be relative to that directory.
10014dir_fd may not be implemented on your platform.
10015 If it is unavailable, using it will raise a NotImplementedError.
10016[clinic start generated code]*/
10017
Larry Hastings2f936352014-08-05 14:04:04 +100010018static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010019os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
10020/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010021{
10022 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010023 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +100010024
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010025 do {
10026 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +100010027#ifdef HAVE_MKFIFOAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010028 if (dir_fd != DEFAULT_DIR_FD)
10029 result = mkfifoat(dir_fd, path->narrow, mode);
10030 else
Ross Lagerwall7807c352011-03-17 20:20:30 +020010031#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010032 result = mkfifo(path->narrow, mode);
10033 Py_END_ALLOW_THREADS
10034 } while (result != 0 && errno == EINTR &&
10035 !(async_err = PyErr_CheckSignals()));
10036 if (result != 0)
10037 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100010038
10039 Py_RETURN_NONE;
10040}
10041#endif /* HAVE_MKFIFO */
10042
10043
10044#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
10045/*[clinic input]
10046os.mknod
10047
10048 path: path_t
10049 mode: int=0o600
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +020010050 device: dev_t=0
Larry Hastings2f936352014-08-05 14:04:04 +100010051 *
10052 dir_fd: dir_fd(requires='mknodat')=None
10053
10054Create a node in the file system.
10055
10056Create a node in the file system (file, device special file or named pipe)
10057at path. mode specifies both the permissions to use and the
10058type of node to be created, being combined (bitwise OR) with one of
10059S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
10060device defines the newly created device special file (probably using
10061os.makedev()). Otherwise device is ignored.
10062
10063If dir_fd is not None, it should be a file descriptor open to a directory,
10064 and path should be relative; path will then be relative to that directory.
10065dir_fd may not be implemented on your platform.
10066 If it is unavailable, using it will raise a NotImplementedError.
10067[clinic start generated code]*/
10068
Larry Hastings2f936352014-08-05 14:04:04 +100010069static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010070os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
Larry Hastings89964c42015-04-14 18:07:59 -040010071 int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010072/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010073{
10074 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010075 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +100010076
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010077 do {
10078 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +100010079#ifdef HAVE_MKNODAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010080 if (dir_fd != DEFAULT_DIR_FD)
10081 result = mknodat(dir_fd, path->narrow, mode, device);
10082 else
Larry Hastings2f936352014-08-05 14:04:04 +100010083#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010084 result = mknod(path->narrow, mode, device);
10085 Py_END_ALLOW_THREADS
10086 } while (result != 0 && errno == EINTR &&
10087 !(async_err = PyErr_CheckSignals()));
10088 if (result != 0)
10089 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100010090
10091 Py_RETURN_NONE;
10092}
10093#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
10094
10095
10096#ifdef HAVE_DEVICE_MACROS
10097/*[clinic input]
10098os.major -> unsigned_int
10099
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +020010100 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +100010101 /
10102
10103Extracts a device major number from a raw device number.
10104[clinic start generated code]*/
10105
Larry Hastings2f936352014-08-05 14:04:04 +100010106static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010107os_major_impl(PyObject *module, dev_t device)
10108/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010109{
10110 return major(device);
10111}
10112
10113
10114/*[clinic input]
10115os.minor -> unsigned_int
10116
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +020010117 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +100010118 /
10119
10120Extracts a device minor number from a raw device number.
10121[clinic start generated code]*/
10122
Larry Hastings2f936352014-08-05 14:04:04 +100010123static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010124os_minor_impl(PyObject *module, dev_t device)
10125/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010126{
10127 return minor(device);
10128}
10129
10130
10131/*[clinic input]
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +020010132os.makedev -> dev_t
Larry Hastings2f936352014-08-05 14:04:04 +100010133
10134 major: int
10135 minor: int
10136 /
10137
10138Composes a raw device number from the major and minor device numbers.
10139[clinic start generated code]*/
10140
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +020010141static dev_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010142os_makedev_impl(PyObject *module, int major, int minor)
10143/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010144{
10145 return makedev(major, minor);
10146}
10147#endif /* HAVE_DEVICE_MACROS */
10148
10149
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010150#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010151/*[clinic input]
10152os.ftruncate
10153
10154 fd: int
10155 length: Py_off_t
10156 /
10157
10158Truncate a file, specified by file descriptor, to a specific length.
10159[clinic start generated code]*/
10160
Larry Hastings2f936352014-08-05 14:04:04 +100010161static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010162os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
10163/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010164{
10165 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010166 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +100010167
Steve Dowerb82e17e2019-05-23 08:45:22 -070010168 if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
10169 return NULL;
10170 }
10171
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010172 do {
10173 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -040010174 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010175#ifdef MS_WINDOWS
10176 result = _chsize_s(fd, length);
10177#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010178 result = ftruncate(fd, length);
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010179#endif
Steve Dowera1c7e722015-04-12 00:26:43 -040010180 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010181 Py_END_ALLOW_THREADS
10182 } while (result != 0 && errno == EINTR &&
10183 !(async_err = PyErr_CheckSignals()));
10184 if (result != 0)
10185 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100010186 Py_RETURN_NONE;
10187}
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010188#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +100010189
10190
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010191#if defined HAVE_TRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010192/*[clinic input]
10193os.truncate
10194 path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
10195 length: Py_off_t
10196
10197Truncate a file, specified by path, to a specific length.
10198
10199On some platforms, path may also be specified as an open file descriptor.
10200 If this functionality is unavailable, using it raises an exception.
10201[clinic start generated code]*/
10202
Larry Hastings2f936352014-08-05 14:04:04 +100010203static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010204os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
10205/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010206{
10207 int result;
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010208#ifdef MS_WINDOWS
10209 int fd;
10210#endif
10211
10212 if (path->fd != -1)
10213 return os_ftruncate_impl(module, path->fd, length);
Larry Hastings2f936352014-08-05 14:04:04 +100010214
Steve Dowerb82e17e2019-05-23 08:45:22 -070010215 if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
10216 return NULL;
10217 }
10218
Larry Hastings2f936352014-08-05 14:04:04 +100010219 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -040010220 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010221#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -070010222 fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
Victor Stinnercc0bbbc2015-04-25 00:21:52 +020010223 if (fd < 0)
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010224 result = -1;
10225 else {
10226 result = _chsize_s(fd, length);
10227 close(fd);
10228 if (result < 0)
10229 errno = result;
10230 }
10231#else
10232 result = truncate(path->narrow, length);
Larry Hastings2f936352014-08-05 14:04:04 +100010233#endif
Steve Dowera1c7e722015-04-12 00:26:43 -040010234 _Py_END_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +100010235 Py_END_ALLOW_THREADS
10236 if (result < 0)
Alexey Izbyshev83460312018-10-20 03:28:22 +030010237 return posix_path_error(path);
Larry Hastings2f936352014-08-05 14:04:04 +100010238
10239 Py_RETURN_NONE;
10240}
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010241#endif /* HAVE_TRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +100010242
Ross Lagerwall7807c352011-03-17 20:20:30 +020010243
Victor Stinnerd6b17692014-09-30 12:20:05 +020010244/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
10245 and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
10246 defined, which is the case in Python on AIX. AIX bug report:
10247 http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
10248#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
10249# define POSIX_FADVISE_AIX_BUG
10250#endif
10251
Victor Stinnerec39e262014-09-30 12:35:58 +020010252
Victor Stinnerd6b17692014-09-30 12:20:05 +020010253#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +100010254/*[clinic input]
10255os.posix_fallocate
10256
10257 fd: int
10258 offset: Py_off_t
10259 length: Py_off_t
10260 /
10261
10262Ensure a file has allocated at least a particular number of bytes on disk.
10263
10264Ensure that the file specified by fd encompasses a range of bytes
10265starting at offset bytes from the beginning and continuing for length bytes.
10266[clinic start generated code]*/
10267
Larry Hastings2f936352014-08-05 14:04:04 +100010268static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010269os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -040010270 Py_off_t length)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010271/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010272{
10273 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010274 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010275
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010276 do {
10277 Py_BEGIN_ALLOW_THREADS
10278 result = posix_fallocate(fd, offset, length);
10279 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010280 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10281
10282 if (result == 0)
10283 Py_RETURN_NONE;
10284
10285 if (async_err)
10286 return NULL;
10287
10288 errno = result;
10289 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010290}
Victor Stinnerec39e262014-09-30 12:35:58 +020010291#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
Larry Hastings2f936352014-08-05 14:04:04 +100010292
Ross Lagerwall7807c352011-03-17 20:20:30 +020010293
Victor Stinnerd6b17692014-09-30 12:20:05 +020010294#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +100010295/*[clinic input]
10296os.posix_fadvise
10297
10298 fd: int
10299 offset: Py_off_t
10300 length: Py_off_t
10301 advice: int
10302 /
10303
10304Announce an intention to access data in a specific pattern.
10305
10306Announce an intention to access data in a specific pattern, thus allowing
10307the kernel to make optimizations.
10308The advice applies to the region of the file specified by fd starting at
10309offset and continuing for length bytes.
10310advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
10311POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
10312POSIX_FADV_DONTNEED.
10313[clinic start generated code]*/
10314
Larry Hastings2f936352014-08-05 14:04:04 +100010315static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010316os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -040010317 Py_off_t length, int advice)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010318/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010319{
10320 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010321 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010322
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010323 do {
10324 Py_BEGIN_ALLOW_THREADS
10325 result = posix_fadvise(fd, offset, length, advice);
10326 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010327 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10328
10329 if (result == 0)
10330 Py_RETURN_NONE;
10331
10332 if (async_err)
10333 return NULL;
10334
10335 errno = result;
10336 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010337}
Victor Stinnerec39e262014-09-30 12:35:58 +020010338#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
Ross Lagerwall7807c352011-03-17 20:20:30 +020010339
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000010340
Thomas Hellerf78f12a2007-11-08 19:33:05 +000010341#ifdef MS_WINDOWS
Victor Stinner161e7b32020-01-24 11:53:44 +010010342static PyObject*
10343win32_putenv(PyObject *name, PyObject *value)
10344{
10345 /* Search from index 1 because on Windows starting '=' is allowed for
10346 defining hidden environment variables. */
10347 if (PyUnicode_GET_LENGTH(name) == 0 ||
10348 PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
10349 {
10350 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10351 return NULL;
10352 }
10353 PyObject *unicode;
10354 if (value != NULL) {
10355 unicode = PyUnicode_FromFormat("%U=%U", name, value);
10356 }
10357 else {
10358 unicode = PyUnicode_FromFormat("%U=", name);
10359 }
10360 if (unicode == NULL) {
10361 return NULL;
10362 }
10363
10364 Py_ssize_t size;
10365 /* PyUnicode_AsWideCharString() rejects embedded null characters */
10366 wchar_t *env = PyUnicode_AsWideCharString(unicode, &size);
10367 Py_DECREF(unicode);
10368
10369 if (env == NULL) {
10370 return NULL;
10371 }
10372 if (size > _MAX_ENV) {
10373 PyErr_Format(PyExc_ValueError,
10374 "the environment variable is longer than %u characters",
10375 _MAX_ENV);
10376 PyMem_Free(env);
10377 return NULL;
10378 }
10379
10380 /* _wputenv() and SetEnvironmentVariableW() update the environment in the
10381 Process Environment Block (PEB). _wputenv() also updates CRT 'environ'
10382 and '_wenviron' variables, whereas SetEnvironmentVariableW() does not.
10383
10384 Prefer _wputenv() to be compatible with C libraries using CRT
10385 variables and CRT functions using these variables (ex: getenv()). */
10386 int err = _wputenv(env);
10387 PyMem_Free(env);
10388
10389 if (err) {
10390 posix_error();
10391 return NULL;
10392 }
10393
10394 Py_RETURN_NONE;
10395}
10396#endif
10397
10398
10399#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010400/*[clinic input]
10401os.putenv
10402
10403 name: unicode
10404 value: unicode
10405 /
10406
10407Change or add an environment variable.
10408[clinic start generated code]*/
10409
Larry Hastings2f936352014-08-05 14:04:04 +100010410static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010411os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10412/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010413{
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010414 if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
10415 return NULL;
10416 }
Victor Stinner161e7b32020-01-24 11:53:44 +010010417 return win32_putenv(name, value);
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010418}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010419#else
Larry Hastings2f936352014-08-05 14:04:04 +100010420/*[clinic input]
10421os.putenv
Guido van Rossumb6a47161997-09-15 22:54:34 +000010422
Larry Hastings2f936352014-08-05 14:04:04 +100010423 name: FSConverter
10424 value: FSConverter
10425 /
10426
10427Change or add an environment variable.
10428[clinic start generated code]*/
10429
Larry Hastings2f936352014-08-05 14:04:04 +100010430static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010431os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10432/*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010433{
Serhiy Storchaka77703942017-06-25 07:33:01 +030010434 const char *name_string = PyBytes_AS_STRING(name);
10435 const char *value_string = PyBytes_AS_STRING(value);
Larry Hastings2f936352014-08-05 14:04:04 +100010436
Serhiy Storchaka77703942017-06-25 07:33:01 +030010437 if (strchr(name_string, '=') != NULL) {
10438 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10439 return NULL;
10440 }
Victor Stinnerb477d192020-01-22 22:48:16 +010010441
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010442 if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
10443 return NULL;
10444 }
10445
Victor Stinnerb477d192020-01-22 22:48:16 +010010446 if (setenv(name_string, value_string, 1)) {
10447 return posix_error();
10448 }
Larry Hastings2f936352014-08-05 14:04:04 +100010449 Py_RETURN_NONE;
10450}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010451#endif /* !defined(MS_WINDOWS) */
Larry Hastings2f936352014-08-05 14:04:04 +100010452
10453
Victor Stinner161e7b32020-01-24 11:53:44 +010010454#ifdef MS_WINDOWS
10455/*[clinic input]
10456os.unsetenv
10457 name: unicode
10458 /
10459
10460Delete an environment variable.
10461[clinic start generated code]*/
10462
10463static PyObject *
10464os_unsetenv_impl(PyObject *module, PyObject *name)
10465/*[clinic end generated code: output=54c4137ab1834f02 input=4d6a1747cc526d2f]*/
10466{
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010467 if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
10468 return NULL;
10469 }
Victor Stinner161e7b32020-01-24 11:53:44 +010010470 return win32_putenv(name, NULL);
10471}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010472#else
Larry Hastings2f936352014-08-05 14:04:04 +100010473/*[clinic input]
10474os.unsetenv
10475 name: FSConverter
10476 /
10477
10478Delete an environment variable.
10479[clinic start generated code]*/
10480
Larry Hastings2f936352014-08-05 14:04:04 +100010481static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010482os_unsetenv_impl(PyObject *module, PyObject *name)
10483/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010484{
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010485 if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
10486 return NULL;
10487 }
Victor Stinner984890f2011-11-24 13:53:38 +010010488#ifdef HAVE_BROKEN_UNSETENV
10489 unsetenv(PyBytes_AS_STRING(name));
10490#else
Victor Stinner161e7b32020-01-24 11:53:44 +010010491 int err = unsetenv(PyBytes_AS_STRING(name));
10492 if (err) {
Victor Stinner60b385e2011-11-22 22:01:28 +010010493 return posix_error();
Victor Stinner161e7b32020-01-24 11:53:44 +010010494 }
Victor Stinner984890f2011-11-24 13:53:38 +010010495#endif
Guido van Rossumc524d952001-10-19 01:31:59 +000010496
Victor Stinner84ae1182010-05-06 22:05:07 +000010497 Py_RETURN_NONE;
Guido van Rossumc524d952001-10-19 01:31:59 +000010498}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010499#endif /* !MS_WINDOWS */
Guido van Rossumc524d952001-10-19 01:31:59 +000010500
Larry Hastings2f936352014-08-05 14:04:04 +100010501
10502/*[clinic input]
10503os.strerror
10504
10505 code: int
10506 /
10507
10508Translate an error code to a message string.
10509[clinic start generated code]*/
10510
Larry Hastings2f936352014-08-05 14:04:04 +100010511static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010512os_strerror_impl(PyObject *module, int code)
10513/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010514{
10515 char *message = strerror(code);
Victor Stinner8c62be82010-05-06 00:08:46 +000010516 if (message == NULL) {
10517 PyErr_SetString(PyExc_ValueError,
10518 "strerror() argument out of range");
10519 return NULL;
10520 }
Victor Stinner1b579672011-12-17 05:47:23 +010010521 return PyUnicode_DecodeLocale(message, "surrogateescape");
Guido van Rossumb6a47161997-09-15 22:54:34 +000010522}
Guido van Rossumb6a47161997-09-15 22:54:34 +000010523
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010524
Guido van Rossumc9641791998-08-04 15:26:23 +000010525#ifdef HAVE_SYS_WAIT_H
Fred Drake106c1a02002-04-23 15:58:02 +000010526#ifdef WCOREDUMP
Larry Hastings2f936352014-08-05 14:04:04 +100010527/*[clinic input]
10528os.WCOREDUMP -> bool
10529
10530 status: int
10531 /
10532
10533Return True if the process returning status was dumped to a core file.
10534[clinic start generated code]*/
10535
Larry Hastings2f936352014-08-05 14:04:04 +100010536static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010537os_WCOREDUMP_impl(PyObject *module, int status)
10538/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010539{
10540 WAIT_TYPE wait_status;
10541 WAIT_STATUS_INT(wait_status) = status;
10542 return WCOREDUMP(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010543}
10544#endif /* WCOREDUMP */
10545
Larry Hastings2f936352014-08-05 14:04:04 +100010546
Fred Drake106c1a02002-04-23 15:58:02 +000010547#ifdef WIFCONTINUED
Larry Hastings2f936352014-08-05 14:04:04 +100010548/*[clinic input]
10549os.WIFCONTINUED -> bool
10550
10551 status: int
10552
10553Return True if a particular process was continued from a job control stop.
10554
10555Return True if the process returning status was continued from a
10556job control stop.
10557[clinic start generated code]*/
10558
Larry Hastings2f936352014-08-05 14:04:04 +100010559static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010560os_WIFCONTINUED_impl(PyObject *module, int status)
10561/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010562{
10563 WAIT_TYPE wait_status;
10564 WAIT_STATUS_INT(wait_status) = status;
10565 return WIFCONTINUED(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010566}
10567#endif /* WIFCONTINUED */
10568
Larry Hastings2f936352014-08-05 14:04:04 +100010569
Guido van Rossumc9641791998-08-04 15:26:23 +000010570#ifdef WIFSTOPPED
Larry Hastings2f936352014-08-05 14:04:04 +100010571/*[clinic input]
10572os.WIFSTOPPED -> bool
10573
10574 status: int
10575
10576Return True if the process returning status was stopped.
10577[clinic start generated code]*/
10578
Larry Hastings2f936352014-08-05 14:04:04 +100010579static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010580os_WIFSTOPPED_impl(PyObject *module, int status)
10581/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010582{
10583 WAIT_TYPE wait_status;
10584 WAIT_STATUS_INT(wait_status) = status;
10585 return WIFSTOPPED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010586}
10587#endif /* WIFSTOPPED */
10588
Larry Hastings2f936352014-08-05 14:04:04 +100010589
Guido van Rossumc9641791998-08-04 15:26:23 +000010590#ifdef WIFSIGNALED
Larry Hastings2f936352014-08-05 14:04:04 +100010591/*[clinic input]
10592os.WIFSIGNALED -> bool
10593
10594 status: int
10595
10596Return True if the process returning status was terminated by a signal.
10597[clinic start generated code]*/
10598
Larry Hastings2f936352014-08-05 14:04:04 +100010599static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010600os_WIFSIGNALED_impl(PyObject *module, int status)
10601/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010602{
10603 WAIT_TYPE wait_status;
10604 WAIT_STATUS_INT(wait_status) = status;
10605 return WIFSIGNALED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010606}
10607#endif /* WIFSIGNALED */
10608
Larry Hastings2f936352014-08-05 14:04:04 +100010609
Guido van Rossumc9641791998-08-04 15:26:23 +000010610#ifdef WIFEXITED
Larry Hastings2f936352014-08-05 14:04:04 +100010611/*[clinic input]
10612os.WIFEXITED -> bool
10613
10614 status: int
10615
10616Return True if the process returning status exited via the exit() system call.
10617[clinic start generated code]*/
10618
Larry Hastings2f936352014-08-05 14:04:04 +100010619static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010620os_WIFEXITED_impl(PyObject *module, int status)
10621/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010622{
10623 WAIT_TYPE wait_status;
10624 WAIT_STATUS_INT(wait_status) = status;
10625 return WIFEXITED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010626}
10627#endif /* WIFEXITED */
10628
Larry Hastings2f936352014-08-05 14:04:04 +100010629
Guido van Rossum54ecc3d1999-01-27 17:53:11 +000010630#ifdef WEXITSTATUS
Larry Hastings2f936352014-08-05 14:04:04 +100010631/*[clinic input]
10632os.WEXITSTATUS -> int
10633
10634 status: int
10635
10636Return the process return code from status.
10637[clinic start generated code]*/
10638
Larry Hastings2f936352014-08-05 14:04:04 +100010639static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010640os_WEXITSTATUS_impl(PyObject *module, int status)
10641/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010642{
10643 WAIT_TYPE wait_status;
10644 WAIT_STATUS_INT(wait_status) = status;
10645 return WEXITSTATUS(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010646}
10647#endif /* WEXITSTATUS */
10648
Larry Hastings2f936352014-08-05 14:04:04 +100010649
Guido van Rossumc9641791998-08-04 15:26:23 +000010650#ifdef WTERMSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010651/*[clinic input]
10652os.WTERMSIG -> int
10653
10654 status: int
10655
10656Return the signal that terminated the process that provided the status value.
10657[clinic start generated code]*/
10658
Larry Hastings2f936352014-08-05 14:04:04 +100010659static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010660os_WTERMSIG_impl(PyObject *module, int status)
10661/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010662{
10663 WAIT_TYPE wait_status;
10664 WAIT_STATUS_INT(wait_status) = status;
10665 return WTERMSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010666}
10667#endif /* WTERMSIG */
10668
Larry Hastings2f936352014-08-05 14:04:04 +100010669
Guido van Rossumc9641791998-08-04 15:26:23 +000010670#ifdef WSTOPSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010671/*[clinic input]
10672os.WSTOPSIG -> int
10673
10674 status: int
10675
10676Return the signal that stopped the process that provided the status value.
10677[clinic start generated code]*/
10678
Larry Hastings2f936352014-08-05 14:04:04 +100010679static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010680os_WSTOPSIG_impl(PyObject *module, int status)
10681/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010682{
10683 WAIT_TYPE wait_status;
10684 WAIT_STATUS_INT(wait_status) = status;
10685 return WSTOPSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010686}
10687#endif /* WSTOPSIG */
Guido van Rossumc9641791998-08-04 15:26:23 +000010688#endif /* HAVE_SYS_WAIT_H */
10689
10690
Thomas Wouters477c8d52006-05-27 19:21:47 +000010691#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossumd5753e11999-10-19 13:29:23 +000010692#ifdef _SCO_DS
10693/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
10694 needed definitions in sys/statvfs.h */
10695#define _SVID3
10696#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000010697#include <sys/statvfs.h>
10698
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010699static PyObject*
Victor Stinner1c2fa782020-05-10 11:05:29 +020010700_pystatvfs_fromstructstatvfs(PyObject *module, struct statvfs st) {
10701 PyObject *StatVFSResultType = get_posix_state(module)->StatVFSResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -080010702 PyObject *v = PyStructSequence_New((PyTypeObject *)StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000010703 if (v == NULL)
10704 return NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010705
10706#if !defined(HAVE_LARGEFILE_SUPPORT)
Victor Stinner8c62be82010-05-06 00:08:46 +000010707 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10708 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10709 PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
10710 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
10711 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
10712 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
10713 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
10714 PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
10715 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10716 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010717#else
Victor Stinner8c62be82010-05-06 00:08:46 +000010718 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10719 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10720 PyStructSequence_SET_ITEM(v, 2,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010721 PyLong_FromLongLong((long long) st.f_blocks));
Victor Stinner8c62be82010-05-06 00:08:46 +000010722 PyStructSequence_SET_ITEM(v, 3,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010723 PyLong_FromLongLong((long long) st.f_bfree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010724 PyStructSequence_SET_ITEM(v, 4,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010725 PyLong_FromLongLong((long long) st.f_bavail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010726 PyStructSequence_SET_ITEM(v, 5,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010727 PyLong_FromLongLong((long long) st.f_files));
Victor Stinner8c62be82010-05-06 00:08:46 +000010728 PyStructSequence_SET_ITEM(v, 6,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010729 PyLong_FromLongLong((long long) st.f_ffree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010730 PyStructSequence_SET_ITEM(v, 7,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010731 PyLong_FromLongLong((long long) st.f_favail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010732 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10733 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010734#endif
Michael Felt502d5512018-01-05 13:01:58 +010010735/* The _ALL_SOURCE feature test macro defines f_fsid as a structure
10736 * (issue #32390). */
10737#if defined(_AIX) && defined(_ALL_SOURCE)
10738 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
10739#else
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +010010740 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid));
Michael Felt502d5512018-01-05 13:01:58 +010010741#endif
Victor Stinnerf0a7bac2013-10-30 18:55:24 +010010742 if (PyErr_Occurred()) {
10743 Py_DECREF(v);
10744 return NULL;
10745 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010746
Victor Stinner8c62be82010-05-06 00:08:46 +000010747 return v;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010748}
10749
Larry Hastings2f936352014-08-05 14:04:04 +100010750
10751/*[clinic input]
10752os.fstatvfs
10753 fd: int
10754 /
10755
10756Perform an fstatvfs system call on the given fd.
10757
10758Equivalent to statvfs(fd).
10759[clinic start generated code]*/
10760
Larry Hastings2f936352014-08-05 14:04:04 +100010761static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010762os_fstatvfs_impl(PyObject *module, int fd)
10763/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010764{
10765 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010766 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010767 struct statvfs st;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010768
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010769 do {
10770 Py_BEGIN_ALLOW_THREADS
10771 result = fstatvfs(fd, &st);
10772 Py_END_ALLOW_THREADS
10773 } while (result != 0 && errno == EINTR &&
10774 !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +100010775 if (result != 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010776 return (!async_err) ? posix_error() : NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010777
Victor Stinner1c2fa782020-05-10 11:05:29 +020010778 return _pystatvfs_fromstructstatvfs(module, st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010779}
Larry Hastings2f936352014-08-05 14:04:04 +100010780#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
Guido van Rossum94f6f721999-01-06 18:42:14 +000010781
10782
Thomas Wouters477c8d52006-05-27 19:21:47 +000010783#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossum94f6f721999-01-06 18:42:14 +000010784#include <sys/statvfs.h>
Larry Hastings2f936352014-08-05 14:04:04 +100010785/*[clinic input]
10786os.statvfs
Guido van Rossum94f6f721999-01-06 18:42:14 +000010787
Larry Hastings2f936352014-08-05 14:04:04 +100010788 path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
10789
10790Perform a statvfs system call on the given path.
10791
10792path may always be specified as a string.
10793On some platforms, path may also be specified as an open file descriptor.
10794 If this functionality is unavailable, using it raises an exception.
10795[clinic start generated code]*/
10796
Larry Hastings2f936352014-08-05 14:04:04 +100010797static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010798os_statvfs_impl(PyObject *module, path_t *path)
10799/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010800{
10801 int result;
10802 struct statvfs st;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010803
10804 Py_BEGIN_ALLOW_THREADS
10805#ifdef HAVE_FSTATVFS
Larry Hastings2f936352014-08-05 14:04:04 +100010806 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -070010807#ifdef __APPLE__
10808 /* handle weak-linking on Mac OS X 10.3 */
10809 if (fstatvfs == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010810 fd_specified("statvfs", path->fd);
10811 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010812 }
10813#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010814 result = fstatvfs(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010815 }
10816 else
10817#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010818 result = statvfs(path->narrow, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010819 Py_END_ALLOW_THREADS
10820
10821 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100010822 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010823 }
10824
Victor Stinner1c2fa782020-05-10 11:05:29 +020010825 return _pystatvfs_fromstructstatvfs(module, st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010826}
Larry Hastings2f936352014-08-05 14:04:04 +100010827#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
10828
Guido van Rossum94f6f721999-01-06 18:42:14 +000010829
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010830#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010831/*[clinic input]
10832os._getdiskusage
10833
Steve Dower23ad6d02018-02-22 10:39:10 -080010834 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +100010835
10836Return disk usage statistics about the given path as a (total, free) tuple.
10837[clinic start generated code]*/
10838
Larry Hastings2f936352014-08-05 14:04:04 +100010839static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -080010840os__getdiskusage_impl(PyObject *module, path_t *path)
10841/*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010842{
10843 BOOL retval;
10844 ULARGE_INTEGER _, total, free;
Joe Pamerc8c02492018-09-25 10:57:36 -040010845 DWORD err = 0;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010846
10847 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -080010848 retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010849 Py_END_ALLOW_THREADS
Joe Pamerc8c02492018-09-25 10:57:36 -040010850 if (retval == 0) {
10851 if (GetLastError() == ERROR_DIRECTORY) {
10852 wchar_t *dir_path = NULL;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010853
Joe Pamerc8c02492018-09-25 10:57:36 -040010854 dir_path = PyMem_New(wchar_t, path->length + 1);
10855 if (dir_path == NULL) {
10856 return PyErr_NoMemory();
10857 }
10858
10859 wcscpy_s(dir_path, path->length + 1, path->wide);
10860
10861 if (_dirnameW(dir_path) != -1) {
10862 Py_BEGIN_ALLOW_THREADS
10863 retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
10864 Py_END_ALLOW_THREADS
10865 }
10866 /* Record the last error in case it's modified by PyMem_Free. */
10867 err = GetLastError();
10868 PyMem_Free(dir_path);
10869 if (retval) {
10870 goto success;
10871 }
10872 }
10873 return PyErr_SetFromWindowsErr(err);
10874 }
10875
10876success:
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010877 return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
10878}
Larry Hastings2f936352014-08-05 14:04:04 +100010879#endif /* MS_WINDOWS */
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010880
10881
Fred Drakec9680921999-12-13 16:37:25 +000010882/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
10883 * It maps strings representing configuration variable names to
10884 * integer values, allowing those functions to be called with the
Thomas Wouters7e474022000-07-16 12:04:32 +000010885 * magic names instead of polluting the module's namespace with tons of
Fred Drake12c6e2d1999-12-14 21:25:03 +000010886 * rarely-used constants. There are three separate tables that use
10887 * these definitions.
Fred Drakebec628d1999-12-15 18:31:10 +000010888 *
10889 * This code is always included, even if none of the interfaces that
10890 * need it are included. The #if hackery needed to avoid it would be
10891 * sufficiently pervasive that it's not worth the loss of readability.
Fred Drakec9680921999-12-13 16:37:25 +000010892 */
10893struct constdef {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020010894 const char *name;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010895 int value;
Fred Drakec9680921999-12-13 16:37:25 +000010896};
10897
Fred Drake12c6e2d1999-12-14 21:25:03 +000010898static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010899conv_confname(PyObject *arg, int *valuep, struct constdef *table,
Guido van Rossum7d5baac2007-08-27 23:24:46 +000010900 size_t tablesize)
Fred Drake12c6e2d1999-12-14 21:25:03 +000010901{
Christian Heimes217cfd12007-12-02 14:31:20 +000010902 if (PyLong_Check(arg)) {
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010903 int value = _PyLong_AsInt(arg);
10904 if (value == -1 && PyErr_Occurred())
10905 return 0;
10906 *valuep = value;
Stefan Krah0e803b32010-11-26 16:16:47 +000010907 return 1;
Fred Drake12c6e2d1999-12-14 21:25:03 +000010908 }
Guido van Rossumbce56a62007-05-10 18:04:33 +000010909 else {
Stefan Krah0e803b32010-11-26 16:16:47 +000010910 /* look up the value in the table using a binary search */
10911 size_t lo = 0;
10912 size_t mid;
10913 size_t hi = tablesize;
10914 int cmp;
10915 const char *confname;
10916 if (!PyUnicode_Check(arg)) {
10917 PyErr_SetString(PyExc_TypeError,
10918 "configuration names must be strings or integers");
10919 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010920 }
Serhiy Storchaka06515832016-11-20 09:13:07 +020010921 confname = PyUnicode_AsUTF8(arg);
Stefan Krah0e803b32010-11-26 16:16:47 +000010922 if (confname == NULL)
10923 return 0;
10924 while (lo < hi) {
10925 mid = (lo + hi) / 2;
10926 cmp = strcmp(confname, table[mid].name);
10927 if (cmp < 0)
10928 hi = mid;
10929 else if (cmp > 0)
10930 lo = mid + 1;
10931 else {
10932 *valuep = table[mid].value;
10933 return 1;
10934 }
10935 }
10936 PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
10937 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010938 }
Fred Drake12c6e2d1999-12-14 21:25:03 +000010939}
10940
10941
10942#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
10943static struct constdef posix_constants_pathconf[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010944#ifdef _PC_ABI_AIO_XFER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010945 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000010946#endif
10947#ifdef _PC_ABI_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010948 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010949#endif
Fred Drakec9680921999-12-13 16:37:25 +000010950#ifdef _PC_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010951 {"PC_ASYNC_IO", _PC_ASYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010952#endif
10953#ifdef _PC_CHOWN_RESTRICTED
Victor Stinner8c62be82010-05-06 00:08:46 +000010954 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
Fred Drakec9680921999-12-13 16:37:25 +000010955#endif
10956#ifdef _PC_FILESIZEBITS
Victor Stinner8c62be82010-05-06 00:08:46 +000010957 {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
Fred Drakec9680921999-12-13 16:37:25 +000010958#endif
10959#ifdef _PC_LAST
Victor Stinner8c62be82010-05-06 00:08:46 +000010960 {"PC_LAST", _PC_LAST},
Fred Drakec9680921999-12-13 16:37:25 +000010961#endif
10962#ifdef _PC_LINK_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010963 {"PC_LINK_MAX", _PC_LINK_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010964#endif
10965#ifdef _PC_MAX_CANON
Victor Stinner8c62be82010-05-06 00:08:46 +000010966 {"PC_MAX_CANON", _PC_MAX_CANON},
Fred Drakec9680921999-12-13 16:37:25 +000010967#endif
10968#ifdef _PC_MAX_INPUT
Victor Stinner8c62be82010-05-06 00:08:46 +000010969 {"PC_MAX_INPUT", _PC_MAX_INPUT},
Fred Drakec9680921999-12-13 16:37:25 +000010970#endif
10971#ifdef _PC_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010972 {"PC_NAME_MAX", _PC_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010973#endif
10974#ifdef _PC_NO_TRUNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010975 {"PC_NO_TRUNC", _PC_NO_TRUNC},
Fred Drakec9680921999-12-13 16:37:25 +000010976#endif
10977#ifdef _PC_PATH_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010978 {"PC_PATH_MAX", _PC_PATH_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010979#endif
10980#ifdef _PC_PIPE_BUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010981 {"PC_PIPE_BUF", _PC_PIPE_BUF},
Fred Drakec9680921999-12-13 16:37:25 +000010982#endif
10983#ifdef _PC_PRIO_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010984 {"PC_PRIO_IO", _PC_PRIO_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010985#endif
10986#ifdef _PC_SOCK_MAXBUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010987 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
Fred Drakec9680921999-12-13 16:37:25 +000010988#endif
10989#ifdef _PC_SYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010990 {"PC_SYNC_IO", _PC_SYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010991#endif
10992#ifdef _PC_VDISABLE
Victor Stinner8c62be82010-05-06 00:08:46 +000010993 {"PC_VDISABLE", _PC_VDISABLE},
Fred Drakec9680921999-12-13 16:37:25 +000010994#endif
Jesus Cea7e9065c2010-10-25 13:02:04 +000010995#ifdef _PC_ACL_ENABLED
10996 {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
10997#endif
10998#ifdef _PC_MIN_HOLE_SIZE
10999 {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
11000#endif
11001#ifdef _PC_ALLOC_SIZE_MIN
11002 {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
11003#endif
11004#ifdef _PC_REC_INCR_XFER_SIZE
11005 {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
11006#endif
11007#ifdef _PC_REC_MAX_XFER_SIZE
11008 {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
11009#endif
11010#ifdef _PC_REC_MIN_XFER_SIZE
11011 {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
11012#endif
11013#ifdef _PC_REC_XFER_ALIGN
11014 {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
11015#endif
11016#ifdef _PC_SYMLINK_MAX
11017 {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
11018#endif
11019#ifdef _PC_XATTR_ENABLED
11020 {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
11021#endif
11022#ifdef _PC_XATTR_EXISTS
11023 {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
11024#endif
11025#ifdef _PC_TIMESTAMP_RESOLUTION
11026 {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
11027#endif
Fred Drakec9680921999-12-13 16:37:25 +000011028};
11029
Fred Drakec9680921999-12-13 16:37:25 +000011030static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011031conv_path_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011032{
11033 return conv_confname(arg, valuep, posix_constants_pathconf,
11034 sizeof(posix_constants_pathconf)
11035 / sizeof(struct constdef));
11036}
11037#endif
11038
Larry Hastings2f936352014-08-05 14:04:04 +100011039
Fred Drakec9680921999-12-13 16:37:25 +000011040#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100011041/*[clinic input]
11042os.fpathconf -> long
11043
Gregory P. Smith3ccb96c2020-06-20 15:06:48 -070011044 fd: fildes
Larry Hastings2f936352014-08-05 14:04:04 +100011045 name: path_confname
11046 /
11047
11048Return the configuration limit name for the file descriptor fd.
11049
11050If there is no limit, return -1.
11051[clinic start generated code]*/
11052
Larry Hastings2f936352014-08-05 14:04:04 +100011053static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011054os_fpathconf_impl(PyObject *module, int fd, int name)
Gregory P. Smith3ccb96c2020-06-20 15:06:48 -070011055/*[clinic end generated code: output=d5b7042425fc3e21 input=5b8d2471cfaae186]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011056{
11057 long limit;
11058
11059 errno = 0;
11060 limit = fpathconf(fd, name);
11061 if (limit == -1 && errno != 0)
11062 posix_error();
11063
11064 return limit;
11065}
11066#endif /* HAVE_FPATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011067
11068
11069#ifdef HAVE_PATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100011070/*[clinic input]
11071os.pathconf -> long
11072 path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
11073 name: path_confname
11074
11075Return the configuration limit name for the file or directory path.
11076
11077If there is no limit, return -1.
11078On some platforms, path may also be specified as an open file descriptor.
11079 If this functionality is unavailable, using it raises an exception.
11080[clinic start generated code]*/
11081
Larry Hastings2f936352014-08-05 14:04:04 +100011082static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011083os_pathconf_impl(PyObject *module, path_t *path, int name)
11084/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011085{
Victor Stinner8c62be82010-05-06 00:08:46 +000011086 long limit;
Fred Drakec9680921999-12-13 16:37:25 +000011087
Victor Stinner8c62be82010-05-06 00:08:46 +000011088 errno = 0;
Georg Brandl306336b2012-06-24 12:55:33 +020011089#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100011090 if (path->fd != -1)
11091 limit = fpathconf(path->fd, name);
Georg Brandl306336b2012-06-24 12:55:33 +020011092 else
11093#endif
Larry Hastings2f936352014-08-05 14:04:04 +100011094 limit = pathconf(path->narrow, name);
Victor Stinner8c62be82010-05-06 00:08:46 +000011095 if (limit == -1 && errno != 0) {
11096 if (errno == EINVAL)
Stefan Krah99439262010-11-26 12:58:05 +000011097 /* could be a path or name problem */
11098 posix_error();
Fred Drakec9680921999-12-13 16:37:25 +000011099 else
Larry Hastings2f936352014-08-05 14:04:04 +100011100 path_error(path);
Victor Stinner8c62be82010-05-06 00:08:46 +000011101 }
Larry Hastings2f936352014-08-05 14:04:04 +100011102
11103 return limit;
Fred Drakec9680921999-12-13 16:37:25 +000011104}
Larry Hastings2f936352014-08-05 14:04:04 +100011105#endif /* HAVE_PATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011106
11107#ifdef HAVE_CONFSTR
11108static struct constdef posix_constants_confstr[] = {
Fred Draked86ed291999-12-15 15:34:33 +000011109#ifdef _CS_ARCHITECTURE
Victor Stinner8c62be82010-05-06 00:08:46 +000011110 {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
Fred Draked86ed291999-12-15 15:34:33 +000011111#endif
Mark Dickinson876d7c82010-04-16 12:47:52 +000011112#ifdef _CS_GNU_LIBC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011113 {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000011114#endif
11115#ifdef _CS_GNU_LIBPTHREAD_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011116 {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000011117#endif
Fred Draked86ed291999-12-15 15:34:33 +000011118#ifdef _CS_HOSTNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011119 {"CS_HOSTNAME", _CS_HOSTNAME},
Fred Draked86ed291999-12-15 15:34:33 +000011120#endif
11121#ifdef _CS_HW_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000011122 {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000011123#endif
11124#ifdef _CS_HW_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000011125 {"CS_HW_SERIAL", _CS_HW_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000011126#endif
11127#ifdef _CS_INITTAB_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011128 {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000011129#endif
Fred Drakec9680921999-12-13 16:37:25 +000011130#ifdef _CS_LFS64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011131 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011132#endif
11133#ifdef _CS_LFS64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011134 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011135#endif
11136#ifdef _CS_LFS64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011137 {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011138#endif
11139#ifdef _CS_LFS64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011140 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011141#endif
11142#ifdef _CS_LFS_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011143 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011144#endif
11145#ifdef _CS_LFS_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011146 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011147#endif
11148#ifdef _CS_LFS_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011149 {"CS_LFS_LIBS", _CS_LFS_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011150#endif
11151#ifdef _CS_LFS_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011152 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011153#endif
Fred Draked86ed291999-12-15 15:34:33 +000011154#ifdef _CS_MACHINE
Victor Stinner8c62be82010-05-06 00:08:46 +000011155 {"CS_MACHINE", _CS_MACHINE},
Fred Draked86ed291999-12-15 15:34:33 +000011156#endif
Fred Drakec9680921999-12-13 16:37:25 +000011157#ifdef _CS_PATH
Victor Stinner8c62be82010-05-06 00:08:46 +000011158 {"CS_PATH", _CS_PATH},
Fred Drakec9680921999-12-13 16:37:25 +000011159#endif
Fred Draked86ed291999-12-15 15:34:33 +000011160#ifdef _CS_RELEASE
Victor Stinner8c62be82010-05-06 00:08:46 +000011161 {"CS_RELEASE", _CS_RELEASE},
Fred Draked86ed291999-12-15 15:34:33 +000011162#endif
11163#ifdef _CS_SRPC_DOMAIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011164 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
Fred Draked86ed291999-12-15 15:34:33 +000011165#endif
11166#ifdef _CS_SYSNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011167 {"CS_SYSNAME", _CS_SYSNAME},
Fred Draked86ed291999-12-15 15:34:33 +000011168#endif
11169#ifdef _CS_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011170 {"CS_VERSION", _CS_VERSION},
Fred Draked86ed291999-12-15 15:34:33 +000011171#endif
Fred Drakec9680921999-12-13 16:37:25 +000011172#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011173 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011174#endif
11175#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011176 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011177#endif
11178#ifdef _CS_XBS5_ILP32_OFF32_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011179 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011180#endif
11181#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011182 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011183#endif
11184#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011185 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011186#endif
11187#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011188 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011189#endif
11190#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011191 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011192#endif
11193#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011194 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011195#endif
11196#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011197 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011198#endif
11199#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011200 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011201#endif
11202#ifdef _CS_XBS5_LP64_OFF64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011203 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011204#endif
11205#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011206 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011207#endif
11208#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011209 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011210#endif
11211#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011212 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011213#endif
11214#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011215 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011216#endif
11217#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011218 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011219#endif
Fred Draked86ed291999-12-15 15:34:33 +000011220#ifdef _MIPS_CS_AVAIL_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000011221 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000011222#endif
11223#ifdef _MIPS_CS_BASE
Victor Stinner8c62be82010-05-06 00:08:46 +000011224 {"MIPS_CS_BASE", _MIPS_CS_BASE},
Fred Draked86ed291999-12-15 15:34:33 +000011225#endif
11226#ifdef _MIPS_CS_HOSTID
Victor Stinner8c62be82010-05-06 00:08:46 +000011227 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
Fred Draked86ed291999-12-15 15:34:33 +000011228#endif
11229#ifdef _MIPS_CS_HW_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011230 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000011231#endif
11232#ifdef _MIPS_CS_NUM_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000011233 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000011234#endif
11235#ifdef _MIPS_CS_OSREL_MAJ
Victor Stinner8c62be82010-05-06 00:08:46 +000011236 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
Fred Draked86ed291999-12-15 15:34:33 +000011237#endif
11238#ifdef _MIPS_CS_OSREL_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011239 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
Fred Draked86ed291999-12-15 15:34:33 +000011240#endif
11241#ifdef _MIPS_CS_OSREL_PATCH
Victor Stinner8c62be82010-05-06 00:08:46 +000011242 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
Fred Draked86ed291999-12-15 15:34:33 +000011243#endif
11244#ifdef _MIPS_CS_OS_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011245 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000011246#endif
11247#ifdef _MIPS_CS_OS_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000011248 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000011249#endif
11250#ifdef _MIPS_CS_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000011251 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000011252#endif
11253#ifdef _MIPS_CS_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000011254 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000011255#endif
11256#ifdef _MIPS_CS_VENDOR
Victor Stinner8c62be82010-05-06 00:08:46 +000011257 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
Fred Draked86ed291999-12-15 15:34:33 +000011258#endif
Fred Drakec9680921999-12-13 16:37:25 +000011259};
11260
11261static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011262conv_confstr_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011263{
11264 return conv_confname(arg, valuep, posix_constants_confstr,
11265 sizeof(posix_constants_confstr)
11266 / sizeof(struct constdef));
11267}
11268
Larry Hastings2f936352014-08-05 14:04:04 +100011269
11270/*[clinic input]
11271os.confstr
11272
11273 name: confstr_confname
11274 /
11275
11276Return a string-valued system configuration variable.
11277[clinic start generated code]*/
11278
Larry Hastings2f936352014-08-05 14:04:04 +100011279static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011280os_confstr_impl(PyObject *module, int name)
11281/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
Fred Drakec9680921999-12-13 16:37:25 +000011282{
11283 PyObject *result = NULL;
Victor Stinnercb043522010-09-10 23:49:04 +000011284 char buffer[255];
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011285 size_t len;
Fred Drakec9680921999-12-13 16:37:25 +000011286
Victor Stinnercb043522010-09-10 23:49:04 +000011287 errno = 0;
11288 len = confstr(name, buffer, sizeof(buffer));
11289 if (len == 0) {
11290 if (errno) {
11291 posix_error();
11292 return NULL;
Fred Drakec9680921999-12-13 16:37:25 +000011293 }
11294 else {
Victor Stinnercb043522010-09-10 23:49:04 +000011295 Py_RETURN_NONE;
Fred Drakec9680921999-12-13 16:37:25 +000011296 }
11297 }
Victor Stinnercb043522010-09-10 23:49:04 +000011298
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011299 if (len >= sizeof(buffer)) {
Victor Stinnercbc18f32014-12-05 22:51:51 +010011300 size_t len2;
Victor Stinnercb043522010-09-10 23:49:04 +000011301 char *buf = PyMem_Malloc(len);
11302 if (buf == NULL)
11303 return PyErr_NoMemory();
Victor Stinnercbc18f32014-12-05 22:51:51 +010011304 len2 = confstr(name, buf, len);
11305 assert(len == len2);
Christian Heimes8714cfd2015-04-21 10:57:41 +020011306 result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
Victor Stinnercb043522010-09-10 23:49:04 +000011307 PyMem_Free(buf);
11308 }
11309 else
11310 result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
Fred Drakec9680921999-12-13 16:37:25 +000011311 return result;
11312}
Larry Hastings2f936352014-08-05 14:04:04 +100011313#endif /* HAVE_CONFSTR */
Fred Drakec9680921999-12-13 16:37:25 +000011314
11315
11316#ifdef HAVE_SYSCONF
11317static struct constdef posix_constants_sysconf[] = {
11318#ifdef _SC_2_CHAR_TERM
Victor Stinner8c62be82010-05-06 00:08:46 +000011319 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
Fred Drakec9680921999-12-13 16:37:25 +000011320#endif
11321#ifdef _SC_2_C_BIND
Victor Stinner8c62be82010-05-06 00:08:46 +000011322 {"SC_2_C_BIND", _SC_2_C_BIND},
Fred Drakec9680921999-12-13 16:37:25 +000011323#endif
11324#ifdef _SC_2_C_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011325 {"SC_2_C_DEV", _SC_2_C_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011326#endif
11327#ifdef _SC_2_C_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011328 {"SC_2_C_VERSION", _SC_2_C_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011329#endif
11330#ifdef _SC_2_FORT_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011331 {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011332#endif
11333#ifdef _SC_2_FORT_RUN
Victor Stinner8c62be82010-05-06 00:08:46 +000011334 {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
Fred Drakec9680921999-12-13 16:37:25 +000011335#endif
11336#ifdef _SC_2_LOCALEDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000011337 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
Fred Drakec9680921999-12-13 16:37:25 +000011338#endif
11339#ifdef _SC_2_SW_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011340 {"SC_2_SW_DEV", _SC_2_SW_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011341#endif
11342#ifdef _SC_2_UPE
Victor Stinner8c62be82010-05-06 00:08:46 +000011343 {"SC_2_UPE", _SC_2_UPE},
Fred Drakec9680921999-12-13 16:37:25 +000011344#endif
11345#ifdef _SC_2_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011346 {"SC_2_VERSION", _SC_2_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011347#endif
Fred Draked86ed291999-12-15 15:34:33 +000011348#ifdef _SC_ABI_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011349 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
Fred Draked86ed291999-12-15 15:34:33 +000011350#endif
11351#ifdef _SC_ACL
Victor Stinner8c62be82010-05-06 00:08:46 +000011352 {"SC_ACL", _SC_ACL},
Fred Draked86ed291999-12-15 15:34:33 +000011353#endif
Fred Drakec9680921999-12-13 16:37:25 +000011354#ifdef _SC_AIO_LISTIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011355 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011356#endif
Fred Drakec9680921999-12-13 16:37:25 +000011357#ifdef _SC_AIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011358 {"SC_AIO_MAX", _SC_AIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011359#endif
11360#ifdef _SC_AIO_PRIO_DELTA_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011361 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011362#endif
11363#ifdef _SC_ARG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011364 {"SC_ARG_MAX", _SC_ARG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011365#endif
11366#ifdef _SC_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011367 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011368#endif
11369#ifdef _SC_ATEXIT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011370 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011371#endif
Fred Draked86ed291999-12-15 15:34:33 +000011372#ifdef _SC_AUDIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011373 {"SC_AUDIT", _SC_AUDIT},
Fred Draked86ed291999-12-15 15:34:33 +000011374#endif
Fred Drakec9680921999-12-13 16:37:25 +000011375#ifdef _SC_AVPHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011376 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011377#endif
11378#ifdef _SC_BC_BASE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011379 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011380#endif
11381#ifdef _SC_BC_DIM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011382 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011383#endif
11384#ifdef _SC_BC_SCALE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011385 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011386#endif
11387#ifdef _SC_BC_STRING_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011388 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011389#endif
Fred Draked86ed291999-12-15 15:34:33 +000011390#ifdef _SC_CAP
Victor Stinner8c62be82010-05-06 00:08:46 +000011391 {"SC_CAP", _SC_CAP},
Fred Draked86ed291999-12-15 15:34:33 +000011392#endif
Fred Drakec9680921999-12-13 16:37:25 +000011393#ifdef _SC_CHARCLASS_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011394 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011395#endif
11396#ifdef _SC_CHAR_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011397 {"SC_CHAR_BIT", _SC_CHAR_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011398#endif
11399#ifdef _SC_CHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011400 {"SC_CHAR_MAX", _SC_CHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011401#endif
11402#ifdef _SC_CHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011403 {"SC_CHAR_MIN", _SC_CHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011404#endif
11405#ifdef _SC_CHILD_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011406 {"SC_CHILD_MAX", _SC_CHILD_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011407#endif
11408#ifdef _SC_CLK_TCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011409 {"SC_CLK_TCK", _SC_CLK_TCK},
Fred Drakec9680921999-12-13 16:37:25 +000011410#endif
11411#ifdef _SC_COHER_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011412 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011413#endif
11414#ifdef _SC_COLL_WEIGHTS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011415 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011416#endif
11417#ifdef _SC_DCACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011418 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011419#endif
11420#ifdef _SC_DCACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011421 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011422#endif
11423#ifdef _SC_DCACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011424 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011425#endif
11426#ifdef _SC_DCACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011427 {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011428#endif
11429#ifdef _SC_DCACHE_TBLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011430 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011431#endif
11432#ifdef _SC_DELAYTIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011433 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011434#endif
11435#ifdef _SC_EQUIV_CLASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011436 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011437#endif
11438#ifdef _SC_EXPR_NEST_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011439 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011440#endif
11441#ifdef _SC_FSYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000011442 {"SC_FSYNC", _SC_FSYNC},
Fred Drakec9680921999-12-13 16:37:25 +000011443#endif
11444#ifdef _SC_GETGR_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011445 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011446#endif
11447#ifdef _SC_GETPW_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011448 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011449#endif
11450#ifdef _SC_ICACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011451 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011452#endif
11453#ifdef _SC_ICACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011454 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011455#endif
11456#ifdef _SC_ICACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011457 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011458#endif
11459#ifdef _SC_ICACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011460 {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011461#endif
Fred Draked86ed291999-12-15 15:34:33 +000011462#ifdef _SC_INF
Victor Stinner8c62be82010-05-06 00:08:46 +000011463 {"SC_INF", _SC_INF},
Fred Draked86ed291999-12-15 15:34:33 +000011464#endif
Fred Drakec9680921999-12-13 16:37:25 +000011465#ifdef _SC_INT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011466 {"SC_INT_MAX", _SC_INT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011467#endif
11468#ifdef _SC_INT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011469 {"SC_INT_MIN", _SC_INT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011470#endif
11471#ifdef _SC_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011472 {"SC_IOV_MAX", _SC_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011473#endif
Fred Draked86ed291999-12-15 15:34:33 +000011474#ifdef _SC_IP_SECOPTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011475 {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
Fred Draked86ed291999-12-15 15:34:33 +000011476#endif
Fred Drakec9680921999-12-13 16:37:25 +000011477#ifdef _SC_JOB_CONTROL
Victor Stinner8c62be82010-05-06 00:08:46 +000011478 {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
Fred Drakec9680921999-12-13 16:37:25 +000011479#endif
Fred Draked86ed291999-12-15 15:34:33 +000011480#ifdef _SC_KERN_POINTERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011481 {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
Fred Draked86ed291999-12-15 15:34:33 +000011482#endif
11483#ifdef _SC_KERN_SIM
Victor Stinner8c62be82010-05-06 00:08:46 +000011484 {"SC_KERN_SIM", _SC_KERN_SIM},
Fred Draked86ed291999-12-15 15:34:33 +000011485#endif
Fred Drakec9680921999-12-13 16:37:25 +000011486#ifdef _SC_LINE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011487 {"SC_LINE_MAX", _SC_LINE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011488#endif
11489#ifdef _SC_LOGIN_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011490 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011491#endif
11492#ifdef _SC_LOGNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011493 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011494#endif
11495#ifdef _SC_LONG_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011496 {"SC_LONG_BIT", _SC_LONG_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011497#endif
Fred Draked86ed291999-12-15 15:34:33 +000011498#ifdef _SC_MAC
Victor Stinner8c62be82010-05-06 00:08:46 +000011499 {"SC_MAC", _SC_MAC},
Fred Draked86ed291999-12-15 15:34:33 +000011500#endif
Fred Drakec9680921999-12-13 16:37:25 +000011501#ifdef _SC_MAPPED_FILES
Victor Stinner8c62be82010-05-06 00:08:46 +000011502 {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
Fred Drakec9680921999-12-13 16:37:25 +000011503#endif
11504#ifdef _SC_MAXPID
Victor Stinner8c62be82010-05-06 00:08:46 +000011505 {"SC_MAXPID", _SC_MAXPID},
Fred Drakec9680921999-12-13 16:37:25 +000011506#endif
11507#ifdef _SC_MB_LEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011508 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011509#endif
11510#ifdef _SC_MEMLOCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011511 {"SC_MEMLOCK", _SC_MEMLOCK},
Fred Drakec9680921999-12-13 16:37:25 +000011512#endif
11513#ifdef _SC_MEMLOCK_RANGE
Victor Stinner8c62be82010-05-06 00:08:46 +000011514 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
Fred Drakec9680921999-12-13 16:37:25 +000011515#endif
11516#ifdef _SC_MEMORY_PROTECTION
Victor Stinner8c62be82010-05-06 00:08:46 +000011517 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
Fred Drakec9680921999-12-13 16:37:25 +000011518#endif
11519#ifdef _SC_MESSAGE_PASSING
Victor Stinner8c62be82010-05-06 00:08:46 +000011520 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
Fred Drakec9680921999-12-13 16:37:25 +000011521#endif
Fred Draked86ed291999-12-15 15:34:33 +000011522#ifdef _SC_MMAP_FIXED_ALIGNMENT
Victor Stinner8c62be82010-05-06 00:08:46 +000011523 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
Fred Draked86ed291999-12-15 15:34:33 +000011524#endif
Fred Drakec9680921999-12-13 16:37:25 +000011525#ifdef _SC_MQ_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011526 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011527#endif
11528#ifdef _SC_MQ_PRIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011529 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011530#endif
Fred Draked86ed291999-12-15 15:34:33 +000011531#ifdef _SC_NACLS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011532 {"SC_NACLS_MAX", _SC_NACLS_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000011533#endif
Fred Drakec9680921999-12-13 16:37:25 +000011534#ifdef _SC_NGROUPS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011535 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011536#endif
11537#ifdef _SC_NL_ARGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011538 {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011539#endif
11540#ifdef _SC_NL_LANGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011541 {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011542#endif
11543#ifdef _SC_NL_MSGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011544 {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011545#endif
11546#ifdef _SC_NL_NMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011547 {"SC_NL_NMAX", _SC_NL_NMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011548#endif
11549#ifdef _SC_NL_SETMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011550 {"SC_NL_SETMAX", _SC_NL_SETMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011551#endif
11552#ifdef _SC_NL_TEXTMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011553 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011554#endif
11555#ifdef _SC_NPROCESSORS_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011556 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
Fred Drakec9680921999-12-13 16:37:25 +000011557#endif
11558#ifdef _SC_NPROCESSORS_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011559 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
Fred Drakec9680921999-12-13 16:37:25 +000011560#endif
Fred Draked86ed291999-12-15 15:34:33 +000011561#ifdef _SC_NPROC_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011562 {"SC_NPROC_CONF", _SC_NPROC_CONF},
Fred Draked86ed291999-12-15 15:34:33 +000011563#endif
11564#ifdef _SC_NPROC_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011565 {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
Fred Draked86ed291999-12-15 15:34:33 +000011566#endif
Fred Drakec9680921999-12-13 16:37:25 +000011567#ifdef _SC_NZERO
Victor Stinner8c62be82010-05-06 00:08:46 +000011568 {"SC_NZERO", _SC_NZERO},
Fred Drakec9680921999-12-13 16:37:25 +000011569#endif
11570#ifdef _SC_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011571 {"SC_OPEN_MAX", _SC_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011572#endif
11573#ifdef _SC_PAGESIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011574 {"SC_PAGESIZE", _SC_PAGESIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011575#endif
11576#ifdef _SC_PAGE_SIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011577 {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011578#endif
Batuhan Taşkaya909f4a32020-04-05 03:40:49 +030011579#ifdef _SC_AIX_REALMEM
11580 {"SC_AIX_REALMEM", _SC_AIX_REALMEM},
11581#endif
Fred Drakec9680921999-12-13 16:37:25 +000011582#ifdef _SC_PASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011583 {"SC_PASS_MAX", _SC_PASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011584#endif
11585#ifdef _SC_PHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011586 {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011587#endif
11588#ifdef _SC_PII
Victor Stinner8c62be82010-05-06 00:08:46 +000011589 {"SC_PII", _SC_PII},
Fred Drakec9680921999-12-13 16:37:25 +000011590#endif
11591#ifdef _SC_PII_INTERNET
Victor Stinner8c62be82010-05-06 00:08:46 +000011592 {"SC_PII_INTERNET", _SC_PII_INTERNET},
Fred Drakec9680921999-12-13 16:37:25 +000011593#endif
11594#ifdef _SC_PII_INTERNET_DGRAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011595 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
Fred Drakec9680921999-12-13 16:37:25 +000011596#endif
11597#ifdef _SC_PII_INTERNET_STREAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011598 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
Fred Drakec9680921999-12-13 16:37:25 +000011599#endif
11600#ifdef _SC_PII_OSI
Victor Stinner8c62be82010-05-06 00:08:46 +000011601 {"SC_PII_OSI", _SC_PII_OSI},
Fred Drakec9680921999-12-13 16:37:25 +000011602#endif
11603#ifdef _SC_PII_OSI_CLTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011604 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
Fred Drakec9680921999-12-13 16:37:25 +000011605#endif
11606#ifdef _SC_PII_OSI_COTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011607 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
Fred Drakec9680921999-12-13 16:37:25 +000011608#endif
11609#ifdef _SC_PII_OSI_M
Victor Stinner8c62be82010-05-06 00:08:46 +000011610 {"SC_PII_OSI_M", _SC_PII_OSI_M},
Fred Drakec9680921999-12-13 16:37:25 +000011611#endif
11612#ifdef _SC_PII_SOCKET
Victor Stinner8c62be82010-05-06 00:08:46 +000011613 {"SC_PII_SOCKET", _SC_PII_SOCKET},
Fred Drakec9680921999-12-13 16:37:25 +000011614#endif
11615#ifdef _SC_PII_XTI
Victor Stinner8c62be82010-05-06 00:08:46 +000011616 {"SC_PII_XTI", _SC_PII_XTI},
Fred Drakec9680921999-12-13 16:37:25 +000011617#endif
11618#ifdef _SC_POLL
Victor Stinner8c62be82010-05-06 00:08:46 +000011619 {"SC_POLL", _SC_POLL},
Fred Drakec9680921999-12-13 16:37:25 +000011620#endif
11621#ifdef _SC_PRIORITIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011622 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011623#endif
11624#ifdef _SC_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011625 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011626#endif
11627#ifdef _SC_REALTIME_SIGNALS
Victor Stinner8c62be82010-05-06 00:08:46 +000011628 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
Fred Drakec9680921999-12-13 16:37:25 +000011629#endif
11630#ifdef _SC_RE_DUP_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011631 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011632#endif
11633#ifdef _SC_RTSIG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011634 {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011635#endif
11636#ifdef _SC_SAVED_IDS
Victor Stinner8c62be82010-05-06 00:08:46 +000011637 {"SC_SAVED_IDS", _SC_SAVED_IDS},
Fred Drakec9680921999-12-13 16:37:25 +000011638#endif
11639#ifdef _SC_SCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011640 {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011641#endif
11642#ifdef _SC_SCHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011643 {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011644#endif
11645#ifdef _SC_SELECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011646 {"SC_SELECT", _SC_SELECT},
Fred Drakec9680921999-12-13 16:37:25 +000011647#endif
11648#ifdef _SC_SEMAPHORES
Victor Stinner8c62be82010-05-06 00:08:46 +000011649 {"SC_SEMAPHORES", _SC_SEMAPHORES},
Fred Drakec9680921999-12-13 16:37:25 +000011650#endif
11651#ifdef _SC_SEM_NSEMS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011652 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011653#endif
11654#ifdef _SC_SEM_VALUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011655 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011656#endif
11657#ifdef _SC_SHARED_MEMORY_OBJECTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011658 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
Fred Drakec9680921999-12-13 16:37:25 +000011659#endif
11660#ifdef _SC_SHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011661 {"SC_SHRT_MAX", _SC_SHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011662#endif
11663#ifdef _SC_SHRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011664 {"SC_SHRT_MIN", _SC_SHRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011665#endif
11666#ifdef _SC_SIGQUEUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011667 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011668#endif
11669#ifdef _SC_SIGRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011670 {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011671#endif
11672#ifdef _SC_SIGRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011673 {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011674#endif
Fred Draked86ed291999-12-15 15:34:33 +000011675#ifdef _SC_SOFTPOWER
Victor Stinner8c62be82010-05-06 00:08:46 +000011676 {"SC_SOFTPOWER", _SC_SOFTPOWER},
Fred Draked86ed291999-12-15 15:34:33 +000011677#endif
Fred Drakec9680921999-12-13 16:37:25 +000011678#ifdef _SC_SPLIT_CACHE
Victor Stinner8c62be82010-05-06 00:08:46 +000011679 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
Fred Drakec9680921999-12-13 16:37:25 +000011680#endif
11681#ifdef _SC_SSIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011682 {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011683#endif
11684#ifdef _SC_STACK_PROT
Victor Stinner8c62be82010-05-06 00:08:46 +000011685 {"SC_STACK_PROT", _SC_STACK_PROT},
Fred Drakec9680921999-12-13 16:37:25 +000011686#endif
11687#ifdef _SC_STREAM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011688 {"SC_STREAM_MAX", _SC_STREAM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011689#endif
11690#ifdef _SC_SYNCHRONIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011691 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011692#endif
11693#ifdef _SC_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011694 {"SC_THREADS", _SC_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011695#endif
11696#ifdef _SC_THREAD_ATTR_STACKADDR
Victor Stinner8c62be82010-05-06 00:08:46 +000011697 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
Fred Drakec9680921999-12-13 16:37:25 +000011698#endif
11699#ifdef _SC_THREAD_ATTR_STACKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011700 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011701#endif
11702#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011703 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011704#endif
11705#ifdef _SC_THREAD_KEYS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011706 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011707#endif
11708#ifdef _SC_THREAD_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011709 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011710#endif
11711#ifdef _SC_THREAD_PRIO_INHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011712 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
Fred Drakec9680921999-12-13 16:37:25 +000011713#endif
11714#ifdef _SC_THREAD_PRIO_PROTECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011715 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
Fred Drakec9680921999-12-13 16:37:25 +000011716#endif
11717#ifdef _SC_THREAD_PROCESS_SHARED
Victor Stinner8c62be82010-05-06 00:08:46 +000011718 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
Fred Drakec9680921999-12-13 16:37:25 +000011719#endif
11720#ifdef _SC_THREAD_SAFE_FUNCTIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011721 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011722#endif
11723#ifdef _SC_THREAD_STACK_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011724 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011725#endif
11726#ifdef _SC_THREAD_THREADS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011727 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011728#endif
11729#ifdef _SC_TIMERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011730 {"SC_TIMERS", _SC_TIMERS},
Fred Drakec9680921999-12-13 16:37:25 +000011731#endif
11732#ifdef _SC_TIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011733 {"SC_TIMER_MAX", _SC_TIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011734#endif
11735#ifdef _SC_TTY_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011736 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011737#endif
11738#ifdef _SC_TZNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011739 {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011740#endif
11741#ifdef _SC_T_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011742 {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011743#endif
11744#ifdef _SC_UCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011745 {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011746#endif
11747#ifdef _SC_UINT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011748 {"SC_UINT_MAX", _SC_UINT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011749#endif
11750#ifdef _SC_UIO_MAXIOV
Victor Stinner8c62be82010-05-06 00:08:46 +000011751 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
Fred Drakec9680921999-12-13 16:37:25 +000011752#endif
11753#ifdef _SC_ULONG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011754 {"SC_ULONG_MAX", _SC_ULONG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011755#endif
11756#ifdef _SC_USHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011757 {"SC_USHRT_MAX", _SC_USHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011758#endif
11759#ifdef _SC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011760 {"SC_VERSION", _SC_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011761#endif
11762#ifdef _SC_WORD_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011763 {"SC_WORD_BIT", _SC_WORD_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011764#endif
11765#ifdef _SC_XBS5_ILP32_OFF32
Victor Stinner8c62be82010-05-06 00:08:46 +000011766 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
Fred Drakec9680921999-12-13 16:37:25 +000011767#endif
11768#ifdef _SC_XBS5_ILP32_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011769 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011770#endif
11771#ifdef _SC_XBS5_LP64_OFF64
Victor Stinner8c62be82010-05-06 00:08:46 +000011772 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
Fred Drakec9680921999-12-13 16:37:25 +000011773#endif
11774#ifdef _SC_XBS5_LPBIG_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011775 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011776#endif
11777#ifdef _SC_XOPEN_CRYPT
Victor Stinner8c62be82010-05-06 00:08:46 +000011778 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
Fred Drakec9680921999-12-13 16:37:25 +000011779#endif
11780#ifdef _SC_XOPEN_ENH_I18N
Victor Stinner8c62be82010-05-06 00:08:46 +000011781 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
Fred Drakec9680921999-12-13 16:37:25 +000011782#endif
11783#ifdef _SC_XOPEN_LEGACY
Victor Stinner8c62be82010-05-06 00:08:46 +000011784 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
Fred Drakec9680921999-12-13 16:37:25 +000011785#endif
11786#ifdef _SC_XOPEN_REALTIME
Victor Stinner8c62be82010-05-06 00:08:46 +000011787 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
Fred Drakec9680921999-12-13 16:37:25 +000011788#endif
11789#ifdef _SC_XOPEN_REALTIME_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011790 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011791#endif
11792#ifdef _SC_XOPEN_SHM
Victor Stinner8c62be82010-05-06 00:08:46 +000011793 {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
Fred Drakec9680921999-12-13 16:37:25 +000011794#endif
11795#ifdef _SC_XOPEN_UNIX
Victor Stinner8c62be82010-05-06 00:08:46 +000011796 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
Fred Drakec9680921999-12-13 16:37:25 +000011797#endif
11798#ifdef _SC_XOPEN_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011799 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011800#endif
11801#ifdef _SC_XOPEN_XCU_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011802 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011803#endif
11804#ifdef _SC_XOPEN_XPG2
Victor Stinner8c62be82010-05-06 00:08:46 +000011805 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
Fred Drakec9680921999-12-13 16:37:25 +000011806#endif
11807#ifdef _SC_XOPEN_XPG3
Victor Stinner8c62be82010-05-06 00:08:46 +000011808 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
Fred Drakec9680921999-12-13 16:37:25 +000011809#endif
11810#ifdef _SC_XOPEN_XPG4
Victor Stinner8c62be82010-05-06 00:08:46 +000011811 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
Fred Drakec9680921999-12-13 16:37:25 +000011812#endif
11813};
11814
11815static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011816conv_sysconf_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011817{
11818 return conv_confname(arg, valuep, posix_constants_sysconf,
11819 sizeof(posix_constants_sysconf)
11820 / sizeof(struct constdef));
11821}
11822
Larry Hastings2f936352014-08-05 14:04:04 +100011823
11824/*[clinic input]
11825os.sysconf -> long
11826 name: sysconf_confname
11827 /
11828
11829Return an integer-valued system configuration variable.
11830[clinic start generated code]*/
11831
Larry Hastings2f936352014-08-05 14:04:04 +100011832static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011833os_sysconf_impl(PyObject *module, int name)
11834/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011835{
11836 long value;
11837
11838 errno = 0;
11839 value = sysconf(name);
11840 if (value == -1 && errno != 0)
11841 posix_error();
11842 return value;
11843}
11844#endif /* HAVE_SYSCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011845
11846
Fred Drakebec628d1999-12-15 18:31:10 +000011847/* This code is used to ensure that the tables of configuration value names
Serhiy Storchaka56a6d852014-12-01 18:28:43 +020011848 * are in sorted order as required by conv_confname(), and also to build
Fred Drakebec628d1999-12-15 18:31:10 +000011849 * the exported dictionaries that are used to publish information about the
11850 * names available on the host platform.
11851 *
11852 * Sorting the table at runtime ensures that the table is properly ordered
11853 * when used, even for platforms we're not able to test on. It also makes
11854 * it easier to add additional entries to the tables.
Fred Draked86ed291999-12-15 15:34:33 +000011855 */
Fred Drakebec628d1999-12-15 18:31:10 +000011856
11857static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011858cmp_constdefs(const void *v1, const void *v2)
Fred Drakebec628d1999-12-15 18:31:10 +000011859{
11860 const struct constdef *c1 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011861 (const struct constdef *) v1;
Fred Drakebec628d1999-12-15 18:31:10 +000011862 const struct constdef *c2 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011863 (const struct constdef *) v2;
Fred Drakebec628d1999-12-15 18:31:10 +000011864
11865 return strcmp(c1->name, c2->name);
11866}
11867
11868static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011869setup_confname_table(struct constdef *table, size_t tablesize,
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011870 const char *tablename, PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011871{
Fred Drakebec628d1999-12-15 18:31:10 +000011872 PyObject *d = NULL;
Barry Warsaw3155db32000-04-13 15:20:40 +000011873 size_t i;
Fred Drakebec628d1999-12-15 18:31:10 +000011874
11875 qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
11876 d = PyDict_New();
Barry Warsaw3155db32000-04-13 15:20:40 +000011877 if (d == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +000011878 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011879
Barry Warsaw3155db32000-04-13 15:20:40 +000011880 for (i=0; i < tablesize; ++i) {
Victor Stinner8c62be82010-05-06 00:08:46 +000011881 PyObject *o = PyLong_FromLong(table[i].value);
11882 if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
11883 Py_XDECREF(o);
11884 Py_DECREF(d);
11885 return -1;
11886 }
11887 Py_DECREF(o);
Fred Draked86ed291999-12-15 15:34:33 +000011888 }
Fred Drake4d1e64b2002-04-15 19:40:07 +000011889 return PyModule_AddObject(module, tablename, d);
Fred Draked86ed291999-12-15 15:34:33 +000011890}
11891
Fred Drakebec628d1999-12-15 18:31:10 +000011892/* Return -1 on failure, 0 on success. */
11893static int
Fred Drake4d1e64b2002-04-15 19:40:07 +000011894setup_confname_tables(PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011895{
11896#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
Fred Drakebec628d1999-12-15 18:31:10 +000011897 if (setup_confname_table(posix_constants_pathconf,
Fred Draked86ed291999-12-15 15:34:33 +000011898 sizeof(posix_constants_pathconf)
11899 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011900 "pathconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011901 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011902#endif
11903#ifdef HAVE_CONFSTR
Fred Drakebec628d1999-12-15 18:31:10 +000011904 if (setup_confname_table(posix_constants_confstr,
Fred Draked86ed291999-12-15 15:34:33 +000011905 sizeof(posix_constants_confstr)
11906 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011907 "confstr_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011908 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011909#endif
11910#ifdef HAVE_SYSCONF
Fred Drakebec628d1999-12-15 18:31:10 +000011911 if (setup_confname_table(posix_constants_sysconf,
Fred Draked86ed291999-12-15 15:34:33 +000011912 sizeof(posix_constants_sysconf)
11913 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011914 "sysconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011915 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011916#endif
Fred Drakebec628d1999-12-15 18:31:10 +000011917 return 0;
Fred Draked86ed291999-12-15 15:34:33 +000011918}
Fred Draked86ed291999-12-15 15:34:33 +000011919
11920
Larry Hastings2f936352014-08-05 14:04:04 +100011921/*[clinic input]
11922os.abort
11923
11924Abort the interpreter immediately.
11925
11926This function 'dumps core' or otherwise fails in the hardest way possible
11927on the hosting operating system. This function never returns.
11928[clinic start generated code]*/
11929
Larry Hastings2f936352014-08-05 14:04:04 +100011930static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011931os_abort_impl(PyObject *module)
11932/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011933{
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011934 abort();
11935 /*NOTREACHED*/
Victor Stinner9a2329f2016-12-05 17:56:36 +010011936#ifndef __clang__
11937 /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
11938 GCC emits a warning without "return NULL;" (compiler bug?), but Clang
11939 is smarter and emits a warning on the return. */
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011940 Py_FatalError("abort() called from Python code didn't abort!");
11941 return NULL;
Victor Stinner9a2329f2016-12-05 17:56:36 +010011942#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011943}
Fred Drakebec628d1999-12-15 18:31:10 +000011944
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011945#ifdef MS_WINDOWS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011946/* Grab ShellExecute dynamically from shell32 */
11947static int has_ShellExecute = -1;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011948static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
11949 LPCWSTR, INT);
11950static int
11951check_ShellExecute()
11952{
11953 HINSTANCE hShell32;
11954
11955 /* only recheck */
11956 if (-1 == has_ShellExecute) {
11957 Py_BEGIN_ALLOW_THREADS
Victor Stinnera9912152017-10-13 13:46:57 -070011958 /* Security note: this call is not vulnerable to "DLL hijacking".
11959 SHELL32 is part of "KnownDLLs" and so Windows always load
11960 the system SHELL32.DLL, even if there is another SHELL32.DLL
11961 in the DLL search path. */
Steve Dower7d0e0c92015-01-24 08:18:24 -080011962 hShell32 = LoadLibraryW(L"SHELL32");
Steve Dower7d0e0c92015-01-24 08:18:24 -080011963 if (hShell32) {
Steve Dower7d0e0c92015-01-24 08:18:24 -080011964 *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
11965 "ShellExecuteW");
Steve Dowercc16be82016-09-08 10:35:16 -070011966 has_ShellExecute = Py_ShellExecuteW != NULL;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011967 } else {
11968 has_ShellExecute = 0;
11969 }
Tony Roberts4860f012019-02-02 18:16:42 +010011970 Py_END_ALLOW_THREADS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011971 }
11972 return has_ShellExecute;
11973}
11974
11975
Steve Dowercc16be82016-09-08 10:35:16 -070011976/*[clinic input]
11977os.startfile
11978 filepath: path_t
11979 operation: Py_UNICODE = NULL
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +000011980
Steve Dowercc16be82016-09-08 10:35:16 -070011981Start a file with its associated application.
11982
11983When "operation" is not specified or "open", this acts like
11984double-clicking the file in Explorer, or giving the file name as an
11985argument to the DOS "start" command: the file is opened with whatever
11986application (if any) its extension is associated.
11987When another "operation" is given, it specifies what should be done with
11988the file. A typical operation is "print".
11989
11990startfile returns as soon as the associated application is launched.
11991There is no option to wait for the application to close, and no way
11992to retrieve the application's exit status.
11993
11994The filepath is relative to the current directory. If you want to use
11995an absolute path, make sure the first character is not a slash ("/");
11996the underlying Win32 ShellExecute function doesn't work if it is.
11997[clinic start generated code]*/
11998
11999static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +020012000os_startfile_impl(PyObject *module, path_t *filepath,
12001 const Py_UNICODE *operation)
Serhiy Storchaka279f4462019-09-14 12:24:05 +030012002/*[clinic end generated code: output=66dc311c94d50797 input=c940888a5390f039]*/
Steve Dowercc16be82016-09-08 10:35:16 -070012003{
12004 HINSTANCE rc;
Steve Dower7d0e0c92015-01-24 08:18:24 -080012005
12006 if(!check_ShellExecute()) {
12007 /* If the OS doesn't have ShellExecute, return a
12008 NotImplementedError. */
12009 return PyErr_Format(PyExc_NotImplementedError,
12010 "startfile not available on this platform");
12011 }
12012
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012013 if (PySys_Audit("os.startfile", "Ou", filepath->object, operation) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -080012014 return NULL;
12015 }
12016
Victor Stinner8c62be82010-05-06 00:08:46 +000012017 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -070012018 rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
Steve Dower7d0e0c92015-01-24 08:18:24 -080012019 NULL, NULL, SW_SHOWNORMAL);
Victor Stinner8c62be82010-05-06 00:08:46 +000012020 Py_END_ALLOW_THREADS
12021
Victor Stinner8c62be82010-05-06 00:08:46 +000012022 if (rc <= (HINSTANCE)32) {
Steve Dowercc16be82016-09-08 10:35:16 -070012023 win32_error_object("startfile", filepath->object);
Victor Stinnereb5657a2011-09-30 01:44:27 +020012024 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000012025 }
Steve Dowercc16be82016-09-08 10:35:16 -070012026 Py_RETURN_NONE;
Tim Petersf58a7aa2000-09-22 10:05:54 +000012027}
Larry Hastings2f936352014-08-05 14:04:04 +100012028#endif /* MS_WINDOWS */
12029
Fred Drake5ab8eaf1999-12-09 21:13:07 +000012030
Martin v. Löwis438b5342002-12-27 10:16:42 +000012031#ifdef HAVE_GETLOADAVG
Larry Hastings2f936352014-08-05 14:04:04 +100012032/*[clinic input]
12033os.getloadavg
12034
12035Return average recent system load information.
12036
12037Return the number of processes in the system run queue averaged over
12038the last 1, 5, and 15 minutes as a tuple of three floats.
12039Raises OSError if the load average was unobtainable.
12040[clinic start generated code]*/
12041
Larry Hastings2f936352014-08-05 14:04:04 +100012042static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012043os_getloadavg_impl(PyObject *module)
12044/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
Martin v. Löwis438b5342002-12-27 10:16:42 +000012045{
12046 double loadavg[3];
Martin v. Löwis438b5342002-12-27 10:16:42 +000012047 if (getloadavg(loadavg, 3)!=3) {
Stefan Krah0e803b32010-11-26 16:16:47 +000012048 PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
12049 return NULL;
Martin v. Löwis438b5342002-12-27 10:16:42 +000012050 } else
Stefan Krah0e803b32010-11-26 16:16:47 +000012051 return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
Martin v. Löwis438b5342002-12-27 10:16:42 +000012052}
Larry Hastings2f936352014-08-05 14:04:04 +100012053#endif /* HAVE_GETLOADAVG */
Martin v. Löwis438b5342002-12-27 10:16:42 +000012054
Larry Hastings2f936352014-08-05 14:04:04 +100012055
12056/*[clinic input]
12057os.device_encoding
12058 fd: int
12059
12060Return a string describing the encoding of a terminal's file descriptor.
12061
12062The file descriptor must be attached to a terminal.
12063If the device is not a terminal, return None.
12064[clinic start generated code]*/
12065
Larry Hastings2f936352014-08-05 14:04:04 +100012066static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012067os_device_encoding_impl(PyObject *module, int fd)
12068/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012069{
Brett Cannonefb00c02012-02-29 18:31:31 -050012070 return _Py_device_encoding(fd);
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +000012071}
12072
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012073
Larry Hastings2f936352014-08-05 14:04:04 +100012074#ifdef HAVE_SETRESUID
12075/*[clinic input]
12076os.setresuid
12077
12078 ruid: uid_t
12079 euid: uid_t
12080 suid: uid_t
12081 /
12082
12083Set the current process's real, effective, and saved user ids.
12084[clinic start generated code]*/
12085
Larry Hastings2f936352014-08-05 14:04:04 +100012086static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012087os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
12088/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012089{
Victor Stinner8c62be82010-05-06 00:08:46 +000012090 if (setresuid(ruid, euid, suid) < 0)
12091 return posix_error();
12092 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012093}
Larry Hastings2f936352014-08-05 14:04:04 +100012094#endif /* HAVE_SETRESUID */
12095
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012096
12097#ifdef HAVE_SETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100012098/*[clinic input]
12099os.setresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012100
Larry Hastings2f936352014-08-05 14:04:04 +100012101 rgid: gid_t
12102 egid: gid_t
12103 sgid: gid_t
12104 /
12105
12106Set the current process's real, effective, and saved group ids.
12107[clinic start generated code]*/
12108
Larry Hastings2f936352014-08-05 14:04:04 +100012109static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012110os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
12111/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012112{
Victor Stinner8c62be82010-05-06 00:08:46 +000012113 if (setresgid(rgid, egid, sgid) < 0)
12114 return posix_error();
12115 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012116}
Larry Hastings2f936352014-08-05 14:04:04 +100012117#endif /* HAVE_SETRESGID */
12118
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012119
12120#ifdef HAVE_GETRESUID
Larry Hastings2f936352014-08-05 14:04:04 +100012121/*[clinic input]
12122os.getresuid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012123
Larry Hastings2f936352014-08-05 14:04:04 +100012124Return a tuple of the current process's real, effective, and saved user ids.
12125[clinic start generated code]*/
12126
Larry Hastings2f936352014-08-05 14:04:04 +100012127static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012128os_getresuid_impl(PyObject *module)
12129/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012130{
Victor Stinner8c62be82010-05-06 00:08:46 +000012131 uid_t ruid, euid, suid;
Victor Stinner8c62be82010-05-06 00:08:46 +000012132 if (getresuid(&ruid, &euid, &suid) < 0)
12133 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020012134 return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
12135 _PyLong_FromUid(euid),
12136 _PyLong_FromUid(suid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012137}
Larry Hastings2f936352014-08-05 14:04:04 +100012138#endif /* HAVE_GETRESUID */
12139
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012140
12141#ifdef HAVE_GETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100012142/*[clinic input]
12143os.getresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012144
Larry Hastings2f936352014-08-05 14:04:04 +100012145Return a tuple of the current process's real, effective, and saved group ids.
12146[clinic start generated code]*/
12147
Larry Hastings2f936352014-08-05 14:04:04 +100012148static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012149os_getresgid_impl(PyObject *module)
12150/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012151{
12152 gid_t rgid, egid, sgid;
Victor Stinner8c62be82010-05-06 00:08:46 +000012153 if (getresgid(&rgid, &egid, &sgid) < 0)
12154 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020012155 return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
12156 _PyLong_FromGid(egid),
12157 _PyLong_FromGid(sgid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012158}
Larry Hastings2f936352014-08-05 14:04:04 +100012159#endif /* HAVE_GETRESGID */
12160
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012161
Benjamin Peterson9428d532011-09-14 11:45:52 -040012162#ifdef USE_XATTRS
Larry Hastings2f936352014-08-05 14:04:04 +100012163/*[clinic input]
12164os.getxattr
Benjamin Peterson799bd802011-08-31 22:15:17 -040012165
Larry Hastings2f936352014-08-05 14:04:04 +100012166 path: path_t(allow_fd=True)
12167 attribute: path_t
12168 *
12169 follow_symlinks: bool = True
12170
12171Return the value of extended attribute attribute on path.
12172
BNMetricsb9427072018-11-02 15:20:19 +000012173path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012174If follow_symlinks is False, and the last element of the path is a symbolic
12175 link, getxattr will examine the symbolic link itself instead of the file
12176 the link points to.
12177
12178[clinic start generated code]*/
12179
Larry Hastings2f936352014-08-05 14:04:04 +100012180static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012181os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012182 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012183/*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012184{
12185 Py_ssize_t i;
12186 PyObject *buffer = NULL;
12187
12188 if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
12189 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012190
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012191 if (PySys_Audit("os.getxattr", "OO", path->object, attribute->object) < 0) {
12192 return NULL;
12193 }
12194
Larry Hastings9cf065c2012-06-22 16:30:09 -070012195 for (i = 0; ; i++) {
12196 void *ptr;
12197 ssize_t result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012198 static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
Larry Hastings9cf065c2012-06-22 16:30:09 -070012199 Py_ssize_t buffer_size = buffer_sizes[i];
12200 if (!buffer_size) {
Larry Hastings2f936352014-08-05 14:04:04 +100012201 path_error(path);
12202 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012203 }
12204 buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
12205 if (!buffer)
Larry Hastings2f936352014-08-05 14:04:04 +100012206 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012207 ptr = PyBytes_AS_STRING(buffer);
Benjamin Peterson799bd802011-08-31 22:15:17 -040012208
Larry Hastings9cf065c2012-06-22 16:30:09 -070012209 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012210 if (path->fd >= 0)
12211 result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012212 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100012213 result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012214 else
Larry Hastings2f936352014-08-05 14:04:04 +100012215 result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012216 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012217
Larry Hastings9cf065c2012-06-22 16:30:09 -070012218 if (result < 0) {
12219 Py_DECREF(buffer);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012220 if (errno == ERANGE)
12221 continue;
Larry Hastings2f936352014-08-05 14:04:04 +100012222 path_error(path);
12223 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012224 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012225
Larry Hastings9cf065c2012-06-22 16:30:09 -070012226 if (result != buffer_size) {
12227 /* Can only shrink. */
12228 _PyBytes_Resize(&buffer, result);
12229 }
12230 break;
12231 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012232
Larry Hastings9cf065c2012-06-22 16:30:09 -070012233 return buffer;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012234}
12235
Larry Hastings2f936352014-08-05 14:04:04 +100012236
12237/*[clinic input]
12238os.setxattr
12239
12240 path: path_t(allow_fd=True)
12241 attribute: path_t
12242 value: Py_buffer
12243 flags: int = 0
12244 *
12245 follow_symlinks: bool = True
12246
12247Set extended attribute attribute on path to value.
12248
BNMetricsb9427072018-11-02 15:20:19 +000012249path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012250If follow_symlinks is False, and the last element of the path is a symbolic
12251 link, setxattr will modify the symbolic link itself instead of the file
12252 the link points to.
12253
12254[clinic start generated code]*/
12255
Benjamin Peterson799bd802011-08-31 22:15:17 -040012256static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012257os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012258 Py_buffer *value, int flags, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012259/*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
Benjamin Peterson799bd802011-08-31 22:15:17 -040012260{
Larry Hastings2f936352014-08-05 14:04:04 +100012261 ssize_t result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012262
Larry Hastings2f936352014-08-05 14:04:04 +100012263 if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
Benjamin Peterson799bd802011-08-31 22:15:17 -040012264 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012265
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012266 if (PySys_Audit("os.setxattr", "OOy#i", path->object, attribute->object,
12267 value->buf, value->len, flags) < 0) {
12268 return NULL;
12269 }
12270
Benjamin Peterson799bd802011-08-31 22:15:17 -040012271 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012272 if (path->fd > -1)
12273 result = fsetxattr(path->fd, attribute->narrow,
12274 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012275 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100012276 result = setxattr(path->narrow, attribute->narrow,
12277 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012278 else
Larry Hastings2f936352014-08-05 14:04:04 +100012279 result = lsetxattr(path->narrow, attribute->narrow,
12280 value->buf, value->len, flags);
Benjamin Peterson799bd802011-08-31 22:15:17 -040012281 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012282
Larry Hastings9cf065c2012-06-22 16:30:09 -070012283 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100012284 path_error(path);
12285 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012286 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012287
Larry Hastings2f936352014-08-05 14:04:04 +100012288 Py_RETURN_NONE;
12289}
12290
12291
12292/*[clinic input]
12293os.removexattr
12294
12295 path: path_t(allow_fd=True)
12296 attribute: path_t
12297 *
12298 follow_symlinks: bool = True
12299
12300Remove extended attribute attribute on path.
12301
BNMetricsb9427072018-11-02 15:20:19 +000012302path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012303If follow_symlinks is False, and the last element of the path is a symbolic
12304 link, removexattr will modify the symbolic link itself instead of the file
12305 the link points to.
12306
12307[clinic start generated code]*/
12308
Larry Hastings2f936352014-08-05 14:04:04 +100012309static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012310os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012311 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012312/*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012313{
12314 ssize_t result;
12315
12316 if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
12317 return NULL;
12318
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012319 if (PySys_Audit("os.removexattr", "OO", path->object, attribute->object) < 0) {
12320 return NULL;
12321 }
12322
Larry Hastings2f936352014-08-05 14:04:04 +100012323 Py_BEGIN_ALLOW_THREADS;
12324 if (path->fd > -1)
12325 result = fremovexattr(path->fd, attribute->narrow);
12326 else if (follow_symlinks)
12327 result = removexattr(path->narrow, attribute->narrow);
12328 else
12329 result = lremovexattr(path->narrow, attribute->narrow);
12330 Py_END_ALLOW_THREADS;
12331
12332 if (result) {
12333 return path_error(path);
12334 }
12335
12336 Py_RETURN_NONE;
12337}
12338
12339
12340/*[clinic input]
12341os.listxattr
12342
12343 path: path_t(allow_fd=True, nullable=True) = None
12344 *
12345 follow_symlinks: bool = True
12346
12347Return a list of extended attributes on path.
12348
BNMetricsb9427072018-11-02 15:20:19 +000012349path may be either None, a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012350if path is None, listxattr will examine the current directory.
12351If follow_symlinks is False, and the last element of the path is a symbolic
12352 link, listxattr will examine the symbolic link itself instead of the file
12353 the link points to.
12354[clinic start generated code]*/
12355
Larry Hastings2f936352014-08-05 14:04:04 +100012356static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012357os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012358/*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012359{
Larry Hastings9cf065c2012-06-22 16:30:09 -070012360 Py_ssize_t i;
12361 PyObject *result = NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100012362 const char *name;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012363 char *buffer = NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012364
Larry Hastings2f936352014-08-05 14:04:04 +100012365 if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
Larry Hastings9cf065c2012-06-22 16:30:09 -070012366 goto exit;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012367
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012368 if (PySys_Audit("os.listxattr", "(O)",
12369 path->object ? path->object : Py_None) < 0) {
12370 return NULL;
12371 }
12372
Larry Hastings2f936352014-08-05 14:04:04 +100012373 name = path->narrow ? path->narrow : ".";
12374
Larry Hastings9cf065c2012-06-22 16:30:09 -070012375 for (i = 0; ; i++) {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012376 const char *start, *trace, *end;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012377 ssize_t length;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012378 static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
Larry Hastings9cf065c2012-06-22 16:30:09 -070012379 Py_ssize_t buffer_size = buffer_sizes[i];
12380 if (!buffer_size) {
Christian Heimes3b9493b2012-09-23 16:11:15 +020012381 /* ERANGE */
Larry Hastings2f936352014-08-05 14:04:04 +100012382 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012383 break;
12384 }
12385 buffer = PyMem_MALLOC(buffer_size);
12386 if (!buffer) {
12387 PyErr_NoMemory();
12388 break;
12389 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012390
Larry Hastings9cf065c2012-06-22 16:30:09 -070012391 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012392 if (path->fd > -1)
12393 length = flistxattr(path->fd, buffer, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012394 else if (follow_symlinks)
12395 length = listxattr(name, buffer, buffer_size);
12396 else
12397 length = llistxattr(name, buffer, buffer_size);
12398 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012399
Larry Hastings9cf065c2012-06-22 16:30:09 -070012400 if (length < 0) {
Antoine Pitrou7f987392013-05-13 19:46:29 +020012401 if (errno == ERANGE) {
12402 PyMem_FREE(buffer);
Benjamin Petersondedac522013-05-13 19:55:40 -050012403 buffer = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012404 continue;
Antoine Pitrou7f987392013-05-13 19:46:29 +020012405 }
Larry Hastings2f936352014-08-05 14:04:04 +100012406 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012407 break;
12408 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012409
Larry Hastings9cf065c2012-06-22 16:30:09 -070012410 result = PyList_New(0);
12411 if (!result) {
12412 goto exit;
12413 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012414
Larry Hastings9cf065c2012-06-22 16:30:09 -070012415 end = buffer + length;
12416 for (trace = start = buffer; trace != end; trace++) {
12417 if (!*trace) {
12418 int error;
12419 PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
12420 trace - start);
12421 if (!attribute) {
12422 Py_DECREF(result);
12423 result = NULL;
12424 goto exit;
12425 }
12426 error = PyList_Append(result, attribute);
12427 Py_DECREF(attribute);
12428 if (error) {
12429 Py_DECREF(result);
12430 result = NULL;
12431 goto exit;
12432 }
12433 start = trace + 1;
12434 }
12435 }
12436 break;
12437 }
12438exit:
Larry Hastings9cf065c2012-06-22 16:30:09 -070012439 if (buffer)
12440 PyMem_FREE(buffer);
12441 return result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012442}
Benjamin Peterson9428d532011-09-14 11:45:52 -040012443#endif /* USE_XATTRS */
Benjamin Peterson799bd802011-08-31 22:15:17 -040012444
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012445
Larry Hastings2f936352014-08-05 14:04:04 +100012446/*[clinic input]
12447os.urandom
12448
12449 size: Py_ssize_t
12450 /
12451
12452Return a bytes object containing random bytes suitable for cryptographic use.
12453[clinic start generated code]*/
12454
Larry Hastings2f936352014-08-05 14:04:04 +100012455static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012456os_urandom_impl(PyObject *module, Py_ssize_t size)
12457/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012458{
12459 PyObject *bytes;
12460 int result;
12461
Georg Brandl2fb477c2012-02-21 00:33:36 +010012462 if (size < 0)
12463 return PyErr_Format(PyExc_ValueError,
12464 "negative argument not allowed");
Larry Hastings2f936352014-08-05 14:04:04 +100012465 bytes = PyBytes_FromStringAndSize(NULL, size);
12466 if (bytes == NULL)
Georg Brandl2fb477c2012-02-21 00:33:36 +010012467 return NULL;
12468
Victor Stinnere66987e2016-09-06 16:33:52 -070012469 result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
Larry Hastings2f936352014-08-05 14:04:04 +100012470 if (result == -1) {
12471 Py_DECREF(bytes);
Georg Brandl2fb477c2012-02-21 00:33:36 +010012472 return NULL;
12473 }
Larry Hastings2f936352014-08-05 14:04:04 +100012474 return bytes;
Georg Brandl2fb477c2012-02-21 00:33:36 +010012475}
12476
Zackery Spytz43fdbd22019-05-29 13:57:07 -060012477#ifdef HAVE_MEMFD_CREATE
12478/*[clinic input]
12479os.memfd_create
12480
12481 name: FSConverter
12482 flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
12483
12484[clinic start generated code]*/
12485
12486static PyObject *
12487os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
12488/*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
12489{
12490 int fd;
12491 const char *bytes = PyBytes_AS_STRING(name);
12492 Py_BEGIN_ALLOW_THREADS
12493 fd = memfd_create(bytes, flags);
12494 Py_END_ALLOW_THREADS
12495 if (fd == -1) {
12496 return PyErr_SetFromErrno(PyExc_OSError);
12497 }
12498 return PyLong_FromLong(fd);
12499}
12500#endif
12501
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012502/* Terminal size querying */
12503
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012504PyDoc_STRVAR(TerminalSize_docstring,
12505 "A tuple of (columns, lines) for holding terminal window size");
12506
12507static PyStructSequence_Field TerminalSize_fields[] = {
12508 {"columns", "width of the terminal window in characters"},
12509 {"lines", "height of the terminal window in characters"},
12510 {NULL, NULL}
12511};
12512
12513static PyStructSequence_Desc TerminalSize_desc = {
12514 "os.terminal_size",
12515 TerminalSize_docstring,
12516 TerminalSize_fields,
12517 2,
12518};
12519
12520#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
Serhiy Storchaka2b560312020-04-18 19:14:10 +030012521/*[clinic input]
12522os.get_terminal_size
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012523
Serhiy Storchaka2b560312020-04-18 19:14:10 +030012524 fd: int(c_default="fileno(stdout)", py_default="<unrepresentable>") = -1
12525 /
12526
12527Return the size of the terminal window as (columns, lines).
12528
12529The optional argument fd (default standard output) specifies
12530which file descriptor should be queried.
12531
12532If the file descriptor is not connected to a terminal, an OSError
12533is thrown.
12534
12535This function will only be defined if an implementation is
12536available for this system.
12537
12538shutil.get_terminal_size is the high-level function which should
12539normally be used, os.get_terminal_size is the low-level implementation.
12540[clinic start generated code]*/
12541
12542static PyObject *
12543os_get_terminal_size_impl(PyObject *module, int fd)
12544/*[clinic end generated code: output=fbab93acef980508 input=ead5679b82ddb920]*/
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012545{
12546 int columns, lines;
12547 PyObject *termsize;
12548
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012549 /* Under some conditions stdout may not be connected and
12550 * fileno(stdout) may point to an invalid file descriptor. For example
12551 * GUI apps don't have valid standard streams by default.
12552 *
12553 * If this happens, and the optional fd argument is not present,
12554 * the ioctl below will fail returning EBADF. This is what we want.
12555 */
12556
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012557#ifdef TERMSIZE_USE_IOCTL
12558 {
12559 struct winsize w;
12560 if (ioctl(fd, TIOCGWINSZ, &w))
12561 return PyErr_SetFromErrno(PyExc_OSError);
12562 columns = w.ws_col;
12563 lines = w.ws_row;
12564 }
12565#endif /* TERMSIZE_USE_IOCTL */
12566
12567#ifdef TERMSIZE_USE_CONIO
12568 {
12569 DWORD nhandle;
12570 HANDLE handle;
12571 CONSOLE_SCREEN_BUFFER_INFO csbi;
12572 switch (fd) {
12573 case 0: nhandle = STD_INPUT_HANDLE;
12574 break;
12575 case 1: nhandle = STD_OUTPUT_HANDLE;
12576 break;
12577 case 2: nhandle = STD_ERROR_HANDLE;
12578 break;
12579 default:
12580 return PyErr_Format(PyExc_ValueError, "bad file descriptor");
12581 }
12582 handle = GetStdHandle(nhandle);
12583 if (handle == NULL)
12584 return PyErr_Format(PyExc_OSError, "handle cannot be retrieved");
12585 if (handle == INVALID_HANDLE_VALUE)
12586 return PyErr_SetFromWindowsErr(0);
12587
12588 if (!GetConsoleScreenBufferInfo(handle, &csbi))
12589 return PyErr_SetFromWindowsErr(0);
12590
12591 columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
12592 lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
12593 }
12594#endif /* TERMSIZE_USE_CONIO */
12595
Serhiy Storchaka2b560312020-04-18 19:14:10 +030012596 PyObject *TerminalSizeType = get_posix_state(module)->TerminalSizeType;
Eddie Elizondob3966632019-11-05 07:16:14 -080012597 termsize = PyStructSequence_New((PyTypeObject *)TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012598 if (termsize == NULL)
12599 return NULL;
12600 PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
12601 PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
12602 if (PyErr_Occurred()) {
12603 Py_DECREF(termsize);
12604 return NULL;
12605 }
12606 return termsize;
12607}
12608#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
12609
Larry Hastings2f936352014-08-05 14:04:04 +100012610
12611/*[clinic input]
12612os.cpu_count
12613
Charles-François Natali80d62e62015-08-13 20:37:08 +010012614Return the number of CPUs in the system; return None if indeterminable.
12615
12616This number is not equivalent to the number of CPUs the current process can
12617use. The number of usable CPUs can be obtained with
12618``len(os.sched_getaffinity(0))``
Larry Hastings2f936352014-08-05 14:04:04 +100012619[clinic start generated code]*/
12620
Larry Hastings2f936352014-08-05 14:04:04 +100012621static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012622os_cpu_count_impl(PyObject *module)
Serhiy Storchaka2954f832016-07-07 18:20:03 +030012623/*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012624{
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012625 int ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012626#ifdef MS_WINDOWS
Steve Doweraa929272019-09-11 16:15:39 +010012627 ncpu = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012628#elif defined(__hpux)
12629 ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
12630#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
12631 ncpu = sysconf(_SC_NPROCESSORS_ONLN);
pxinwr3405e052020-08-07 13:21:52 +080012632#elif defined(__VXWORKS__)
12633 ncpu = _Py_popcount32(vxCpuEnabledGet());
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012634#elif defined(__DragonFly__) || \
12635 defined(__OpenBSD__) || \
12636 defined(__FreeBSD__) || \
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012637 defined(__NetBSD__) || \
12638 defined(__APPLE__)
Charles-Francois Natali7c4f8da2013-05-20 17:40:32 +020012639 int mib[2];
12640 size_t len = sizeof(ncpu);
12641 mib[0] = CTL_HW;
12642 mib[1] = HW_NCPU;
12643 if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
12644 ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012645#endif
12646 if (ncpu >= 1)
12647 return PyLong_FromLong(ncpu);
12648 else
12649 Py_RETURN_NONE;
12650}
12651
Victor Stinnerdaf45552013-08-28 00:53:59 +020012652
Larry Hastings2f936352014-08-05 14:04:04 +100012653/*[clinic input]
12654os.get_inheritable -> bool
12655
12656 fd: int
12657 /
12658
12659Get the close-on-exe flag of the specified file descriptor.
12660[clinic start generated code]*/
12661
Larry Hastings2f936352014-08-05 14:04:04 +100012662static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012663os_get_inheritable_impl(PyObject *module, int fd)
12664/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012665{
Steve Dower8fc89802015-04-12 00:26:27 -040012666 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -040012667 _Py_BEGIN_SUPPRESS_IPH
12668 return_value = _Py_get_inheritable(fd);
12669 _Py_END_SUPPRESS_IPH
12670 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +100012671}
12672
12673
12674/*[clinic input]
12675os.set_inheritable
12676 fd: int
12677 inheritable: int
12678 /
12679
12680Set the inheritable flag of the specified file descriptor.
12681[clinic start generated code]*/
12682
Larry Hastings2f936352014-08-05 14:04:04 +100012683static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012684os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
12685/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
Victor Stinnerdaf45552013-08-28 00:53:59 +020012686{
Steve Dower8fc89802015-04-12 00:26:27 -040012687 int result;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012688
Steve Dower8fc89802015-04-12 00:26:27 -040012689 _Py_BEGIN_SUPPRESS_IPH
12690 result = _Py_set_inheritable(fd, inheritable, NULL);
12691 _Py_END_SUPPRESS_IPH
12692 if (result < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +020012693 return NULL;
12694 Py_RETURN_NONE;
12695}
12696
12697
12698#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100012699/*[clinic input]
12700os.get_handle_inheritable -> bool
Benjamin Petersonca470632016-09-06 13:47:26 -070012701 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012702 /
Victor Stinnerdaf45552013-08-28 00:53:59 +020012703
Larry Hastings2f936352014-08-05 14:04:04 +100012704Get the close-on-exe flag of the specified file descriptor.
12705[clinic start generated code]*/
12706
Larry Hastings2f936352014-08-05 14:04:04 +100012707static int
Benjamin Petersonca470632016-09-06 13:47:26 -070012708os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
Victor Stinner581139c2016-09-06 15:54:20 -070012709/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012710{
12711 DWORD flags;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012712
12713 if (!GetHandleInformation((HANDLE)handle, &flags)) {
12714 PyErr_SetFromWindowsErr(0);
Larry Hastings2f936352014-08-05 14:04:04 +100012715 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012716 }
12717
Larry Hastings2f936352014-08-05 14:04:04 +100012718 return flags & HANDLE_FLAG_INHERIT;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012719}
12720
Victor Stinnerdaf45552013-08-28 00:53:59 +020012721
Larry Hastings2f936352014-08-05 14:04:04 +100012722/*[clinic input]
12723os.set_handle_inheritable
Benjamin Petersonca470632016-09-06 13:47:26 -070012724 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012725 inheritable: bool
12726 /
12727
12728Set the inheritable flag of the specified handle.
12729[clinic start generated code]*/
12730
Larry Hastings2f936352014-08-05 14:04:04 +100012731static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -070012732os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
Larry Hastings89964c42015-04-14 18:07:59 -040012733 int inheritable)
Victor Stinner581139c2016-09-06 15:54:20 -070012734/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012735{
12736 DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012737 if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
12738 PyErr_SetFromWindowsErr(0);
12739 return NULL;
12740 }
12741 Py_RETURN_NONE;
12742}
Larry Hastings2f936352014-08-05 14:04:04 +100012743#endif /* MS_WINDOWS */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012744
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012745#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012746/*[clinic input]
12747os.get_blocking -> bool
12748 fd: int
12749 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012750
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012751Get the blocking mode of the file descriptor.
12752
12753Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
12754[clinic start generated code]*/
12755
12756static int
12757os_get_blocking_impl(PyObject *module, int fd)
12758/*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012759{
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012760 int blocking;
12761
Steve Dower8fc89802015-04-12 00:26:27 -040012762 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012763 blocking = _Py_get_blocking(fd);
Steve Dower8fc89802015-04-12 00:26:27 -040012764 _Py_END_SUPPRESS_IPH
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012765 return blocking;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012766}
12767
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012768/*[clinic input]
12769os.set_blocking
12770 fd: int
12771 blocking: bool(accept={int})
12772 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012773
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012774Set the blocking mode of the specified file descriptor.
12775
12776Set the O_NONBLOCK flag if blocking is False,
12777clear the O_NONBLOCK flag otherwise.
12778[clinic start generated code]*/
12779
12780static PyObject *
12781os_set_blocking_impl(PyObject *module, int fd, int blocking)
12782/*[clinic end generated code: output=384eb43aa0762a9d input=bf5c8efdc5860ff3]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012783{
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012784 int result;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012785
Steve Dower8fc89802015-04-12 00:26:27 -040012786 _Py_BEGIN_SUPPRESS_IPH
12787 result = _Py_set_blocking(fd, blocking);
12788 _Py_END_SUPPRESS_IPH
12789 if (result < 0)
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012790 return NULL;
12791 Py_RETURN_NONE;
12792}
12793#endif /* !MS_WINDOWS */
12794
12795
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012796/*[clinic input]
Eddie Elizondob3966632019-11-05 07:16:14 -080012797class os.DirEntry "DirEntry *" "DirEntryType"
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012798[clinic start generated code]*/
Eddie Elizondob3966632019-11-05 07:16:14 -080012799/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3c18c7a448247980]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012800
12801typedef struct {
12802 PyObject_HEAD
12803 PyObject *name;
12804 PyObject *path;
12805 PyObject *stat;
12806 PyObject *lstat;
12807#ifdef MS_WINDOWS
12808 struct _Py_stat_struct win32_lstat;
Victor Stinner0f6d7332017-03-09 17:34:28 +010012809 uint64_t win32_file_index;
Victor Stinner6036e442015-03-08 01:58:04 +010012810 int got_file_index;
12811#else /* POSIX */
Victor Stinner35a97c02015-03-08 02:59:09 +010012812#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012813 unsigned char d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012814#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012815 ino_t d_ino;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012816 int dir_fd;
Victor Stinner6036e442015-03-08 01:58:04 +010012817#endif
12818} DirEntry;
12819
Eddie Elizondob3966632019-11-05 07:16:14 -080012820static PyObject *
12821_disabled_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
12822{
12823 PyErr_Format(PyExc_TypeError,
12824 "cannot create '%.100s' instances", _PyType_Name(type));
12825 return NULL;
12826}
12827
Victor Stinner6036e442015-03-08 01:58:04 +010012828static void
12829DirEntry_dealloc(DirEntry *entry)
12830{
Eddie Elizondob3966632019-11-05 07:16:14 -080012831 PyTypeObject *tp = Py_TYPE(entry);
Victor Stinner6036e442015-03-08 01:58:04 +010012832 Py_XDECREF(entry->name);
12833 Py_XDECREF(entry->path);
12834 Py_XDECREF(entry->stat);
12835 Py_XDECREF(entry->lstat);
Eddie Elizondob3966632019-11-05 07:16:14 -080012836 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
12837 free_func(entry);
12838 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010012839}
12840
12841/* Forward reference */
12842static int
Victor Stinner97f33c32020-05-14 18:05:58 +020012843DirEntry_test_mode(PyTypeObject *defining_class, DirEntry *self,
12844 int follow_symlinks, unsigned short mode_bits);
Victor Stinner6036e442015-03-08 01:58:04 +010012845
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012846/*[clinic input]
12847os.DirEntry.is_symlink -> bool
Victor Stinner97f33c32020-05-14 18:05:58 +020012848 defining_class: defining_class
12849 /
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012850
12851Return True if the entry is a symbolic link; cached per entry.
12852[clinic start generated code]*/
12853
Victor Stinner6036e442015-03-08 01:58:04 +010012854static int
Victor Stinner97f33c32020-05-14 18:05:58 +020012855os_DirEntry_is_symlink_impl(DirEntry *self, PyTypeObject *defining_class)
12856/*[clinic end generated code: output=293096d589b6d47c input=e9acc5ee4d511113]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012857{
12858#ifdef MS_WINDOWS
12859 return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
Victor Stinner35a97c02015-03-08 02:59:09 +010012860#elif defined(HAVE_DIRENT_D_TYPE)
12861 /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010012862 if (self->d_type != DT_UNKNOWN)
12863 return self->d_type == DT_LNK;
12864 else
Victor Stinner97f33c32020-05-14 18:05:58 +020012865 return DirEntry_test_mode(defining_class, self, 0, S_IFLNK);
Victor Stinner35a97c02015-03-08 02:59:09 +010012866#else
12867 /* POSIX without d_type */
Victor Stinner97f33c32020-05-14 18:05:58 +020012868 return DirEntry_test_mode(defining_class, self, 0, S_IFLNK);
Victor Stinner6036e442015-03-08 01:58:04 +010012869#endif
12870}
12871
12872static PyObject *
Victor Stinner97f33c32020-05-14 18:05:58 +020012873DirEntry_fetch_stat(PyObject *module, DirEntry *self, int follow_symlinks)
Victor Stinner6036e442015-03-08 01:58:04 +010012874{
12875 int result;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012876 STRUCT_STAT st;
12877 PyObject *ub;
Victor Stinner6036e442015-03-08 01:58:04 +010012878
12879#ifdef MS_WINDOWS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012880 if (!PyUnicode_FSDecoder(self->path, &ub))
12881 return NULL;
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030012882#if USE_UNICODE_WCHAR_CACHE
12883_Py_COMP_DIAG_PUSH
12884_Py_COMP_DIAG_IGNORE_DEPR_DECLS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012885 const wchar_t *path = PyUnicode_AsUnicode(ub);
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030012886_Py_COMP_DIAG_POP
12887#else /* USE_UNICODE_WCHAR_CACHE */
12888 wchar_t *path = PyUnicode_AsWideCharString(ub, NULL);
12889 Py_DECREF(ub);
12890#endif /* USE_UNICODE_WCHAR_CACHE */
Victor Stinner6036e442015-03-08 01:58:04 +010012891#else /* POSIX */
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012892 if (!PyUnicode_FSConverter(self->path, &ub))
12893 return NULL;
12894 const char *path = PyBytes_AS_STRING(ub);
12895 if (self->dir_fd != DEFAULT_DIR_FD) {
12896#ifdef HAVE_FSTATAT
12897 result = fstatat(self->dir_fd, path, &st,
12898 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
12899#else
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030012900 Py_DECREF(ub);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012901 PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
12902 return NULL;
12903#endif /* HAVE_FSTATAT */
12904 }
12905 else
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012906#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012907 {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012908 if (follow_symlinks)
12909 result = STAT(path, &st);
12910 else
12911 result = LSTAT(path, &st);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012912 }
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030012913#if defined(MS_WINDOWS) && !USE_UNICODE_WCHAR_CACHE
12914 PyMem_Free(path);
12915#else /* USE_UNICODE_WCHAR_CACHE */
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012916 Py_DECREF(ub);
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030012917#endif /* USE_UNICODE_WCHAR_CACHE */
Victor Stinner6036e442015-03-08 01:58:04 +010012918
12919 if (result != 0)
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012920 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012921
Victor Stinner97f33c32020-05-14 18:05:58 +020012922 return _pystat_fromstructstat(module, &st);
Victor Stinner6036e442015-03-08 01:58:04 +010012923}
12924
12925static PyObject *
Victor Stinner97f33c32020-05-14 18:05:58 +020012926DirEntry_get_lstat(PyTypeObject *defining_class, DirEntry *self)
Victor Stinner6036e442015-03-08 01:58:04 +010012927{
12928 if (!self->lstat) {
Victor Stinner97f33c32020-05-14 18:05:58 +020012929 PyObject *module = PyType_GetModule(defining_class);
Victor Stinner6036e442015-03-08 01:58:04 +010012930#ifdef MS_WINDOWS
Victor Stinner97f33c32020-05-14 18:05:58 +020012931 self->lstat = _pystat_fromstructstat(module, &self->win32_lstat);
Victor Stinner6036e442015-03-08 01:58:04 +010012932#else /* POSIX */
Victor Stinner97f33c32020-05-14 18:05:58 +020012933 self->lstat = DirEntry_fetch_stat(module, self, 0);
Victor Stinner6036e442015-03-08 01:58:04 +010012934#endif
12935 }
12936 Py_XINCREF(self->lstat);
12937 return self->lstat;
12938}
12939
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012940/*[clinic input]
12941os.DirEntry.stat
Victor Stinner97f33c32020-05-14 18:05:58 +020012942 defining_class: defining_class
12943 /
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012944 *
12945 follow_symlinks: bool = True
12946
12947Return stat_result object for the entry; cached per entry.
12948[clinic start generated code]*/
12949
Victor Stinner6036e442015-03-08 01:58:04 +010012950static PyObject *
Victor Stinner97f33c32020-05-14 18:05:58 +020012951os_DirEntry_stat_impl(DirEntry *self, PyTypeObject *defining_class,
12952 int follow_symlinks)
12953/*[clinic end generated code: output=23f803e19c3e780e input=e816273c4e67ee98]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012954{
Victor Stinner97f33c32020-05-14 18:05:58 +020012955 if (!follow_symlinks) {
12956 return DirEntry_get_lstat(defining_class, self);
12957 }
Victor Stinner6036e442015-03-08 01:58:04 +010012958
12959 if (!self->stat) {
Victor Stinner97f33c32020-05-14 18:05:58 +020012960 int result = os_DirEntry_is_symlink_impl(self, defining_class);
12961 if (result == -1) {
Victor Stinner6036e442015-03-08 01:58:04 +010012962 return NULL;
Victor Stinner97f33c32020-05-14 18:05:58 +020012963 }
12964 if (result) {
12965 PyObject *module = PyType_GetModule(defining_class);
12966 self->stat = DirEntry_fetch_stat(module, self, 1);
12967 }
12968 else {
12969 self->stat = DirEntry_get_lstat(defining_class, self);
12970 }
Victor Stinner6036e442015-03-08 01:58:04 +010012971 }
12972
12973 Py_XINCREF(self->stat);
12974 return self->stat;
12975}
12976
Victor Stinner6036e442015-03-08 01:58:04 +010012977/* Set exception and return -1 on error, 0 for False, 1 for True */
12978static int
Victor Stinner97f33c32020-05-14 18:05:58 +020012979DirEntry_test_mode(PyTypeObject *defining_class, DirEntry *self,
12980 int follow_symlinks, unsigned short mode_bits)
Victor Stinner6036e442015-03-08 01:58:04 +010012981{
12982 PyObject *stat = NULL;
12983 PyObject *st_mode = NULL;
12984 long mode;
12985 int result;
Victor Stinner35a97c02015-03-08 02:59:09 +010012986#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012987 int is_symlink;
12988 int need_stat;
Victor Stinner35a97c02015-03-08 02:59:09 +010012989#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012990#ifdef MS_WINDOWS
12991 unsigned long dir_bits;
12992#endif
12993
12994#ifdef MS_WINDOWS
12995 is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
12996 need_stat = follow_symlinks && is_symlink;
Victor Stinner35a97c02015-03-08 02:59:09 +010012997#elif defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012998 is_symlink = self->d_type == DT_LNK;
12999 need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
13000#endif
13001
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 if (need_stat) {
Victor Stinner35a97c02015-03-08 02:59:09 +010013004#endif
Victor Stinner97f33c32020-05-14 18:05:58 +020013005 stat = os_DirEntry_stat_impl(self, defining_class, follow_symlinks);
Victor Stinner6036e442015-03-08 01:58:04 +010013006 if (!stat) {
13007 if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
13008 /* If file doesn't exist (anymore), then return False
13009 (i.e., say it's not a file/directory) */
13010 PyErr_Clear();
13011 return 0;
13012 }
13013 goto error;
13014 }
Victor Stinner97f33c32020-05-14 18:05:58 +020013015 _posixstate* state = get_posix_state(PyType_GetModule(defining_class));
13016 st_mode = PyObject_GetAttr(stat, state->st_mode);
Victor Stinner6036e442015-03-08 01:58:04 +010013017 if (!st_mode)
13018 goto error;
13019
13020 mode = PyLong_AsLong(st_mode);
13021 if (mode == -1 && PyErr_Occurred())
13022 goto error;
13023 Py_CLEAR(st_mode);
13024 Py_CLEAR(stat);
13025 result = (mode & S_IFMT) == mode_bits;
Victor Stinner35a97c02015-03-08 02:59:09 +010013026#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010013027 }
13028 else if (is_symlink) {
13029 assert(mode_bits != S_IFLNK);
13030 result = 0;
13031 }
13032 else {
13033 assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
13034#ifdef MS_WINDOWS
13035 dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
13036 if (mode_bits == S_IFDIR)
13037 result = dir_bits != 0;
13038 else
13039 result = dir_bits == 0;
13040#else /* POSIX */
13041 if (mode_bits == S_IFDIR)
13042 result = self->d_type == DT_DIR;
13043 else
13044 result = self->d_type == DT_REG;
13045#endif
13046 }
Victor Stinner35a97c02015-03-08 02:59:09 +010013047#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013048
13049 return result;
13050
13051error:
13052 Py_XDECREF(st_mode);
13053 Py_XDECREF(stat);
13054 return -1;
13055}
13056
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013057/*[clinic input]
13058os.DirEntry.is_dir -> bool
Victor Stinner97f33c32020-05-14 18:05:58 +020013059 defining_class: defining_class
13060 /
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013061 *
13062 follow_symlinks: bool = True
Victor Stinner6036e442015-03-08 01:58:04 +010013063
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013064Return True if the entry is a directory; cached per entry.
13065[clinic start generated code]*/
13066
13067static int
Victor Stinner97f33c32020-05-14 18:05:58 +020013068os_DirEntry_is_dir_impl(DirEntry *self, PyTypeObject *defining_class,
13069 int follow_symlinks)
13070/*[clinic end generated code: output=0cd453b9c0987fdf input=1a4ffd6dec9920cb]*/
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013071{
Victor Stinner97f33c32020-05-14 18:05:58 +020013072 return DirEntry_test_mode(defining_class, self, follow_symlinks, S_IFDIR);
Victor Stinner6036e442015-03-08 01:58:04 +010013073}
13074
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013075/*[clinic input]
13076os.DirEntry.is_file -> bool
Victor Stinner97f33c32020-05-14 18:05:58 +020013077 defining_class: defining_class
13078 /
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013079 *
13080 follow_symlinks: bool = True
13081
13082Return True if the entry is a file; cached per entry.
13083[clinic start generated code]*/
13084
13085static int
Victor Stinner97f33c32020-05-14 18:05:58 +020013086os_DirEntry_is_file_impl(DirEntry *self, PyTypeObject *defining_class,
13087 int follow_symlinks)
13088/*[clinic end generated code: output=f7c277ab5ba80908 input=0a64c5a12e802e3b]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013089{
Victor Stinner97f33c32020-05-14 18:05:58 +020013090 return DirEntry_test_mode(defining_class, self, follow_symlinks, S_IFREG);
Victor Stinner6036e442015-03-08 01:58:04 +010013091}
13092
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013093/*[clinic input]
13094os.DirEntry.inode
Victor Stinner6036e442015-03-08 01:58:04 +010013095
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013096Return inode of the entry; cached per entry.
13097[clinic start generated code]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013098
13099static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013100os_DirEntry_inode_impl(DirEntry *self)
13101/*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013102{
13103#ifdef MS_WINDOWS
13104 if (!self->got_file_index) {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030013105 PyObject *unicode;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030013106 STRUCT_STAT stat;
13107 int result;
Victor Stinner6036e442015-03-08 01:58:04 +010013108
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030013109 if (!PyUnicode_FSDecoder(self->path, &unicode))
Victor Stinner6036e442015-03-08 01:58:04 +010013110 return NULL;
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030013111#if USE_UNICODE_WCHAR_CACHE
13112_Py_COMP_DIAG_PUSH
13113_Py_COMP_DIAG_IGNORE_DEPR_DECLS
13114 const wchar_t *path = PyUnicode_AsUnicode(unicode);
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030013115 result = LSTAT(path, &stat);
13116 Py_DECREF(unicode);
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030013117_Py_COMP_DIAG_POP
13118#else /* USE_UNICODE_WCHAR_CACHE */
13119 wchar_t *path = PyUnicode_AsWideCharString(unicode, NULL);
13120 Py_DECREF(unicode);
13121 result = LSTAT(path, &stat);
13122 PyMem_Free(path);
13123#endif /* USE_UNICODE_WCHAR_CACHE */
Victor Stinner6036e442015-03-08 01:58:04 +010013124
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030013125 if (result != 0)
13126 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013127
13128 self->win32_file_index = stat.st_ino;
13129 self->got_file_index = 1;
13130 }
Victor Stinner0f6d7332017-03-09 17:34:28 +010013131 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->win32_file_index));
13132 return PyLong_FromUnsignedLongLong(self->win32_file_index);
Victor Stinner6036e442015-03-08 01:58:04 +010013133#else /* POSIX */
xdegaye50e86032017-05-22 11:15:08 +020013134 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->d_ino));
13135 return PyLong_FromUnsignedLongLong(self->d_ino);
Victor Stinner6036e442015-03-08 01:58:04 +010013136#endif
13137}
13138
13139static PyObject *
13140DirEntry_repr(DirEntry *self)
13141{
13142 return PyUnicode_FromFormat("<DirEntry %R>", self->name);
13143}
13144
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013145/*[clinic input]
13146os.DirEntry.__fspath__
13147
13148Returns the path for the entry.
13149[clinic start generated code]*/
13150
Brett Cannon96881cd2016-06-10 14:37:21 -070013151static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013152os_DirEntry___fspath___impl(DirEntry *self)
13153/*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
Brett Cannon96881cd2016-06-10 14:37:21 -070013154{
13155 Py_INCREF(self->path);
13156 return self->path;
13157}
13158
Victor Stinner6036e442015-03-08 01:58:04 +010013159static PyMemberDef DirEntry_members[] = {
13160 {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
13161 "the entry's base filename, relative to scandir() \"path\" argument"},
13162 {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
13163 "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
13164 {NULL}
13165};
13166
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013167#include "clinic/posixmodule.c.h"
13168
Victor Stinner6036e442015-03-08 01:58:04 +010013169static PyMethodDef DirEntry_methods[] = {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013170 OS_DIRENTRY_IS_DIR_METHODDEF
13171 OS_DIRENTRY_IS_FILE_METHODDEF
13172 OS_DIRENTRY_IS_SYMLINK_METHODDEF
13173 OS_DIRENTRY_STAT_METHODDEF
13174 OS_DIRENTRY_INODE_METHODDEF
13175 OS_DIRENTRY___FSPATH___METHODDEF
Batuhan Taşkayaf9dd51e2020-04-08 00:37:19 +030013176 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
13177 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Victor Stinner6036e442015-03-08 01:58:04 +010013178 {NULL}
13179};
13180
Eddie Elizondob3966632019-11-05 07:16:14 -080013181static PyType_Slot DirEntryType_slots[] = {
13182 {Py_tp_new, _disabled_new},
13183 {Py_tp_dealloc, DirEntry_dealloc},
13184 {Py_tp_repr, DirEntry_repr},
13185 {Py_tp_methods, DirEntry_methods},
13186 {Py_tp_members, DirEntry_members},
13187 {0, 0},
Victor Stinner6036e442015-03-08 01:58:04 +010013188};
13189
Eddie Elizondob3966632019-11-05 07:16:14 -080013190static PyType_Spec DirEntryType_spec = {
13191 MODNAME ".DirEntry",
13192 sizeof(DirEntry),
13193 0,
13194 Py_TPFLAGS_DEFAULT,
13195 DirEntryType_slots
13196};
13197
13198
Victor Stinner6036e442015-03-08 01:58:04 +010013199#ifdef MS_WINDOWS
13200
13201static wchar_t *
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030013202join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
Victor Stinner6036e442015-03-08 01:58:04 +010013203{
13204 Py_ssize_t path_len;
13205 Py_ssize_t size;
13206 wchar_t *result;
13207 wchar_t ch;
13208
13209 if (!path_wide) { /* Default arg: "." */
13210 path_wide = L".";
13211 path_len = 1;
13212 }
13213 else {
13214 path_len = wcslen(path_wide);
13215 }
13216
13217 /* The +1's are for the path separator and the NUL */
13218 size = path_len + 1 + wcslen(filename) + 1;
13219 result = PyMem_New(wchar_t, size);
13220 if (!result) {
13221 PyErr_NoMemory();
13222 return NULL;
13223 }
13224 wcscpy(result, path_wide);
13225 if (path_len > 0) {
13226 ch = result[path_len - 1];
13227 if (ch != SEP && ch != ALTSEP && ch != L':')
13228 result[path_len++] = SEP;
13229 wcscpy(result + path_len, filename);
13230 }
13231 return result;
13232}
13233
13234static PyObject *
Victor Stinner1c2fa782020-05-10 11:05:29 +020013235DirEntry_from_find_data(PyObject *module, path_t *path, WIN32_FIND_DATAW *dataW)
Victor Stinner6036e442015-03-08 01:58:04 +010013236{
13237 DirEntry *entry;
13238 BY_HANDLE_FILE_INFORMATION file_info;
13239 ULONG reparse_tag;
13240 wchar_t *joined_path;
13241
Victor Stinner1c2fa782020-05-10 11:05:29 +020013242 PyObject *DirEntryType = get_posix_state(module)->DirEntryType;
Eddie Elizondob3966632019-11-05 07:16:14 -080013243 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010013244 if (!entry)
13245 return NULL;
13246 entry->name = NULL;
13247 entry->path = NULL;
13248 entry->stat = NULL;
13249 entry->lstat = NULL;
13250 entry->got_file_index = 0;
13251
13252 entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
13253 if (!entry->name)
13254 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070013255 if (path->narrow) {
13256 Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
13257 if (!entry->name)
13258 goto error;
13259 }
Victor Stinner6036e442015-03-08 01:58:04 +010013260
13261 joined_path = join_path_filenameW(path->wide, dataW->cFileName);
13262 if (!joined_path)
13263 goto error;
13264
13265 entry->path = PyUnicode_FromWideChar(joined_path, -1);
13266 PyMem_Free(joined_path);
13267 if (!entry->path)
13268 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070013269 if (path->narrow) {
13270 Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
13271 if (!entry->path)
13272 goto error;
13273 }
Victor Stinner6036e442015-03-08 01:58:04 +010013274
Steve Dowercc16be82016-09-08 10:35:16 -070013275 find_data_to_file_info(dataW, &file_info, &reparse_tag);
Victor Stinner6036e442015-03-08 01:58:04 +010013276 _Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
13277
13278 return (PyObject *)entry;
13279
13280error:
13281 Py_DECREF(entry);
13282 return NULL;
13283}
13284
13285#else /* POSIX */
13286
13287static char *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020013288join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
Victor Stinner6036e442015-03-08 01:58:04 +010013289{
13290 Py_ssize_t path_len;
13291 Py_ssize_t size;
13292 char *result;
13293
13294 if (!path_narrow) { /* Default arg: "." */
13295 path_narrow = ".";
13296 path_len = 1;
13297 }
13298 else {
13299 path_len = strlen(path_narrow);
13300 }
13301
13302 if (filename_len == -1)
13303 filename_len = strlen(filename);
13304
13305 /* The +1's are for the path separator and the NUL */
13306 size = path_len + 1 + filename_len + 1;
13307 result = PyMem_New(char, size);
13308 if (!result) {
13309 PyErr_NoMemory();
13310 return NULL;
13311 }
13312 strcpy(result, path_narrow);
13313 if (path_len > 0 && result[path_len - 1] != '/')
13314 result[path_len++] = '/';
13315 strcpy(result + path_len, filename);
13316 return result;
13317}
13318
13319static PyObject *
Victor Stinner1c2fa782020-05-10 11:05:29 +020013320DirEntry_from_posix_info(PyObject *module, path_t *path, const char *name,
13321 Py_ssize_t name_len, ino_t d_ino
Victor Stinner35a97c02015-03-08 02:59:09 +010013322#ifdef HAVE_DIRENT_D_TYPE
13323 , unsigned char d_type
13324#endif
13325 )
Victor Stinner6036e442015-03-08 01:58:04 +010013326{
13327 DirEntry *entry;
13328 char *joined_path;
13329
Victor Stinner1c2fa782020-05-10 11:05:29 +020013330 PyObject *DirEntryType = get_posix_state(module)->DirEntryType;
Eddie Elizondob3966632019-11-05 07:16:14 -080013331 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010013332 if (!entry)
13333 return NULL;
13334 entry->name = NULL;
13335 entry->path = NULL;
13336 entry->stat = NULL;
13337 entry->lstat = NULL;
13338
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013339 if (path->fd != -1) {
13340 entry->dir_fd = path->fd;
13341 joined_path = NULL;
13342 }
13343 else {
13344 entry->dir_fd = DEFAULT_DIR_FD;
13345 joined_path = join_path_filename(path->narrow, name, name_len);
13346 if (!joined_path)
13347 goto error;
13348 }
Victor Stinner6036e442015-03-08 01:58:04 +010013349
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +030013350 if (!path->narrow || !PyObject_CheckBuffer(path->object)) {
Victor Stinner6036e442015-03-08 01:58:04 +010013351 entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013352 if (joined_path)
13353 entry->path = PyUnicode_DecodeFSDefault(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013354 }
13355 else {
13356 entry->name = PyBytes_FromStringAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013357 if (joined_path)
13358 entry->path = PyBytes_FromString(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013359 }
13360 PyMem_Free(joined_path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013361 if (!entry->name)
13362 goto error;
13363
13364 if (path->fd != -1) {
13365 entry->path = entry->name;
13366 Py_INCREF(entry->path);
13367 }
13368 else if (!entry->path)
Victor Stinner6036e442015-03-08 01:58:04 +010013369 goto error;
13370
Victor Stinner35a97c02015-03-08 02:59:09 +010013371#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010013372 entry->d_type = d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010013373#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013374 entry->d_ino = d_ino;
13375
13376 return (PyObject *)entry;
13377
13378error:
13379 Py_XDECREF(entry);
13380 return NULL;
13381}
13382
13383#endif
13384
13385
13386typedef struct {
13387 PyObject_HEAD
13388 path_t path;
13389#ifdef MS_WINDOWS
13390 HANDLE handle;
13391 WIN32_FIND_DATAW file_data;
13392 int first_time;
13393#else /* POSIX */
13394 DIR *dirp;
13395#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013396#ifdef HAVE_FDOPENDIR
13397 int fd;
13398#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013399} ScandirIterator;
13400
13401#ifdef MS_WINDOWS
13402
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013403static int
13404ScandirIterator_is_closed(ScandirIterator *iterator)
13405{
13406 return iterator->handle == INVALID_HANDLE_VALUE;
13407}
13408
Victor Stinner6036e442015-03-08 01:58:04 +010013409static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013410ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013411{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013412 HANDLE handle = iterator->handle;
13413
13414 if (handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013415 return;
13416
Victor Stinner6036e442015-03-08 01:58:04 +010013417 iterator->handle = INVALID_HANDLE_VALUE;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013418 Py_BEGIN_ALLOW_THREADS
13419 FindClose(handle);
13420 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013421}
13422
13423static PyObject *
13424ScandirIterator_iternext(ScandirIterator *iterator)
13425{
13426 WIN32_FIND_DATAW *file_data = &iterator->file_data;
13427 BOOL success;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013428 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013429
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013430 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013431 if (iterator->handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013432 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013433
13434 while (1) {
13435 if (!iterator->first_time) {
13436 Py_BEGIN_ALLOW_THREADS
13437 success = FindNextFileW(iterator->handle, file_data);
13438 Py_END_ALLOW_THREADS
13439 if (!success) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013440 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013441 if (GetLastError() != ERROR_NO_MORE_FILES)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013442 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013443 break;
13444 }
13445 }
13446 iterator->first_time = 0;
13447
13448 /* Skip over . and .. */
13449 if (wcscmp(file_data->cFileName, L".") != 0 &&
Victor Stinner1c2fa782020-05-10 11:05:29 +020013450 wcscmp(file_data->cFileName, L"..") != 0)
13451 {
13452 PyObject *module = PyType_GetModule(Py_TYPE(iterator));
13453 entry = DirEntry_from_find_data(module, &iterator->path, file_data);
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013454 if (!entry)
13455 break;
13456 return entry;
13457 }
Victor Stinner6036e442015-03-08 01:58:04 +010013458
13459 /* Loop till we get a non-dot directory or finish iterating */
13460 }
13461
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013462 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013463 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013464 return NULL;
13465}
13466
13467#else /* POSIX */
13468
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013469static int
13470ScandirIterator_is_closed(ScandirIterator *iterator)
13471{
13472 return !iterator->dirp;
13473}
13474
Victor Stinner6036e442015-03-08 01:58:04 +010013475static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013476ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013477{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013478 DIR *dirp = iterator->dirp;
13479
13480 if (!dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013481 return;
13482
Victor Stinner6036e442015-03-08 01:58:04 +010013483 iterator->dirp = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013484 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013485#ifdef HAVE_FDOPENDIR
13486 if (iterator->path.fd != -1)
13487 rewinddir(dirp);
13488#endif
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013489 closedir(dirp);
13490 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013491 return;
13492}
13493
13494static PyObject *
13495ScandirIterator_iternext(ScandirIterator *iterator)
13496{
13497 struct dirent *direntp;
13498 Py_ssize_t name_len;
13499 int is_dot;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013500 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013501
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013502 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013503 if (!iterator->dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013504 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013505
13506 while (1) {
13507 errno = 0;
13508 Py_BEGIN_ALLOW_THREADS
13509 direntp = readdir(iterator->dirp);
13510 Py_END_ALLOW_THREADS
13511
13512 if (!direntp) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013513 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013514 if (errno != 0)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013515 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013516 break;
13517 }
13518
13519 /* Skip over . and .. */
13520 name_len = NAMLEN(direntp);
13521 is_dot = direntp->d_name[0] == '.' &&
13522 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
13523 if (!is_dot) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020013524 PyObject *module = PyType_GetModule(Py_TYPE(iterator));
13525 entry = DirEntry_from_posix_info(module,
13526 &iterator->path, direntp->d_name,
13527 name_len, direntp->d_ino
Victor Stinner35a97c02015-03-08 02:59:09 +010013528#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner1c2fa782020-05-10 11:05:29 +020013529 , direntp->d_type
Victor Stinner35a97c02015-03-08 02:59:09 +010013530#endif
13531 );
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013532 if (!entry)
13533 break;
13534 return entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013535 }
13536
13537 /* Loop till we get a non-dot directory or finish iterating */
13538 }
13539
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013540 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013541 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013542 return NULL;
13543}
13544
13545#endif
13546
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013547static PyObject *
13548ScandirIterator_close(ScandirIterator *self, PyObject *args)
13549{
13550 ScandirIterator_closedir(self);
13551 Py_RETURN_NONE;
13552}
13553
13554static PyObject *
13555ScandirIterator_enter(PyObject *self, PyObject *args)
13556{
13557 Py_INCREF(self);
13558 return self;
13559}
13560
13561static PyObject *
13562ScandirIterator_exit(ScandirIterator *self, PyObject *args)
13563{
13564 ScandirIterator_closedir(self);
13565 Py_RETURN_NONE;
13566}
13567
Victor Stinner6036e442015-03-08 01:58:04 +010013568static void
Victor Stinner7bfa4092016-03-23 00:43:54 +010013569ScandirIterator_finalize(ScandirIterator *iterator)
13570{
13571 PyObject *error_type, *error_value, *error_traceback;
13572
13573 /* Save the current exception, if any. */
13574 PyErr_Fetch(&error_type, &error_value, &error_traceback);
13575
13576 if (!ScandirIterator_is_closed(iterator)) {
13577 ScandirIterator_closedir(iterator);
13578
13579 if (PyErr_ResourceWarning((PyObject *)iterator, 1,
13580 "unclosed scandir iterator %R", iterator)) {
13581 /* Spurious errors can appear at shutdown */
13582 if (PyErr_ExceptionMatches(PyExc_Warning)) {
13583 PyErr_WriteUnraisable((PyObject *) iterator);
13584 }
13585 }
13586 }
13587
Victor Stinner7bfa4092016-03-23 00:43:54 +010013588 path_cleanup(&iterator->path);
13589
13590 /* Restore the saved exception. */
13591 PyErr_Restore(error_type, error_value, error_traceback);
13592}
13593
13594static void
Victor Stinner6036e442015-03-08 01:58:04 +010013595ScandirIterator_dealloc(ScandirIterator *iterator)
13596{
Eddie Elizondob3966632019-11-05 07:16:14 -080013597 PyTypeObject *tp = Py_TYPE(iterator);
Victor Stinner7bfa4092016-03-23 00:43:54 +010013598 if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
13599 return;
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013600
Eddie Elizondob3966632019-11-05 07:16:14 -080013601 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
13602 free_func(iterator);
13603 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010013604}
13605
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013606static PyMethodDef ScandirIterator_methods[] = {
13607 {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
13608 {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
13609 {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
13610 {NULL}
13611};
13612
Eddie Elizondob3966632019-11-05 07:16:14 -080013613static PyType_Slot ScandirIteratorType_slots[] = {
13614 {Py_tp_new, _disabled_new},
13615 {Py_tp_dealloc, ScandirIterator_dealloc},
13616 {Py_tp_finalize, ScandirIterator_finalize},
13617 {Py_tp_iter, PyObject_SelfIter},
13618 {Py_tp_iternext, ScandirIterator_iternext},
13619 {Py_tp_methods, ScandirIterator_methods},
13620 {0, 0},
13621};
13622
13623static PyType_Spec ScandirIteratorType_spec = {
13624 MODNAME ".ScandirIterator",
13625 sizeof(ScandirIterator),
13626 0,
Victor Stinner97f33c32020-05-14 18:05:58 +020013627 // bpo-40549: Py_TPFLAGS_BASETYPE should not be used, since
13628 // PyType_GetModule(Py_TYPE(self)) doesn't work on a subclass instance.
Eddie Elizondob3966632019-11-05 07:16:14 -080013629 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE,
13630 ScandirIteratorType_slots
Victor Stinner6036e442015-03-08 01:58:04 +010013631};
13632
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013633/*[clinic input]
13634os.scandir
13635
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013636 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013637
13638Return an iterator of DirEntry objects for given path.
13639
BNMetricsb9427072018-11-02 15:20:19 +000013640path can be specified as either str, bytes, or a path-like object. If path
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013641is bytes, the names of yielded DirEntry objects will also be bytes; in
13642all other circumstances they will be str.
13643
13644If path is None, uses the path='.'.
13645[clinic start generated code]*/
13646
Victor Stinner6036e442015-03-08 01:58:04 +010013647static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013648os_scandir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +000013649/*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013650{
13651 ScandirIterator *iterator;
Victor Stinner6036e442015-03-08 01:58:04 +010013652#ifdef MS_WINDOWS
13653 wchar_t *path_strW;
13654#else
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013655 const char *path_str;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013656#ifdef HAVE_FDOPENDIR
13657 int fd = -1;
13658#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013659#endif
13660
Steve Dower60419a72019-06-24 08:42:54 -070013661 if (PySys_Audit("os.scandir", "O",
13662 path->object ? path->object : Py_None) < 0) {
13663 return NULL;
13664 }
13665
Hai Shif707d942020-03-16 21:15:01 +080013666 PyObject *ScandirIteratorType = get_posix_state(module)->ScandirIteratorType;
Eddie Elizondob3966632019-11-05 07:16:14 -080013667 iterator = PyObject_New(ScandirIterator, (PyTypeObject *)ScandirIteratorType);
Victor Stinner6036e442015-03-08 01:58:04 +010013668 if (!iterator)
13669 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013670
13671#ifdef MS_WINDOWS
13672 iterator->handle = INVALID_HANDLE_VALUE;
13673#else
13674 iterator->dirp = NULL;
13675#endif
13676
Serhiy Storchaka095ef732017-02-09 20:05:51 +020013677 /* Move the ownership to iterator->path */
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030013678 memcpy(&iterator->path, path, sizeof(path_t));
13679 memset(path, 0, sizeof(path_t));
Victor Stinner6036e442015-03-08 01:58:04 +010013680
13681#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +010013682 iterator->first_time = 1;
13683
13684 path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
13685 if (!path_strW)
13686 goto error;
13687
13688 Py_BEGIN_ALLOW_THREADS
13689 iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
13690 Py_END_ALLOW_THREADS
13691
13692 PyMem_Free(path_strW);
13693
13694 if (iterator->handle == INVALID_HANDLE_VALUE) {
13695 path_error(&iterator->path);
13696 goto error;
13697 }
13698#else /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010013699 errno = 0;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013700#ifdef HAVE_FDOPENDIR
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030013701 if (iterator->path.fd != -1) {
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013702 /* closedir() closes the FD, so we duplicate it */
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +030013703 fd = _Py_dup(iterator->path.fd);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013704 if (fd == -1)
13705 goto error;
13706
13707 Py_BEGIN_ALLOW_THREADS
13708 iterator->dirp = fdopendir(fd);
13709 Py_END_ALLOW_THREADS
13710 }
13711 else
13712#endif
13713 {
13714 if (iterator->path.narrow)
13715 path_str = iterator->path.narrow;
13716 else
13717 path_str = ".";
13718
13719 Py_BEGIN_ALLOW_THREADS
13720 iterator->dirp = opendir(path_str);
13721 Py_END_ALLOW_THREADS
13722 }
Victor Stinner6036e442015-03-08 01:58:04 +010013723
13724 if (!iterator->dirp) {
13725 path_error(&iterator->path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013726#ifdef HAVE_FDOPENDIR
13727 if (fd != -1) {
13728 Py_BEGIN_ALLOW_THREADS
13729 close(fd);
13730 Py_END_ALLOW_THREADS
13731 }
13732#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013733 goto error;
13734 }
13735#endif
13736
13737 return (PyObject *)iterator;
13738
13739error:
13740 Py_DECREF(iterator);
13741 return NULL;
13742}
13743
Ethan Furman410ef8e2016-06-04 12:06:26 -070013744/*
13745 Return the file system path representation of the object.
13746
13747 If the object is str or bytes, then allow it to pass through with
13748 an incremented refcount. If the object defines __fspath__(), then
13749 return the result of that method. All other types raise a TypeError.
13750*/
13751PyObject *
13752PyOS_FSPath(PyObject *path)
13753{
Brett Cannon3f9183b2016-08-26 14:44:48 -070013754 /* For error message reasons, this function is manually inlined in
13755 path_converter(). */
Ethan Furman410ef8e2016-06-04 12:06:26 -070013756 PyObject *func = NULL;
13757 PyObject *path_repr = NULL;
13758
13759 if (PyUnicode_Check(path) || PyBytes_Check(path)) {
13760 Py_INCREF(path);
13761 return path;
13762 }
13763
13764 func = _PyObject_LookupSpecial(path, &PyId___fspath__);
13765 if (NULL == func) {
13766 return PyErr_Format(PyExc_TypeError,
13767 "expected str, bytes or os.PathLike object, "
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013768 "not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -080013769 _PyType_Name(Py_TYPE(path)));
Ethan Furman410ef8e2016-06-04 12:06:26 -070013770 }
13771
Victor Stinnerf17c3de2016-12-06 18:46:19 +010013772 path_repr = _PyObject_CallNoArg(func);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013773 Py_DECREF(func);
Brett Cannon044283a2016-07-15 10:41:49 -070013774 if (NULL == path_repr) {
13775 return NULL;
13776 }
13777
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013778 if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
13779 PyErr_Format(PyExc_TypeError,
13780 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -080013781 "not %.200s", _PyType_Name(Py_TYPE(path)),
13782 _PyType_Name(Py_TYPE(path_repr)));
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013783 Py_DECREF(path_repr);
13784 return NULL;
13785 }
13786
Ethan Furman410ef8e2016-06-04 12:06:26 -070013787 return path_repr;
13788}
13789
13790/*[clinic input]
13791os.fspath
13792
13793 path: object
13794
13795Return the file system path representation of the object.
13796
Brett Cannonb4f43e92016-06-09 14:32:08 -070013797If the object is str or bytes, then allow it to pass through as-is. If the
13798object defines __fspath__(), then return the result of that method. All other
13799types raise a TypeError.
Ethan Furman410ef8e2016-06-04 12:06:26 -070013800[clinic start generated code]*/
13801
13802static PyObject *
Serhiy Storchaka2954f832016-07-07 18:20:03 +030013803os_fspath_impl(PyObject *module, PyObject *path)
13804/*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
Ethan Furman410ef8e2016-06-04 12:06:26 -070013805{
13806 return PyOS_FSPath(path);
13807}
Victor Stinner6036e442015-03-08 01:58:04 +010013808
Victor Stinner9b1f4742016-09-06 16:18:52 -070013809#ifdef HAVE_GETRANDOM_SYSCALL
13810/*[clinic input]
13811os.getrandom
13812
13813 size: Py_ssize_t
13814 flags: int=0
13815
13816Obtain a series of random bytes.
13817[clinic start generated code]*/
13818
13819static PyObject *
13820os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
13821/*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
13822{
Victor Stinner9b1f4742016-09-06 16:18:52 -070013823 PyObject *bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013824 Py_ssize_t n;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013825
13826 if (size < 0) {
13827 errno = EINVAL;
13828 return posix_error();
13829 }
13830
Victor Stinnerec2319c2016-09-20 23:00:59 +020013831 bytes = PyBytes_FromStringAndSize(NULL, size);
13832 if (bytes == NULL) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013833 PyErr_NoMemory();
13834 return NULL;
13835 }
13836
13837 while (1) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013838 n = syscall(SYS_getrandom,
13839 PyBytes_AS_STRING(bytes),
13840 PyBytes_GET_SIZE(bytes),
13841 flags);
Victor Stinner9b1f4742016-09-06 16:18:52 -070013842 if (n < 0 && errno == EINTR) {
13843 if (PyErr_CheckSignals() < 0) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013844 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013845 }
Victor Stinnerec2319c2016-09-20 23:00:59 +020013846
13847 /* getrandom() was interrupted by a signal: retry */
Victor Stinner9b1f4742016-09-06 16:18:52 -070013848 continue;
13849 }
13850 break;
13851 }
13852
13853 if (n < 0) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013854 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerec2319c2016-09-20 23:00:59 +020013855 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013856 }
13857
Victor Stinnerec2319c2016-09-20 23:00:59 +020013858 if (n != size) {
13859 _PyBytes_Resize(&bytes, n);
13860 }
Victor Stinner9b1f4742016-09-06 16:18:52 -070013861
13862 return bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013863
13864error:
13865 Py_DECREF(bytes);
13866 return NULL;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013867}
13868#endif /* HAVE_GETRANDOM_SYSCALL */
13869
Steve Dower2438cdf2019-03-29 16:37:16 -070013870#ifdef MS_WINDOWS
13871/* bpo-36085: Helper functions for managing DLL search directories
13872 * on win32
13873 */
13874
13875typedef DLL_DIRECTORY_COOKIE (WINAPI *PAddDllDirectory)(PCWSTR newDirectory);
13876typedef BOOL (WINAPI *PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE cookie);
13877
13878/*[clinic input]
13879os._add_dll_directory
13880
13881 path: path_t
13882
13883Add a path to the DLL search path.
13884
13885This search path is used when resolving dependencies for imported
13886extension modules (the module itself is resolved through sys.path),
13887and also by ctypes.
13888
13889Returns an opaque value that may be passed to os.remove_dll_directory
13890to remove this directory from the search path.
13891[clinic start generated code]*/
13892
13893static PyObject *
13894os__add_dll_directory_impl(PyObject *module, path_t *path)
13895/*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
13896{
13897 HMODULE hKernel32;
13898 PAddDllDirectory AddDllDirectory;
13899 DLL_DIRECTORY_COOKIE cookie = 0;
13900 DWORD err = 0;
13901
Saiyang Gou7514f4f2020-02-12 23:47:42 -080013902 if (PySys_Audit("os.add_dll_directory", "(O)", path->object) < 0) {
13903 return NULL;
13904 }
13905
Steve Dower2438cdf2019-03-29 16:37:16 -070013906 /* For Windows 7, we have to load this. As this will be a fairly
13907 infrequent operation, just do it each time. Kernel32 is always
13908 loaded. */
13909 Py_BEGIN_ALLOW_THREADS
13910 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13911 !(AddDllDirectory = (PAddDllDirectory)GetProcAddress(
13912 hKernel32, "AddDllDirectory")) ||
13913 !(cookie = (*AddDllDirectory)(path->wide))) {
13914 err = GetLastError();
13915 }
13916 Py_END_ALLOW_THREADS
13917
13918 if (err) {
13919 return win32_error_object_err("add_dll_directory",
13920 path->object, err);
13921 }
13922
13923 return PyCapsule_New(cookie, "DLL directory cookie", NULL);
13924}
13925
13926/*[clinic input]
13927os._remove_dll_directory
13928
13929 cookie: object
13930
13931Removes a path from the DLL search path.
13932
13933The parameter is an opaque value that was returned from
13934os.add_dll_directory. You can only remove directories that you added
13935yourself.
13936[clinic start generated code]*/
13937
13938static PyObject *
13939os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
13940/*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
13941{
13942 HMODULE hKernel32;
13943 PRemoveDllDirectory RemoveDllDirectory;
13944 DLL_DIRECTORY_COOKIE cookieValue;
13945 DWORD err = 0;
13946
13947 if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
13948 PyErr_SetString(PyExc_TypeError,
13949 "Provided cookie was not returned from os.add_dll_directory");
13950 return NULL;
13951 }
13952
13953 cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
13954 cookie, "DLL directory cookie");
13955
13956 /* For Windows 7, we have to load this. As this will be a fairly
13957 infrequent operation, just do it each time. Kernel32 is always
13958 loaded. */
13959 Py_BEGIN_ALLOW_THREADS
13960 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13961 !(RemoveDllDirectory = (PRemoveDllDirectory)GetProcAddress(
13962 hKernel32, "RemoveDllDirectory")) ||
13963 !(*RemoveDllDirectory)(cookieValue)) {
13964 err = GetLastError();
13965 }
13966 Py_END_ALLOW_THREADS
13967
13968 if (err) {
13969 return win32_error_object_err("remove_dll_directory",
13970 NULL, err);
13971 }
13972
13973 if (PyCapsule_SetName(cookie, NULL)) {
13974 return NULL;
13975 }
13976
13977 Py_RETURN_NONE;
13978}
13979
13980#endif
Larry Hastings31826802013-10-19 00:09:25 -070013981
Victor Stinner65a796e2020-04-01 18:49:29 +020013982
13983/* Only check if WIFEXITED is available: expect that it comes
13984 with WEXITSTATUS, WIFSIGNALED, etc.
13985
13986 os.waitstatus_to_exitcode() is implemented in C and not in Python, so
13987 subprocess can safely call it during late Python finalization without
13988 risking that used os attributes were set to None by _PyImport_Cleanup(). */
13989#if defined(WIFEXITED) || defined(MS_WINDOWS)
13990/*[clinic input]
13991os.waitstatus_to_exitcode
13992
Victor Stinner9bee32b2020-04-22 16:30:35 +020013993 status as status_obj: object
Victor Stinner65a796e2020-04-01 18:49:29 +020013994
13995Convert a wait status to an exit code.
13996
13997On Unix:
13998
13999* If WIFEXITED(status) is true, return WEXITSTATUS(status).
14000* If WIFSIGNALED(status) is true, return -WTERMSIG(status).
14001* Otherwise, raise a ValueError.
14002
14003On Windows, return status shifted right by 8 bits.
14004
14005On Unix, if the process is being traced or if waitpid() was called with
14006WUNTRACED option, the caller must first check if WIFSTOPPED(status) is true.
14007This function must not be called if WIFSTOPPED(status) is true.
14008[clinic start generated code]*/
14009
14010static PyObject *
Victor Stinner9bee32b2020-04-22 16:30:35 +020014011os_waitstatus_to_exitcode_impl(PyObject *module, PyObject *status_obj)
14012/*[clinic end generated code: output=db50b1b0ba3c7153 input=7fe2d7fdaea3db42]*/
Victor Stinner65a796e2020-04-01 18:49:29 +020014013{
14014#ifndef MS_WINDOWS
Victor Stinner9bee32b2020-04-22 16:30:35 +020014015 int status = _PyLong_AsInt(status_obj);
14016 if (status == -1 && PyErr_Occurred()) {
14017 return NULL;
14018 }
14019
Victor Stinner65a796e2020-04-01 18:49:29 +020014020 WAIT_TYPE wait_status;
14021 WAIT_STATUS_INT(wait_status) = status;
14022 int exitcode;
14023 if (WIFEXITED(wait_status)) {
14024 exitcode = WEXITSTATUS(wait_status);
14025 /* Sanity check to provide warranty on the function behavior.
14026 It should not occur in practice */
14027 if (exitcode < 0) {
14028 PyErr_Format(PyExc_ValueError, "invalid WEXITSTATUS: %i", exitcode);
14029 return NULL;
14030 }
14031 }
14032 else if (WIFSIGNALED(wait_status)) {
14033 int signum = WTERMSIG(wait_status);
14034 /* Sanity check to provide warranty on the function behavior.
14035 It should not occurs in practice */
14036 if (signum <= 0) {
14037 PyErr_Format(PyExc_ValueError, "invalid WTERMSIG: %i", signum);
14038 return NULL;
14039 }
14040 exitcode = -signum;
14041 } else if (WIFSTOPPED(wait_status)) {
14042 /* Status only received if the process is being traced
14043 or if waitpid() was called with WUNTRACED option. */
14044 int signum = WSTOPSIG(wait_status);
14045 PyErr_Format(PyExc_ValueError,
14046 "process stopped by delivery of signal %i",
14047 signum);
14048 return NULL;
14049 }
14050 else {
14051 PyErr_Format(PyExc_ValueError, "invalid wait status: %i", status);
14052 return NULL;
14053 }
14054 return PyLong_FromLong(exitcode);
14055#else
14056 /* Windows implementation: see os.waitpid() implementation
14057 which uses _cwait(). */
Victor Stinner9bee32b2020-04-22 16:30:35 +020014058 unsigned long long status = PyLong_AsUnsignedLongLong(status_obj);
14059 if (status == (unsigned long long)-1 && PyErr_Occurred()) {
14060 return NULL;
14061 }
14062
14063 unsigned long long exitcode = (status >> 8);
14064 /* ExitProcess() accepts an UINT type:
14065 reject exit code which doesn't fit in an UINT */
14066 if (exitcode > UINT_MAX) {
14067 PyErr_Format(PyExc_ValueError, "invalid exit code: %llu", exitcode);
14068 return NULL;
14069 }
14070 return PyLong_FromUnsignedLong((unsigned long)exitcode);
Victor Stinner65a796e2020-04-01 18:49:29 +020014071#endif
14072}
14073#endif
14074
14075
Fred Drake5ab8eaf1999-12-09 21:13:07 +000014076static PyMethodDef posix_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -070014077
14078 OS_STAT_METHODDEF
14079 OS_ACCESS_METHODDEF
14080 OS_TTYNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014081 OS_CHDIR_METHODDEF
14082 OS_CHFLAGS_METHODDEF
14083 OS_CHMOD_METHODDEF
14084 OS_FCHMOD_METHODDEF
14085 OS_LCHMOD_METHODDEF
14086 OS_CHOWN_METHODDEF
14087 OS_FCHOWN_METHODDEF
14088 OS_LCHOWN_METHODDEF
14089 OS_LCHFLAGS_METHODDEF
14090 OS_CHROOT_METHODDEF
14091 OS_CTERMID_METHODDEF
14092 OS_GETCWD_METHODDEF
14093 OS_GETCWDB_METHODDEF
14094 OS_LINK_METHODDEF
14095 OS_LISTDIR_METHODDEF
14096 OS_LSTAT_METHODDEF
14097 OS_MKDIR_METHODDEF
14098 OS_NICE_METHODDEF
14099 OS_GETPRIORITY_METHODDEF
14100 OS_SETPRIORITY_METHODDEF
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000014101 OS_POSIX_SPAWN_METHODDEF
Joannah Nanjekye92b83222019-01-16 16:29:26 +030014102 OS_POSIX_SPAWNP_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030014103 OS_READLINK_METHODDEF
Pablo Galindoaac4d032019-05-31 19:39:47 +010014104 OS_COPY_FILE_RANGE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014105 OS_RENAME_METHODDEF
14106 OS_REPLACE_METHODDEF
14107 OS_RMDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014108 OS_SYMLINK_METHODDEF
14109 OS_SYSTEM_METHODDEF
14110 OS_UMASK_METHODDEF
14111 OS_UNAME_METHODDEF
14112 OS_UNLINK_METHODDEF
14113 OS_REMOVE_METHODDEF
14114 OS_UTIME_METHODDEF
14115 OS_TIMES_METHODDEF
14116 OS__EXIT_METHODDEF
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020014117 OS__FCOPYFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014118 OS_EXECV_METHODDEF
14119 OS_EXECVE_METHODDEF
14120 OS_SPAWNV_METHODDEF
14121 OS_SPAWNVE_METHODDEF
14122 OS_FORK1_METHODDEF
14123 OS_FORK_METHODDEF
Antoine Pitrou346cbd32017-05-27 17:50:54 +020014124 OS_REGISTER_AT_FORK_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014125 OS_SCHED_GET_PRIORITY_MAX_METHODDEF
14126 OS_SCHED_GET_PRIORITY_MIN_METHODDEF
14127 OS_SCHED_GETPARAM_METHODDEF
14128 OS_SCHED_GETSCHEDULER_METHODDEF
14129 OS_SCHED_RR_GET_INTERVAL_METHODDEF
14130 OS_SCHED_SETPARAM_METHODDEF
14131 OS_SCHED_SETSCHEDULER_METHODDEF
14132 OS_SCHED_YIELD_METHODDEF
14133 OS_SCHED_SETAFFINITY_METHODDEF
14134 OS_SCHED_GETAFFINITY_METHODDEF
14135 OS_OPENPTY_METHODDEF
14136 OS_FORKPTY_METHODDEF
14137 OS_GETEGID_METHODDEF
14138 OS_GETEUID_METHODDEF
14139 OS_GETGID_METHODDEF
Serhiy Storchaka2b560312020-04-18 19:14:10 +030014140 OS_GETGROUPLIST_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014141 OS_GETGROUPS_METHODDEF
14142 OS_GETPID_METHODDEF
14143 OS_GETPGRP_METHODDEF
14144 OS_GETPPID_METHODDEF
14145 OS_GETUID_METHODDEF
14146 OS_GETLOGIN_METHODDEF
14147 OS_KILL_METHODDEF
14148 OS_KILLPG_METHODDEF
14149 OS_PLOCK_METHODDEF
Steve Dowercc16be82016-09-08 10:35:16 -070014150 OS_STARTFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014151 OS_SETUID_METHODDEF
14152 OS_SETEUID_METHODDEF
14153 OS_SETREUID_METHODDEF
14154 OS_SETGID_METHODDEF
14155 OS_SETEGID_METHODDEF
14156 OS_SETREGID_METHODDEF
14157 OS_SETGROUPS_METHODDEF
Serhiy Storchaka2b560312020-04-18 19:14:10 +030014158 OS_INITGROUPS_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014159 OS_GETPGID_METHODDEF
14160 OS_SETPGRP_METHODDEF
14161 OS_WAIT_METHODDEF
14162 OS_WAIT3_METHODDEF
14163 OS_WAIT4_METHODDEF
14164 OS_WAITID_METHODDEF
14165 OS_WAITPID_METHODDEF
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -080014166 OS_PIDFD_OPEN_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014167 OS_GETSID_METHODDEF
14168 OS_SETSID_METHODDEF
14169 OS_SETPGID_METHODDEF
14170 OS_TCGETPGRP_METHODDEF
14171 OS_TCSETPGRP_METHODDEF
14172 OS_OPEN_METHODDEF
14173 OS_CLOSE_METHODDEF
14174 OS_CLOSERANGE_METHODDEF
14175 OS_DEVICE_ENCODING_METHODDEF
14176 OS_DUP_METHODDEF
14177 OS_DUP2_METHODDEF
14178 OS_LOCKF_METHODDEF
14179 OS_LSEEK_METHODDEF
14180 OS_READ_METHODDEF
14181 OS_READV_METHODDEF
14182 OS_PREAD_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000014183 OS_PREADV_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014184 OS_WRITE_METHODDEF
14185 OS_WRITEV_METHODDEF
14186 OS_PWRITE_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000014187 OS_PWRITEV_METHODDEF
Serhiy Storchaka2b560312020-04-18 19:14:10 +030014188 OS_SENDFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014189 OS_FSTAT_METHODDEF
14190 OS_ISATTY_METHODDEF
14191 OS_PIPE_METHODDEF
14192 OS_PIPE2_METHODDEF
14193 OS_MKFIFO_METHODDEF
14194 OS_MKNOD_METHODDEF
14195 OS_MAJOR_METHODDEF
14196 OS_MINOR_METHODDEF
14197 OS_MAKEDEV_METHODDEF
14198 OS_FTRUNCATE_METHODDEF
14199 OS_TRUNCATE_METHODDEF
14200 OS_POSIX_FALLOCATE_METHODDEF
14201 OS_POSIX_FADVISE_METHODDEF
14202 OS_PUTENV_METHODDEF
14203 OS_UNSETENV_METHODDEF
14204 OS_STRERROR_METHODDEF
14205 OS_FCHDIR_METHODDEF
14206 OS_FSYNC_METHODDEF
14207 OS_SYNC_METHODDEF
14208 OS_FDATASYNC_METHODDEF
14209 OS_WCOREDUMP_METHODDEF
14210 OS_WIFCONTINUED_METHODDEF
14211 OS_WIFSTOPPED_METHODDEF
14212 OS_WIFSIGNALED_METHODDEF
14213 OS_WIFEXITED_METHODDEF
14214 OS_WEXITSTATUS_METHODDEF
14215 OS_WTERMSIG_METHODDEF
14216 OS_WSTOPSIG_METHODDEF
14217 OS_FSTATVFS_METHODDEF
14218 OS_STATVFS_METHODDEF
14219 OS_CONFSTR_METHODDEF
14220 OS_SYSCONF_METHODDEF
14221 OS_FPATHCONF_METHODDEF
14222 OS_PATHCONF_METHODDEF
14223 OS_ABORT_METHODDEF
Serhiy Storchakaf0b50152015-05-13 00:52:39 +030014224 OS__GETFULLPATHNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014225 OS__GETDISKUSAGE_METHODDEF
14226 OS__GETFINALPATHNAME_METHODDEF
14227 OS__GETVOLUMEPATHNAME_METHODDEF
14228 OS_GETLOADAVG_METHODDEF
14229 OS_URANDOM_METHODDEF
14230 OS_SETRESUID_METHODDEF
14231 OS_SETRESGID_METHODDEF
14232 OS_GETRESUID_METHODDEF
14233 OS_GETRESGID_METHODDEF
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000014234
Larry Hastings2f936352014-08-05 14:04:04 +100014235 OS_GETXATTR_METHODDEF
14236 OS_SETXATTR_METHODDEF
14237 OS_REMOVEXATTR_METHODDEF
14238 OS_LISTXATTR_METHODDEF
14239
Serhiy Storchaka2b560312020-04-18 19:14:10 +030014240 OS_GET_TERMINAL_SIZE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014241 OS_CPU_COUNT_METHODDEF
14242 OS_GET_INHERITABLE_METHODDEF
14243 OS_SET_INHERITABLE_METHODDEF
14244 OS_GET_HANDLE_INHERITABLE_METHODDEF
14245 OS_SET_HANDLE_INHERITABLE_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030014246 OS_GET_BLOCKING_METHODDEF
14247 OS_SET_BLOCKING_METHODDEF
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020014248 OS_SCANDIR_METHODDEF
Ethan Furman410ef8e2016-06-04 12:06:26 -070014249 OS_FSPATH_METHODDEF
Victor Stinner9b1f4742016-09-06 16:18:52 -070014250 OS_GETRANDOM_METHODDEF
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014251 OS_MEMFD_CREATE_METHODDEF
Steve Dower2438cdf2019-03-29 16:37:16 -070014252 OS__ADD_DLL_DIRECTORY_METHODDEF
14253 OS__REMOVE_DLL_DIRECTORY_METHODDEF
Victor Stinner65a796e2020-04-01 18:49:29 +020014254 OS_WAITSTATUS_TO_EXITCODE_METHODDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000014255 {NULL, NULL} /* Sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000014256};
14257
Barry Warsaw4a342091996-12-19 23:50:02 +000014258static int
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014259all_ins(PyObject *m)
Barry Warsaw4a342091996-12-19 23:50:02 +000014260{
Guido van Rossum94f6f721999-01-06 18:42:14 +000014261#ifdef F_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014262 if (PyModule_AddIntMacro(m, F_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014263#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000014264#ifdef R_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014265 if (PyModule_AddIntMacro(m, R_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014266#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000014267#ifdef W_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014268 if (PyModule_AddIntMacro(m, W_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014269#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000014270#ifdef X_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014271 if (PyModule_AddIntMacro(m, X_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014272#endif
Fred Drakec9680921999-12-13 16:37:25 +000014273#ifdef NGROUPS_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014274 if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
Fred Drakec9680921999-12-13 16:37:25 +000014275#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000014276#ifdef TMP_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014277 if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
Fred Drake5ab8eaf1999-12-09 21:13:07 +000014278#endif
Fred Drake106c1a02002-04-23 15:58:02 +000014279#ifdef WCONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014280 if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000014281#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000014282#ifdef WNOHANG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014283 if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014284#endif
Fred Drake106c1a02002-04-23 15:58:02 +000014285#ifdef WUNTRACED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014286 if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000014287#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000014288#ifdef O_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014289 if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014290#endif
14291#ifdef O_WRONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014292 if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014293#endif
14294#ifdef O_RDWR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014295 if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014296#endif
14297#ifdef O_NDELAY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014298 if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014299#endif
14300#ifdef O_NONBLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014301 if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014302#endif
14303#ifdef O_APPEND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014304 if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014305#endif
14306#ifdef O_DSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014307 if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014308#endif
14309#ifdef O_RSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014310 if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014311#endif
14312#ifdef O_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014313 if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014314#endif
14315#ifdef O_NOCTTY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014316 if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014317#endif
14318#ifdef O_CREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014319 if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014320#endif
14321#ifdef O_EXCL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014322 if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014323#endif
14324#ifdef O_TRUNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014325 if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014326#endif
Guido van Rossum98d9d091997-08-08 21:48:51 +000014327#ifdef O_BINARY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014328 if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000014329#endif
14330#ifdef O_TEXT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014331 if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000014332#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020014333#ifdef O_XATTR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014334 if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020014335#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014336#ifdef O_LARGEFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014337 if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014338#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020014339#ifndef __GNU__
Skip Montanaro5ff14922005-05-16 02:42:22 +000014340#ifdef O_SHLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014341 if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000014342#endif
14343#ifdef O_EXLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014344 if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000014345#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020014346#endif
Jesus Ceacf381202012-04-24 20:44:40 +020014347#ifdef O_EXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014348 if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020014349#endif
14350#ifdef O_SEARCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014351 if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020014352#endif
Benjamin Peterson3b965a22013-03-13 10:27:41 -050014353#ifdef O_PATH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014354 if (PyModule_AddIntMacro(m, O_PATH)) return -1;
Benjamin Peterson3b965a22013-03-13 10:27:41 -050014355#endif
Jesus Ceacf381202012-04-24 20:44:40 +020014356#ifdef O_TTY_INIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014357 if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020014358#endif
Christian Heimes177b3f92013-08-16 14:35:09 +020014359#ifdef O_TMPFILE
14360 if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
14361#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014362#ifdef PRIO_PROCESS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014363 if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014364#endif
14365#ifdef PRIO_PGRP
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014366 if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014367#endif
14368#ifdef PRIO_USER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014369 if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014370#endif
Charles-François Natali1e045b12011-05-22 20:42:32 +020014371#ifdef O_CLOEXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014372 if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
Charles-François Natali1e045b12011-05-22 20:42:32 +020014373#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020014374#ifdef O_ACCMODE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014375 if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020014376#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014377
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014378
Jesus Cea94363612012-06-22 18:32:07 +020014379#ifdef SEEK_HOLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014380 if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020014381#endif
14382#ifdef SEEK_DATA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014383 if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020014384#endif
14385
Tim Peters5aa91602002-01-30 05:46:57 +000014386/* MS Windows */
14387#ifdef O_NOINHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000014388 /* Don't inherit in child processes. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014389 if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014390#endif
14391#ifdef _O_SHORT_LIVED
Victor Stinner8c62be82010-05-06 00:08:46 +000014392 /* Optimize for short life (keep in memory). */
14393 /* MS forgot to define this one with a non-underscore form too. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014394 if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014395#endif
14396#ifdef O_TEMPORARY
Victor Stinner8c62be82010-05-06 00:08:46 +000014397 /* Automatically delete when last handle is closed. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014398 if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014399#endif
14400#ifdef O_RANDOM
Victor Stinner8c62be82010-05-06 00:08:46 +000014401 /* Optimize for random access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014402 if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014403#endif
14404#ifdef O_SEQUENTIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000014405 /* Optimize for sequential access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014406 if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014407#endif
14408
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014409/* GNU extensions. */
Alexandre Vassalottibee32532008-05-16 18:15:12 +000014410#ifdef O_ASYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000014411 /* Send a SIGIO signal whenever input or output
14412 becomes available on file descriptor */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014413 if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
Alexandre Vassalottibee32532008-05-16 18:15:12 +000014414#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014415#ifdef O_DIRECT
Victor Stinner8c62be82010-05-06 00:08:46 +000014416 /* Direct disk access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014417 if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014418#endif
14419#ifdef O_DIRECTORY
Victor Stinner8c62be82010-05-06 00:08:46 +000014420 /* Must be a directory. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014421 if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014422#endif
14423#ifdef O_NOFOLLOW
Victor Stinner8c62be82010-05-06 00:08:46 +000014424 /* Do not follow links. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014425 if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014426#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020014427#ifdef O_NOLINKS
14428 /* Fails if link count of the named file is greater than 1 */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014429 if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020014430#endif
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000014431#ifdef O_NOATIME
Victor Stinner8c62be82010-05-06 00:08:46 +000014432 /* Do not update the access time. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014433 if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000014434#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +000014435
Victor Stinner8c62be82010-05-06 00:08:46 +000014436 /* These come from sysexits.h */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014437#ifdef EX_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014438 if (PyModule_AddIntMacro(m, EX_OK)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014439#endif /* EX_OK */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014440#ifdef EX_USAGE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014441 if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014442#endif /* EX_USAGE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014443#ifdef EX_DATAERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014444 if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014445#endif /* EX_DATAERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014446#ifdef EX_NOINPUT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014447 if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014448#endif /* EX_NOINPUT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014449#ifdef EX_NOUSER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014450 if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014451#endif /* EX_NOUSER */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014452#ifdef EX_NOHOST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014453 if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014454#endif /* EX_NOHOST */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014455#ifdef EX_UNAVAILABLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014456 if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014457#endif /* EX_UNAVAILABLE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014458#ifdef EX_SOFTWARE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014459 if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014460#endif /* EX_SOFTWARE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014461#ifdef EX_OSERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014462 if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014463#endif /* EX_OSERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014464#ifdef EX_OSFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014465 if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014466#endif /* EX_OSFILE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014467#ifdef EX_CANTCREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014468 if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014469#endif /* EX_CANTCREAT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014470#ifdef EX_IOERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014471 if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014472#endif /* EX_IOERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014473#ifdef EX_TEMPFAIL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014474 if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014475#endif /* EX_TEMPFAIL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014476#ifdef EX_PROTOCOL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014477 if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014478#endif /* EX_PROTOCOL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014479#ifdef EX_NOPERM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014480 if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014481#endif /* EX_NOPERM */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014482#ifdef EX_CONFIG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014483 if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014484#endif /* EX_CONFIG */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014485#ifdef EX_NOTFOUND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014486 if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014487#endif /* EX_NOTFOUND */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014488
Amaury Forgeot d'Arc66d00ad2010-09-10 18:11:45 +000014489 /* statvfs */
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014490#ifdef ST_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014491 if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014492#endif /* ST_RDONLY */
14493#ifdef ST_NOSUID
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014494 if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014495#endif /* ST_NOSUID */
14496
doko@ubuntu.comca616a22013-12-08 15:23:07 +010014497 /* GNU extensions */
14498#ifdef ST_NODEV
14499 if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
14500#endif /* ST_NODEV */
14501#ifdef ST_NOEXEC
14502 if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
14503#endif /* ST_NOEXEC */
14504#ifdef ST_SYNCHRONOUS
14505 if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
14506#endif /* ST_SYNCHRONOUS */
14507#ifdef ST_MANDLOCK
14508 if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
14509#endif /* ST_MANDLOCK */
14510#ifdef ST_WRITE
14511 if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
14512#endif /* ST_WRITE */
14513#ifdef ST_APPEND
14514 if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
14515#endif /* ST_APPEND */
14516#ifdef ST_NOATIME
14517 if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
14518#endif /* ST_NOATIME */
14519#ifdef ST_NODIRATIME
14520 if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
14521#endif /* ST_NODIRATIME */
14522#ifdef ST_RELATIME
14523 if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
14524#endif /* ST_RELATIME */
14525
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014526 /* FreeBSD sendfile() constants */
14527#ifdef SF_NODISKIO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014528 if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014529#endif
14530#ifdef SF_MNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014531 if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014532#endif
14533#ifdef SF_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014534 if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014535#endif
14536
Ross Lagerwall7807c352011-03-17 20:20:30 +020014537 /* constants for posix_fadvise */
14538#ifdef POSIX_FADV_NORMAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014539 if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014540#endif
14541#ifdef POSIX_FADV_SEQUENTIAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014542 if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014543#endif
14544#ifdef POSIX_FADV_RANDOM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014545 if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014546#endif
14547#ifdef POSIX_FADV_NOREUSE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014548 if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014549#endif
14550#ifdef POSIX_FADV_WILLNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014551 if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014552#endif
14553#ifdef POSIX_FADV_DONTNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014554 if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014555#endif
14556
14557 /* constants for waitid */
14558#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014559 if (PyModule_AddIntMacro(m, P_PID)) return -1;
14560 if (PyModule_AddIntMacro(m, P_PGID)) return -1;
14561 if (PyModule_AddIntMacro(m, P_ALL)) return -1;
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080014562#ifdef P_PIDFD
14563 if (PyModule_AddIntMacro(m, P_PIDFD)) return -1;
14564#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014565#endif
14566#ifdef WEXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014567 if (PyModule_AddIntMacro(m, WEXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014568#endif
14569#ifdef WNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014570 if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014571#endif
14572#ifdef WSTOPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014573 if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014574#endif
14575#ifdef CLD_EXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014576 if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014577#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014578#ifdef CLD_KILLED
14579 if (PyModule_AddIntMacro(m, CLD_KILLED)) return -1;
14580#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014581#ifdef CLD_DUMPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014582 if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014583#endif
14584#ifdef CLD_TRAPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014585 if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014586#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014587#ifdef CLD_STOPPED
14588 if (PyModule_AddIntMacro(m, CLD_STOPPED)) return -1;
14589#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014590#ifdef CLD_CONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014591 if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014592#endif
14593
14594 /* constants for lockf */
14595#ifdef F_LOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014596 if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014597#endif
14598#ifdef F_TLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014599 if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014600#endif
14601#ifdef F_ULOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014602 if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014603#endif
14604#ifdef F_TEST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014605 if (PyModule_AddIntMacro(m, F_TEST)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014606#endif
14607
Pablo Galindo4defba32018-01-27 16:16:37 +000014608#ifdef RWF_DSYNC
14609 if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
14610#endif
14611#ifdef RWF_HIPRI
14612 if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
14613#endif
14614#ifdef RWF_SYNC
14615 if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
14616#endif
14617#ifdef RWF_NOWAIT
14618 if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
14619#endif
YoSTEALTH76ef2552020-05-27 15:32:22 -060014620#ifdef RWF_APPEND
14621 if (PyModule_AddIntConstant(m, "RWF_APPEND", RWF_APPEND)) return -1;
14622#endif
Pablo Galindo4defba32018-01-27 16:16:37 +000014623
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000014624/* constants for posix_spawn */
14625#ifdef HAVE_POSIX_SPAWN
14626 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
14627 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
14628 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
14629#endif
14630
pxinwrf2d7ac72019-05-21 18:46:37 +080014631#if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014632 if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
14633 if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014634 if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
pxinwrf2d7ac72019-05-21 18:46:37 +080014635#endif
14636#ifdef HAVE_SPAWNV
14637 if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014638 if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
Guido van Rossum246bc171999-02-01 23:54:31 +000014639#endif
14640
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014641#ifdef HAVE_SCHED_H
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014642#ifdef SCHED_OTHER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014643 if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014644#endif
14645#ifdef SCHED_FIFO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014646 if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014647#endif
14648#ifdef SCHED_RR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014649 if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014650#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014651#ifdef SCHED_SPORADIC
messi Liao0d322182017-06-13 22:30:43 +080014652 if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014653#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014654#ifdef SCHED_BATCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014655 if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014656#endif
14657#ifdef SCHED_IDLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014658 if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014659#endif
14660#ifdef SCHED_RESET_ON_FORK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014661 if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014662#endif
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014663#ifdef SCHED_SYS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014664 if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014665#endif
14666#ifdef SCHED_IA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014667 if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014668#endif
14669#ifdef SCHED_FSS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014670 if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014671#endif
14672#ifdef SCHED_FX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014673 if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014674#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014675#endif
14676
Benjamin Peterson9428d532011-09-14 11:45:52 -040014677#ifdef USE_XATTRS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014678 if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
14679 if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
14680 if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
Benjamin Peterson799bd802011-08-31 22:15:17 -040014681#endif
14682
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014683#if HAVE_DECL_RTLD_LAZY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014684 if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014685#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014686#if HAVE_DECL_RTLD_NOW
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014687 if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014688#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014689#if HAVE_DECL_RTLD_GLOBAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014690 if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014691#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014692#if HAVE_DECL_RTLD_LOCAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014693 if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014694#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014695#if HAVE_DECL_RTLD_NODELETE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014696 if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014697#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014698#if HAVE_DECL_RTLD_NOLOAD
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014699 if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014700#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014701#if HAVE_DECL_RTLD_DEEPBIND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014702 if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014703#endif
Michael Feltc5ae1692017-12-19 13:58:49 +010014704#if HAVE_DECL_RTLD_MEMBER
14705 if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
14706#endif
Victor Stinner8b905bd2011-10-25 13:34:04 +020014707
Victor Stinner9b1f4742016-09-06 16:18:52 -070014708#ifdef HAVE_GETRANDOM_SYSCALL
14709 if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
14710 if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
14711#endif
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014712#ifdef HAVE_MEMFD_CREATE
14713 if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
14714 if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
14715#ifdef MFD_HUGETLB
14716 if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014717#endif
14718#ifdef MFD_HUGE_SHIFT
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014719 if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014720#endif
14721#ifdef MFD_HUGE_MASK
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014722 if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014723#endif
14724#ifdef MFD_HUGE_64KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014725 if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014726#endif
14727#ifdef MFD_HUGE_512KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014728 if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014729#endif
14730#ifdef MFD_HUGE_1MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014731 if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014732#endif
14733#ifdef MFD_HUGE_2MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014734 if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014735#endif
14736#ifdef MFD_HUGE_8MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014737 if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014738#endif
14739#ifdef MFD_HUGE_16MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014740 if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014741#endif
14742#ifdef MFD_HUGE_32MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014743 if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014744#endif
14745#ifdef MFD_HUGE_256MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014746 if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014747#endif
14748#ifdef MFD_HUGE_512MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014749 if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014750#endif
14751#ifdef MFD_HUGE_1GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014752 if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014753#endif
14754#ifdef MFD_HUGE_2GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014755 if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014756#endif
14757#ifdef MFD_HUGE_16GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014758 if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
14759#endif
14760#endif
Victor Stinner9b1f4742016-09-06 16:18:52 -070014761
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020014762#if defined(__APPLE__)
14763 if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
14764#endif
14765
Steve Dower2438cdf2019-03-29 16:37:16 -070014766#ifdef MS_WINDOWS
14767 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
14768 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
14769 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
14770 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
14771 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
14772#endif
14773
Victor Stinner8c62be82010-05-06 00:08:46 +000014774 return 0;
Barry Warsaw4a342091996-12-19 23:50:02 +000014775}
14776
14777
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014778static const char * const have_functions[] = {
Larry Hastings9cf065c2012-06-22 16:30:09 -070014779
14780#ifdef HAVE_FACCESSAT
14781 "HAVE_FACCESSAT",
14782#endif
14783
14784#ifdef HAVE_FCHDIR
14785 "HAVE_FCHDIR",
14786#endif
14787
14788#ifdef HAVE_FCHMOD
14789 "HAVE_FCHMOD",
14790#endif
14791
14792#ifdef HAVE_FCHMODAT
14793 "HAVE_FCHMODAT",
14794#endif
14795
14796#ifdef HAVE_FCHOWN
14797 "HAVE_FCHOWN",
14798#endif
14799
Larry Hastings00964ed2013-08-12 13:49:30 -040014800#ifdef HAVE_FCHOWNAT
14801 "HAVE_FCHOWNAT",
14802#endif
14803
Larry Hastings9cf065c2012-06-22 16:30:09 -070014804#ifdef HAVE_FEXECVE
14805 "HAVE_FEXECVE",
14806#endif
14807
14808#ifdef HAVE_FDOPENDIR
14809 "HAVE_FDOPENDIR",
14810#endif
14811
Georg Brandl306336b2012-06-24 12:55:33 +020014812#ifdef HAVE_FPATHCONF
14813 "HAVE_FPATHCONF",
14814#endif
14815
Larry Hastings9cf065c2012-06-22 16:30:09 -070014816#ifdef HAVE_FSTATAT
14817 "HAVE_FSTATAT",
14818#endif
14819
14820#ifdef HAVE_FSTATVFS
14821 "HAVE_FSTATVFS",
14822#endif
14823
Steve Dowerfe0a41a2015-03-20 19:50:46 -070014824#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Georg Brandl306336b2012-06-24 12:55:33 +020014825 "HAVE_FTRUNCATE",
14826#endif
14827
Larry Hastings9cf065c2012-06-22 16:30:09 -070014828#ifdef HAVE_FUTIMENS
14829 "HAVE_FUTIMENS",
14830#endif
14831
14832#ifdef HAVE_FUTIMES
14833 "HAVE_FUTIMES",
14834#endif
14835
14836#ifdef HAVE_FUTIMESAT
14837 "HAVE_FUTIMESAT",
14838#endif
14839
14840#ifdef HAVE_LINKAT
14841 "HAVE_LINKAT",
14842#endif
14843
14844#ifdef HAVE_LCHFLAGS
14845 "HAVE_LCHFLAGS",
14846#endif
14847
14848#ifdef HAVE_LCHMOD
14849 "HAVE_LCHMOD",
14850#endif
14851
14852#ifdef HAVE_LCHOWN
14853 "HAVE_LCHOWN",
14854#endif
14855
14856#ifdef HAVE_LSTAT
14857 "HAVE_LSTAT",
14858#endif
14859
14860#ifdef HAVE_LUTIMES
14861 "HAVE_LUTIMES",
14862#endif
14863
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014864#ifdef HAVE_MEMFD_CREATE
14865 "HAVE_MEMFD_CREATE",
14866#endif
14867
Larry Hastings9cf065c2012-06-22 16:30:09 -070014868#ifdef HAVE_MKDIRAT
14869 "HAVE_MKDIRAT",
14870#endif
14871
14872#ifdef HAVE_MKFIFOAT
14873 "HAVE_MKFIFOAT",
14874#endif
14875
14876#ifdef HAVE_MKNODAT
14877 "HAVE_MKNODAT",
14878#endif
14879
14880#ifdef HAVE_OPENAT
14881 "HAVE_OPENAT",
14882#endif
14883
14884#ifdef HAVE_READLINKAT
14885 "HAVE_READLINKAT",
14886#endif
14887
14888#ifdef HAVE_RENAMEAT
14889 "HAVE_RENAMEAT",
14890#endif
14891
14892#ifdef HAVE_SYMLINKAT
14893 "HAVE_SYMLINKAT",
14894#endif
14895
14896#ifdef HAVE_UNLINKAT
14897 "HAVE_UNLINKAT",
14898#endif
14899
14900#ifdef HAVE_UTIMENSAT
14901 "HAVE_UTIMENSAT",
14902#endif
14903
14904#ifdef MS_WINDOWS
14905 "MS_WINDOWS",
14906#endif
14907
14908 NULL
14909};
14910
14911
Victor Stinner1c2fa782020-05-10 11:05:29 +020014912static int
14913posixmodule_exec(PyObject *m)
Guido van Rossumb6775db1994-08-01 11:34:53 +000014914{
Victor Stinner97f33c32020-05-14 18:05:58 +020014915 _posixstate *state = get_posix_state(m);
Tim Peters5aa91602002-01-30 05:46:57 +000014916
Victor Stinner8c62be82010-05-06 00:08:46 +000014917 /* Initialize environ dictionary */
Victor Stinner97f33c32020-05-14 18:05:58 +020014918 PyObject *v = convertenviron();
Victor Stinner8c62be82010-05-06 00:08:46 +000014919 Py_XINCREF(v);
14920 if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
Victor Stinner1c2fa782020-05-10 11:05:29 +020014921 return -1;
Victor Stinner8c62be82010-05-06 00:08:46 +000014922 Py_DECREF(v);
Fred Drakec9680921999-12-13 16:37:25 +000014923
Victor Stinner8c62be82010-05-06 00:08:46 +000014924 if (all_ins(m))
Victor Stinner1c2fa782020-05-10 11:05:29 +020014925 return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014926
Victor Stinner8c62be82010-05-06 00:08:46 +000014927 if (setup_confname_tables(m))
Victor Stinner1c2fa782020-05-10 11:05:29 +020014928 return -1;
Fred Drakebec628d1999-12-15 18:31:10 +000014929
Victor Stinner8c62be82010-05-06 00:08:46 +000014930 Py_INCREF(PyExc_OSError);
14931 PyModule_AddObject(m, "error", PyExc_OSError);
Fred Drake762e2061999-08-26 17:23:54 +000014932
Ross Lagerwall7807c352011-03-17 20:20:30 +020014933#if defined(HAVE_WAITID) && !defined(__APPLE__)
Eddie Elizondob3966632019-11-05 07:16:14 -080014934 waitid_result_desc.name = MODNAME ".waitid_result";
14935 PyObject *WaitidResultType = (PyObject *)PyStructSequence_NewType(&waitid_result_desc);
14936 if (WaitidResultType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020014937 return -1;
Eddie Elizondob3966632019-11-05 07:16:14 -080014938 }
14939 Py_INCREF(WaitidResultType);
14940 PyModule_AddObject(m, "waitid_result", WaitidResultType);
Victor Stinner97f33c32020-05-14 18:05:58 +020014941 state->WaitidResultType = WaitidResultType;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014942#endif
14943
Eddie Elizondob3966632019-11-05 07:16:14 -080014944 stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
14945 stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
14946 stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
14947 stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
14948 PyObject *StatResultType = (PyObject *)PyStructSequence_NewType(&stat_result_desc);
14949 if (StatResultType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020014950 return -1;
Eddie Elizondob3966632019-11-05 07:16:14 -080014951 }
14952 Py_INCREF(StatResultType);
14953 PyModule_AddObject(m, "stat_result", StatResultType);
Victor Stinner97f33c32020-05-14 18:05:58 +020014954 state->StatResultType = StatResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014955 structseq_new = ((PyTypeObject *)StatResultType)->tp_new;
14956 ((PyTypeObject *)StatResultType)->tp_new = statresult_new;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014957
Eddie Elizondob3966632019-11-05 07:16:14 -080014958 statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
14959 PyObject *StatVFSResultType = (PyObject *)PyStructSequence_NewType(&statvfs_result_desc);
14960 if (StatVFSResultType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020014961 return -1;
Eddie Elizondob3966632019-11-05 07:16:14 -080014962 }
14963 Py_INCREF(StatVFSResultType);
14964 PyModule_AddObject(m, "statvfs_result", StatVFSResultType);
Victor Stinner97f33c32020-05-14 18:05:58 +020014965 state->StatVFSResultType = StatVFSResultType;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014966#ifdef NEED_TICKS_PER_SECOND
14967# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Eddie Elizondob3966632019-11-05 07:16:14 -080014968 ticks_per_second = sysconf(_SC_CLK_TCK);
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014969# elif defined(HZ)
Eddie Elizondob3966632019-11-05 07:16:14 -080014970 ticks_per_second = HZ;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014971# else
Eddie Elizondob3966632019-11-05 07:16:14 -080014972 ticks_per_second = 60; /* magic fallback value; may be bogus */
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014973# endif
14974#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014975
William Orr81574b82018-10-01 22:19:56 -070014976#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Eddie Elizondob3966632019-11-05 07:16:14 -080014977 sched_param_desc.name = MODNAME ".sched_param";
14978 PyObject *SchedParamType = (PyObject *)PyStructSequence_NewType(&sched_param_desc);
14979 if (SchedParamType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020014980 return -1;
Victor Stinner8c62be82010-05-06 00:08:46 +000014981 }
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014982 Py_INCREF(SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -080014983 PyModule_AddObject(m, "sched_param", SchedParamType);
Victor Stinner97f33c32020-05-14 18:05:58 +020014984 state->SchedParamType = SchedParamType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014985 ((PyTypeObject *)SchedParamType)->tp_new = os_sched_param;
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014986#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +000014987
Eddie Elizondob3966632019-11-05 07:16:14 -080014988 /* initialize TerminalSize_info */
14989 PyObject *TerminalSizeType = (PyObject *)PyStructSequence_NewType(&TerminalSize_desc);
14990 if (TerminalSizeType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020014991 return -1;
Eddie Elizondob3966632019-11-05 07:16:14 -080014992 }
14993 Py_INCREF(TerminalSizeType);
14994 PyModule_AddObject(m, "terminal_size", TerminalSizeType);
Victor Stinner97f33c32020-05-14 18:05:58 +020014995 state->TerminalSizeType = TerminalSizeType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014996
14997 /* initialize scandir types */
Victor Stinner1c2fa782020-05-10 11:05:29 +020014998 PyObject *ScandirIteratorType = PyType_FromModuleAndSpec(m, &ScandirIteratorType_spec, NULL);
Eddie Elizondob3966632019-11-05 07:16:14 -080014999 if (ScandirIteratorType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020015000 return -1;
Eddie Elizondob3966632019-11-05 07:16:14 -080015001 }
Victor Stinner97f33c32020-05-14 18:05:58 +020015002 state->ScandirIteratorType = ScandirIteratorType;
Eddie Elizondob3966632019-11-05 07:16:14 -080015003
Victor Stinner1c2fa782020-05-10 11:05:29 +020015004 PyObject *DirEntryType = PyType_FromModuleAndSpec(m, &DirEntryType_spec, NULL);
Eddie Elizondob3966632019-11-05 07:16:14 -080015005 if (DirEntryType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020015006 return -1;
Eddie Elizondob3966632019-11-05 07:16:14 -080015007 }
15008 Py_INCREF(DirEntryType);
15009 PyModule_AddObject(m, "DirEntry", DirEntryType);
Victor Stinner97f33c32020-05-14 18:05:58 +020015010 state->DirEntryType = DirEntryType;
Eddie Elizondob3966632019-11-05 07:16:14 -080015011
Larry Hastings605a62d2012-06-24 04:33:36 -070015012 times_result_desc.name = MODNAME ".times_result";
Eddie Elizondob3966632019-11-05 07:16:14 -080015013 PyObject *TimesResultType = (PyObject *)PyStructSequence_NewType(&times_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080015014 if (TimesResultType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020015015 return -1;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080015016 }
Eddie Elizondob3966632019-11-05 07:16:14 -080015017 Py_INCREF(TimesResultType);
15018 PyModule_AddObject(m, "times_result", TimesResultType);
Victor Stinner97f33c32020-05-14 18:05:58 +020015019 state->TimesResultType = TimesResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070015020
Eddie Elizondob3966632019-11-05 07:16:14 -080015021 PyTypeObject *UnameResultType = PyStructSequence_NewType(&uname_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080015022 if (UnameResultType == NULL) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020015023 return -1;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080015024 }
Eddie Elizondob3966632019-11-05 07:16:14 -080015025 Py_INCREF(UnameResultType);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080015026 PyModule_AddObject(m, "uname_result", (PyObject *)UnameResultType);
Victor Stinner97f33c32020-05-14 18:05:58 +020015027 state->UnameResultType = (PyObject *)UnameResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070015028
Thomas Wouters477c8d52006-05-27 19:21:47 +000015029#ifdef __APPLE__
Victor Stinner8c62be82010-05-06 00:08:46 +000015030 /*
15031 * Step 2 of weak-linking support on Mac OS X.
15032 *
15033 * The code below removes functions that are not available on the
15034 * currently active platform.
15035 *
15036 * This block allow one to use a python binary that was build on
Larry Hastings9cf065c2012-06-22 16:30:09 -070015037 * OSX 10.4 on OSX 10.3, without losing access to new APIs on
Victor Stinner8c62be82010-05-06 00:08:46 +000015038 * OSX 10.4.
15039 */
Thomas Wouters477c8d52006-05-27 19:21:47 +000015040#ifdef HAVE_FSTATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000015041 if (fstatvfs == NULL) {
15042 if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020015043 return -1;
Victor Stinner8c62be82010-05-06 00:08:46 +000015044 }
15045 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000015046#endif /* HAVE_FSTATVFS */
15047
15048#ifdef HAVE_STATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000015049 if (statvfs == NULL) {
15050 if (PyObject_DelAttrString(m, "statvfs") == -1) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020015051 return -1;
Victor Stinner8c62be82010-05-06 00:08:46 +000015052 }
15053 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000015054#endif /* HAVE_STATVFS */
15055
15056# ifdef HAVE_LCHOWN
Victor Stinner8c62be82010-05-06 00:08:46 +000015057 if (lchown == NULL) {
15058 if (PyObject_DelAttrString(m, "lchown") == -1) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020015059 return -1;
Victor Stinner8c62be82010-05-06 00:08:46 +000015060 }
15061 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000015062#endif /* HAVE_LCHOWN */
15063
15064
15065#endif /* __APPLE__ */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010015066
Victor Stinner97f33c32020-05-14 18:05:58 +020015067 if ((state->billion = PyLong_FromLong(1000000000)) == NULL)
Victor Stinner1c2fa782020-05-10 11:05:29 +020015068 return -1;
Eddie Elizondob3966632019-11-05 07:16:14 -080015069#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
Victor Stinner97f33c32020-05-14 18:05:58 +020015070 state->struct_rusage = PyUnicode_InternFromString("struct_rusage");
15071 if (state->struct_rusage == NULL)
Victor Stinner1c2fa782020-05-10 11:05:29 +020015072 return -1;
Eddie Elizondob3966632019-11-05 07:16:14 -080015073#endif
Victor Stinner97f33c32020-05-14 18:05:58 +020015074 state->st_mode = PyUnicode_InternFromString("st_mode");
15075 if (state->st_mode == NULL)
Victor Stinner1c2fa782020-05-10 11:05:29 +020015076 return -1;
Larry Hastings6fe20b32012-04-19 15:07:49 -070015077
Larry Hastings9cf065c2012-06-22 16:30:09 -070015078 /* suppress "function not used" warnings */
15079 {
15080 int ignored;
15081 fd_specified("", -1);
15082 follow_symlinks_specified("", 1);
15083 dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
15084 dir_fd_converter(Py_None, &ignored);
15085 dir_fd_unavailable(Py_None, &ignored);
15086 }
15087
15088 /*
15089 * provide list of locally available functions
15090 * so os.py can populate support_* lists
15091 */
Victor Stinner97f33c32020-05-14 18:05:58 +020015092 PyObject *list = PyList_New(0);
15093 if (!list) {
Victor Stinner1c2fa782020-05-10 11:05:29 +020015094 return -1;
Victor Stinner97f33c32020-05-14 18:05:58 +020015095 }
15096 for (const char * const *trace = have_functions; *trace; trace++) {
Larry Hastings9cf065c2012-06-22 16:30:09 -070015097 PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
15098 if (!unicode)
Victor Stinner1c2fa782020-05-10 11:05:29 +020015099 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -070015100 if (PyList_Append(list, unicode))
Victor Stinner1c2fa782020-05-10 11:05:29 +020015101 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -070015102 Py_DECREF(unicode);
15103 }
15104 PyModule_AddObject(m, "_have_functions", list);
Ned Deilyeb3be662016-08-15 14:40:38 -040015105
Victor Stinner1c2fa782020-05-10 11:05:29 +020015106 return 0;
15107}
15108
15109
15110static PyModuleDef_Slot posixmodile_slots[] = {
15111 {Py_mod_exec, posixmodule_exec},
15112 {0, NULL}
15113};
15114
15115static struct PyModuleDef posixmodule = {
15116 PyModuleDef_HEAD_INIT,
15117 .m_name = MODNAME,
15118 .m_doc = posix__doc__,
15119 .m_size = sizeof(_posixstate),
15120 .m_methods = posix_methods,
15121 .m_slots = posixmodile_slots,
15122 .m_traverse = _posix_traverse,
15123 .m_clear = _posix_clear,
15124 .m_free = _posix_free,
15125};
15126
15127PyMODINIT_FUNC
15128INITFUNC(void)
15129{
15130 return PyModuleDef_Init(&posixmodule);
Guido van Rossumb6775db1994-08-01 11:34:53 +000015131}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015132
15133#ifdef __cplusplus
15134}
15135#endif