blob: 0163b0757aefa5838f8e691b909483bf42312c80 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* POSIX module implementation */
2
Jesus Ceaab70e2a2012-10-05 01:48:08 +02003/* This file is also used for Windows NT/MS-Win. In that case the
4 module actually calls itself 'nt', not 'posix', and a few
Andrew MacIntyre6c73af22002-03-03 03:07:07 +00005 functions are either unimplemented or implemented differently. The source
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00006 assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent
Guido van Rossumad0ee831995-03-01 10:34:45 +00007 of the compiler used. Different compilers define their own feature
Victor Stinnerf427a142014-10-22 12:33:23 +02008 test macro, e.g. '_MSC_VER'. */
Guido van Rossumad0ee831995-03-01 10:34:45 +00009
Thomas Wouters477c8d52006-05-27 19:21:47 +000010#ifdef __APPLE__
11 /*
Victor Stinner8c62be82010-05-06 00:08:46 +000012 * Step 1 of support for weak-linking a number of symbols existing on
Thomas Wouters477c8d52006-05-27 19:21:47 +000013 * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block
14 * at the end of this file for more information.
15 */
16# pragma weak lchown
17# pragma weak statvfs
18# pragma weak fstatvfs
19
20#endif /* __APPLE__ */
21
Thomas Wouters68bc4f92006-03-01 01:05:10 +000022#define PY_SSIZE_T_CLEAN
23
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000024#include "Python.h"
Victor Stinnerd5d9e812019-05-13 12:35:37 +020025#ifdef MS_WINDOWS
26 /* include <windows.h> early to avoid conflict with pycore_condvar.h:
27
28 #define WIN32_LEAN_AND_MEAN
29 #include <windows.h>
30
31 FSCTL_GET_REPARSE_POINT is not exported with WIN32_LEAN_AND_MEAN. */
32# include <windows.h>
33#endif
34
Victor Stinner4a21e572020-04-15 02:35:41 +020035#include "pycore_ceval.h" // _PyEval_ReInitThreads()
36#include "pycore_import.h" // _PyImport_ReInitLock()
37#include "pycore_pystate.h" // _PyInterpreterState_GET()
38#include "structmember.h" // PyMemberDef
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020039#ifndef MS_WINDOWS
Victor Stinnerd5d9e812019-05-13 12:35:37 +020040# include "posixmodule.h"
Tim Golden0321cf22014-05-05 19:46:17 +010041#else
Victor Stinnerd5d9e812019-05-13 12:35:37 +020042# include "winreparse.h"
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020043#endif
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000044
Stefan Krahfb7c8ae2016-04-26 17:04:18 +020045/* On android API level 21, 'AT_EACCESS' is not declared although
46 * HAVE_FACCESSAT is defined. */
47#ifdef __ANDROID__
Victor Stinner5eca75d2020-04-15 15:07:31 +020048# undef HAVE_FACCESSAT
Stefan Krahfb7c8ae2016-04-26 17:04:18 +020049#endif
50
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)fa76eee2016-05-28 21:03:48 +000051#include <stdio.h> /* needed for ctermid() */
52
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000053#ifdef __cplusplus
54extern "C" {
55#endif
56
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000057PyDoc_STRVAR(posix__doc__,
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000058"This module provides access to operating system functionality that is\n\
59standardized by the C Standard and the POSIX standard (a thinly\n\
60disguised Unix interface). Refer to the library manual and\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000061corresponding Unix manual entries for more information on calls.");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000062
Martin v. Löwis0073f2e2002-11-21 23:52:35 +000063
Ross Lagerwall4d076da2011-03-18 06:56:53 +020064#ifdef HAVE_SYS_UIO_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020065# include <sys/uio.h>
Ross Lagerwall4d076da2011-03-18 06:56:53 +020066#endif
67
Christian Heimes75b96182017-09-05 15:53:09 +020068#ifdef HAVE_SYS_SYSMACROS_H
69/* GNU C Library: major(), minor(), makedev() */
Victor Stinner5eca75d2020-04-15 15:07:31 +020070# include <sys/sysmacros.h>
Christian Heimes75b96182017-09-05 15:53:09 +020071#endif
72
Thomas Wouters0e3f5912006-08-11 14:57:12 +000073#ifdef HAVE_SYS_TYPES_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020074# include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000075#endif /* HAVE_SYS_TYPES_H */
76
77#ifdef HAVE_SYS_STAT_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020078# include <sys/stat.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000079#endif /* HAVE_SYS_STAT_H */
Guido van Rossuma6535fd2001-10-18 19:44:10 +000080
Guido van Rossum36bc6801995-06-14 22:54:23 +000081#ifdef HAVE_SYS_WAIT_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020082# include <sys/wait.h> // WNOHANG
Guido van Rossum36bc6801995-06-14 22:54:23 +000083#endif
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080084#ifdef HAVE_LINUX_WAIT_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020085# include <linux/wait.h> // P_PIDFD
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080086#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +000087
Thomas Wouters0e3f5912006-08-11 14:57:12 +000088#ifdef HAVE_SIGNAL_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020089# include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000090#endif
Guido van Rossuma376cc51996-12-05 23:43:35 +000091
Guido van Rossumb6775db1994-08-01 11:34:53 +000092#ifdef HAVE_FCNTL_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020093# include <fcntl.h>
94#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +000095
Guido van Rossuma6535fd2001-10-18 19:44:10 +000096#ifdef HAVE_GRP_H
Victor Stinner5eca75d2020-04-15 15:07:31 +020097# include <grp.h>
Guido van Rossuma6535fd2001-10-18 19:44:10 +000098#endif
99
Barry Warsaw5676bd12003-01-07 20:57:09 +0000100#ifdef HAVE_SYSEXITS_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200101# include <sysexits.h>
102#endif
Barry Warsaw5676bd12003-01-07 20:57:09 +0000103
Anthony Baxter8a560de2004-10-13 15:30:56 +0000104#ifdef HAVE_SYS_LOADAVG_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200105# include <sys/loadavg.h>
Anthony Baxter8a560de2004-10-13 15:30:56 +0000106#endif
107
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000108#ifdef HAVE_SYS_SENDFILE_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200109# include <sys/sendfile.h>
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000110#endif
111
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +0200112#if defined(__APPLE__)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200113# include <copyfile.h>
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +0200114#endif
115
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500116#ifdef HAVE_SCHED_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200117# include <sched.h>
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500118#endif
119
Pablo Galindoaac4d032019-05-31 19:39:47 +0100120#ifdef HAVE_COPY_FILE_RANGE
Victor Stinner5eca75d2020-04-15 15:07:31 +0200121# include <unistd.h>
Pablo Galindoaac4d032019-05-31 19:39:47 +0100122#endif
123
Benjamin Peterson2dbda072012-03-16 10:12:55 -0500124#if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200125# undef HAVE_SCHED_SETAFFINITY
Benjamin Peterson7b51b8d2012-03-14 22:28:25 -0500126#endif
127
doko@ubuntu.com4a173bc2014-04-17 19:47:16 +0200128#if defined(HAVE_SYS_XATTR_H) && defined(__GLIBC__) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200129# define USE_XATTRS
Benjamin Peterson9428d532011-09-14 11:45:52 -0400130#endif
131
132#ifdef USE_XATTRS
Victor Stinner5eca75d2020-04-15 15:07:31 +0200133# include <sys/xattr.h>
Benjamin Peterson799bd802011-08-31 22:15:17 -0400134#endif
135
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000136#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200137# ifdef HAVE_SYS_SOCKET_H
138# include <sys/socket.h>
139# endif
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000140#endif
141
Victor Stinner8b905bd2011-10-25 13:34:04 +0200142#ifdef HAVE_DLFCN_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200143# include <dlfcn.h>
Victor Stinner8b905bd2011-10-25 13:34:04 +0200144#endif
145
Charles-Francois Natali44feda32013-05-20 14:40:46 +0200146#ifdef __hpux
Victor Stinner5eca75d2020-04-15 15:07:31 +0200147# include <sys/mpctl.h>
Charles-Francois Natali44feda32013-05-20 14:40:46 +0200148#endif
149
150#if defined(__DragonFly__) || \
151 defined(__OpenBSD__) || \
152 defined(__FreeBSD__) || \
153 defined(__NetBSD__) || \
154 defined(__APPLE__)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200155# include <sys/sysctl.h>
Charles-Francois Natali44feda32013-05-20 14:40:46 +0200156#endif
157
Victor Stinner9b1f4742016-09-06 16:18:52 -0700158#ifdef HAVE_LINUX_RANDOM_H
159# include <linux/random.h>
160#endif
161#ifdef HAVE_GETRANDOM_SYSCALL
162# include <sys/syscall.h>
163#endif
164
Antoine Pitroubcf2b592012-02-08 23:28:36 +0100165#if defined(MS_WINDOWS)
166# define TERMSIZE_USE_CONIO
167#elif defined(HAVE_SYS_IOCTL_H)
168# include <sys/ioctl.h>
169# if defined(HAVE_TERMIOS_H)
170# include <termios.h>
171# endif
172# if defined(TIOCGWINSZ)
173# define TERMSIZE_USE_IOCTL
174# endif
175#endif /* MS_WINDOWS */
176
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000177/* Various compilers have only certain posix functions */
Martin v. Löwis4f1cd8b2001-07-26 13:41:06 +0000178/* XXX Gosh I wish these were all moved into pyconfig.h */
Victor Stinner8c62be82010-05-06 00:08:46 +0000179#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
Victor Stinner5eca75d2020-04-15 15:07:31 +0200180# define HAVE_OPENDIR 1
181# define HAVE_SYSTEM 1
182# include <process.h>
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000183#else
Victor Stinner5eca75d2020-04-15 15:07:31 +0200184# ifdef _MSC_VER
185 /* Microsoft compiler */
186# define HAVE_GETPPID 1
187# define HAVE_GETLOGIN 1
188# define HAVE_SPAWNV 1
189# define HAVE_EXECV 1
190# define HAVE_WSPAWNV 1
191# define HAVE_WEXECV 1
192# define HAVE_PIPE 1
193# define HAVE_SYSTEM 1
194# define HAVE_CWAIT 1
195# define HAVE_FSYNC 1
196# define fsync _commit
197# else
198 /* Unix functions that the configure script doesn't check for */
199# ifndef __VXWORKS__
200# define HAVE_EXECV 1
201# define HAVE_FORK 1
202# if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */
203# define HAVE_FORK1 1
204# endif
205# endif
206# define HAVE_GETEGID 1
207# define HAVE_GETEUID 1
208# define HAVE_GETGID 1
209# define HAVE_GETPPID 1
210# define HAVE_GETUID 1
211# define HAVE_KILL 1
212# define HAVE_OPENDIR 1
213# define HAVE_PIPE 1
214# define HAVE_SYSTEM 1
215# define HAVE_WAIT 1
216# define HAVE_TTYNAME 1
217# endif /* _MSC_VER */
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000218#endif /* ! __WATCOMC__ || __QNX__ */
Guido van Rossumad0ee831995-03-01 10:34:45 +0000219
Eddie Elizondob3966632019-11-05 07:16:14 -0800220_Py_IDENTIFIER(__fspath__);
Victor Stinnera2f7c002012-02-08 03:36:25 +0100221
Larry Hastings61272b72014-01-07 12:41:53 -0800222/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +1000223# one of the few times we lie about this name!
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800224module os
Larry Hastings61272b72014-01-07 12:41:53 -0800225[clinic start generated code]*/
Larry Hastings2f936352014-08-05 14:04:04 +1000226/*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
Victor Stinnera2f7c002012-02-08 03:36:25 +0100227
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000228#ifndef _MSC_VER
Guido van Rossum36bc6801995-06-14 22:54:23 +0000229
Martin v. Löwis8eb92a02002-09-19 08:03:21 +0000230#if defined(__sgi)&&_COMPILER_VERSION>=700
231/* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
232 (default) */
233extern char *ctermid_r(char *);
234#endif
235
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000236#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000237
pxinwrf2d7ac72019-05-21 18:46:37 +0800238#if defined(__VXWORKS__)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200239# include <vxCpuLib.h>
240# include <rtpLib.h>
241# include <wait.h>
242# include <taskLib.h>
243# ifndef _P_WAIT
244# define _P_WAIT 0
245# define _P_NOWAIT 1
246# define _P_NOWAITO 1
247# endif
pxinwrf2d7ac72019-05-21 18:46:37 +0800248#endif /* __VXWORKS__ */
249
Pablo Galindo6c6ddf92018-01-29 01:56:10 +0000250#ifdef HAVE_POSIX_SPAWN
Victor Stinner5eca75d2020-04-15 15:07:31 +0200251# include <spawn.h>
Pablo Galindo6c6ddf92018-01-29 01:56:10 +0000252#endif
253
Guido van Rossumb6775db1994-08-01 11:34:53 +0000254#ifdef HAVE_UTIME_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200255# include <utime.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000256#endif /* HAVE_UTIME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000257
Guido van Rossum14ed0b21994-09-29 09:50:09 +0000258#ifdef HAVE_SYS_UTIME_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200259# include <sys/utime.h>
260# define HAVE_UTIME_H /* pretend we do for the rest of this file */
Guido van Rossum14ed0b21994-09-29 09:50:09 +0000261#endif /* HAVE_SYS_UTIME_H */
262
Guido van Rossumb6775db1994-08-01 11:34:53 +0000263#ifdef HAVE_SYS_TIMES_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200264# include <sys/times.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000265#endif /* HAVE_SYS_TIMES_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000266
267#ifdef HAVE_SYS_PARAM_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200268# include <sys/param.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000269#endif /* HAVE_SYS_PARAM_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000270
271#ifdef HAVE_SYS_UTSNAME_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200272# include <sys/utsname.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000273#endif /* HAVE_SYS_UTSNAME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000274
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000275#ifdef HAVE_DIRENT_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200276# include <dirent.h>
277# define NAMLEN(dirent) strlen((dirent)->d_name)
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000278#else
Victor Stinner5eca75d2020-04-15 15:07:31 +0200279# if defined(__WATCOMC__) && !defined(__QNX__)
280# include <direct.h>
281# define NAMLEN(dirent) strlen((dirent)->d_name)
282# else
283# define dirent direct
284# define NAMLEN(dirent) (dirent)->d_namlen
285# endif
286# ifdef HAVE_SYS_NDIR_H
287# include <sys/ndir.h>
288# endif
289# ifdef HAVE_SYS_DIR_H
290# include <sys/dir.h>
291# endif
292# ifdef HAVE_NDIR_H
293# include <ndir.h>
294# endif
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000295#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000296
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000297#ifdef _MSC_VER
Victor Stinner5eca75d2020-04-15 15:07:31 +0200298# ifdef HAVE_DIRECT_H
299# include <direct.h>
300# endif
301# ifdef HAVE_IO_H
302# include <io.h>
303# endif
304# ifdef HAVE_PROCESS_H
305# include <process.h>
306# endif
307# ifndef IO_REPARSE_TAG_SYMLINK
308# define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
309# endif
310# ifndef IO_REPARSE_TAG_MOUNT_POINT
311# define IO_REPARSE_TAG_MOUNT_POINT (0xA0000003L)
312# endif
313# include "osdefs.h" // SEP
314# include <malloc.h>
315# include <windows.h>
316# include <shellapi.h> // ShellExecute()
317# include <lmcons.h> // UNLEN
318# define HAVE_SYMLINK
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000319#endif /* _MSC_VER */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000320
Tim Petersbc2e10e2002-03-03 23:17:02 +0000321#ifndef MAXPATHLEN
Victor Stinner5eca75d2020-04-15 15:07:31 +0200322# if defined(PATH_MAX) && PATH_MAX > 1024
323# define MAXPATHLEN PATH_MAX
324# else
325# define MAXPATHLEN 1024
326# endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000327#endif /* MAXPATHLEN */
328
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000329#ifdef UNION_WAIT
Victor Stinner5eca75d2020-04-15 15:07:31 +0200330 /* Emulate some macros on systems that have a union instead of macros */
331# ifndef WIFEXITED
332# define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
333# endif
334# ifndef WEXITSTATUS
335# define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
336# endif
337# ifndef WTERMSIG
338# define WTERMSIG(u_wait) ((u_wait).w_termsig)
339# endif
340# define WAIT_TYPE union wait
341# define WAIT_STATUS_INT(s) (s.w_status)
342#else
343 /* !UNION_WAIT */
344# define WAIT_TYPE int
345# define WAIT_STATUS_INT(s) (s)
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000346#endif /* UNION_WAIT */
347
Greg Wardb48bc172000-03-01 21:51:56 +0000348/* Don't use the "_r" form if we don't need it (also, won't have a
349 prototype for it, at least on Solaris -- maybe others as well?). */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200350#if defined(HAVE_CTERMID_R)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200351# define USE_CTERMID_R
Greg Wardb48bc172000-03-01 21:51:56 +0000352#endif
353
Fred Drake699f3522000-06-29 21:12:41 +0000354/* choose the appropriate stat and fstat functions and return structs */
Guido van Rossum64529cd2000-06-30 22:45:12 +0000355#undef STAT
Antoine Pitroue47e0932011-01-19 15:21:35 +0000356#undef FSTAT
357#undef STRUCT_STAT
Victor Stinner14b9b112013-06-25 00:37:25 +0200358#ifdef MS_WINDOWS
Victor Stinner5eca75d2020-04-15 15:07:31 +0200359# define STAT win32_stat
360# define LSTAT win32_lstat
361# define FSTAT _Py_fstat_noraise
362# define STRUCT_STAT struct _Py_stat_struct
Fred Drake699f3522000-06-29 21:12:41 +0000363#else
Victor Stinner5eca75d2020-04-15 15:07:31 +0200364# define STAT stat
365# define LSTAT lstat
366# define FSTAT fstat
367# define STRUCT_STAT struct stat
Fred Drake699f3522000-06-29 21:12:41 +0000368#endif
369
Tim Peters11b23062003-04-23 02:39:17 +0000370#if defined(MAJOR_IN_MKDEV)
Victor Stinner5eca75d2020-04-15 15:07:31 +0200371# include <sys/mkdev.h>
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000372#else
Victor Stinner5eca75d2020-04-15 15:07:31 +0200373# if defined(MAJOR_IN_SYSMACROS)
374# include <sys/sysmacros.h>
375# endif
376# if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
377# include <sys/mkdev.h>
378# endif
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000379#endif
Fred Drake699f3522000-06-29 21:12:41 +0000380
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200381#ifdef MS_WINDOWS
Victor Stinner5eca75d2020-04-15 15:07:31 +0200382# define INITFUNC PyInit_nt
383# define MODNAME "nt"
Victor Stinner6036e442015-03-08 01:58:04 +0100384#else
Victor Stinner5eca75d2020-04-15 15:07:31 +0200385# define INITFUNC PyInit_posix
386# define MODNAME "posix"
Victor Stinner6036e442015-03-08 01:58:04 +0100387#endif
388
jcea6c51d512018-01-28 14:00:08 +0100389#if defined(__sun)
390/* Something to implement in autoconf, not present in autoconf 2.69 */
Victor Stinner5eca75d2020-04-15 15:07:31 +0200391# define HAVE_STRUCT_STAT_ST_FSTYPE 1
jcea6c51d512018-01-28 14:00:08 +0100392#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200393
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600394/* memfd_create is either defined in sys/mman.h or sys/memfd.h
395 * linux/memfd.h defines additional flags
396 */
397#ifdef HAVE_SYS_MMAN_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200398# include <sys/mman.h>
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600399#endif
400#ifdef HAVE_SYS_MEMFD_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200401# include <sys/memfd.h>
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600402#endif
403#ifdef HAVE_LINUX_MEMFD_H
Victor Stinner5eca75d2020-04-15 15:07:31 +0200404# include <linux/memfd.h>
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600405#endif
406
Gregory P. Smith1d300ce2018-12-30 21:13:02 -0800407#ifdef _Py_MEMORY_SANITIZER
Victor Stinner5eca75d2020-04-15 15:07:31 +0200408# include <sanitizer/msan_interface.h>
Gregory P. Smith1d300ce2018-12-30 21:13:02 -0800409#endif
410
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200411#ifdef HAVE_FORK
412static void
413run_at_forkers(PyObject *lst, int reverse)
414{
415 Py_ssize_t i;
416 PyObject *cpy;
417
418 if (lst != NULL) {
419 assert(PyList_CheckExact(lst));
420
421 /* Use a list copy in case register_at_fork() is called from
422 * one of the callbacks.
423 */
424 cpy = PyList_GetSlice(lst, 0, PyList_GET_SIZE(lst));
425 if (cpy == NULL)
426 PyErr_WriteUnraisable(lst);
427 else {
428 if (reverse)
429 PyList_Reverse(cpy);
430 for (i = 0; i < PyList_GET_SIZE(cpy); i++) {
431 PyObject *func, *res;
432 func = PyList_GET_ITEM(cpy, i);
Jeroen Demeyer7f41c8e2019-07-04 12:35:31 +0200433 res = _PyObject_CallNoArg(func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200434 if (res == NULL)
435 PyErr_WriteUnraisable(func);
436 else
437 Py_DECREF(res);
438 }
439 Py_DECREF(cpy);
440 }
441 }
442}
443
444void
445PyOS_BeforeFork(void)
446{
Victor Stinner81a7be32020-04-14 15:14:01 +0200447 run_at_forkers(_PyInterpreterState_GET()->before_forkers, 1);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200448
449 _PyImport_AcquireLock();
450}
451
452void
453PyOS_AfterFork_Parent(void)
454{
455 if (_PyImport_ReleaseLock() <= 0)
456 Py_FatalError("failed releasing import lock after fork");
457
Victor Stinner81a7be32020-04-14 15:14:01 +0200458 run_at_forkers(_PyInterpreterState_GET()->after_forkers_parent, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200459}
460
461void
462PyOS_AfterFork_Child(void)
463{
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200464 _PyRuntimeState *runtime = &_PyRuntime;
465 _PyGILState_Reinit(runtime);
Victor Stinnerd5d9e812019-05-13 12:35:37 +0200466 _PyEval_ReInitThreads(runtime);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200467 _PyImport_ReInitLock();
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200468 _PySignal_AfterFork();
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200469 _PyRuntimeState_ReInitThreads(runtime);
Victor Stinnerb49858b2019-05-24 15:20:23 +0200470 _PyInterpreterState_DeleteExceptMain(runtime);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200471
Victor Stinner81a7be32020-04-14 15:14:01 +0200472 run_at_forkers(_PyInterpreterState_GET()->after_forkers_child, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200473}
474
475static int
476register_at_forker(PyObject **lst, PyObject *func)
477{
Gregory P. Smith163468a2017-05-29 10:03:41 -0700478 if (func == NULL) /* nothing to register? do nothing. */
479 return 0;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200480 if (*lst == NULL) {
481 *lst = PyList_New(0);
482 if (*lst == NULL)
483 return -1;
484 }
485 return PyList_Append(*lst, func);
486}
Victor Stinner87255be2020-04-07 23:11:49 +0200487#endif /* HAVE_FORK */
488
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200489
490/* Legacy wrapper */
491void
492PyOS_AfterFork(void)
493{
494#ifdef HAVE_FORK
495 PyOS_AfterFork_Child();
496#endif
497}
498
499
Victor Stinner6036e442015-03-08 01:58:04 +0100500#ifdef MS_WINDOWS
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200501/* defined in fileutils.c */
Benjamin Petersone5024512018-09-12 12:06:42 -0700502void _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
503void _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *,
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200504 ULONG, struct _Py_stat_struct *);
505#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700506
Larry Hastings9cf065c2012-06-22 16:30:09 -0700507
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200508#ifndef MS_WINDOWS
509PyObject *
510_PyLong_FromUid(uid_t uid)
511{
512 if (uid == (uid_t)-1)
513 return PyLong_FromLong(-1);
514 return PyLong_FromUnsignedLong(uid);
515}
516
517PyObject *
518_PyLong_FromGid(gid_t gid)
519{
520 if (gid == (gid_t)-1)
521 return PyLong_FromLong(-1);
522 return PyLong_FromUnsignedLong(gid);
523}
524
525int
526_Py_Uid_Converter(PyObject *obj, void *p)
527{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700528 uid_t uid;
529 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200530 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200531 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700532 unsigned long uresult;
533
534 index = PyNumber_Index(obj);
535 if (index == NULL) {
536 PyErr_Format(PyExc_TypeError,
537 "uid should be integer, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800538 _PyType_Name(Py_TYPE(obj)));
Serhiy Storchakab4621892013-02-10 23:28:02 +0200539 return 0;
540 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700541
542 /*
543 * Handling uid_t is complicated for two reasons:
544 * * Although uid_t is (always?) unsigned, it still
545 * accepts -1.
546 * * We don't know its size in advance--it may be
547 * bigger than an int, or it may be smaller than
548 * a long.
549 *
550 * So a bit of defensive programming is in order.
551 * Start with interpreting the value passed
552 * in as a signed long and see if it works.
553 */
554
555 result = PyLong_AsLongAndOverflow(index, &overflow);
556
557 if (!overflow) {
558 uid = (uid_t)result;
559
560 if (result == -1) {
561 if (PyErr_Occurred())
562 goto fail;
563 /* It's a legitimate -1, we're done. */
564 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200565 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700566
567 /* Any other negative number is disallowed. */
568 if (result < 0)
569 goto underflow;
570
571 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200572 if (sizeof(uid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700573 (long)uid != result)
574 goto underflow;
575 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200576 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700577
578 if (overflow < 0)
579 goto underflow;
580
581 /*
582 * Okay, the value overflowed a signed long. If it
583 * fits in an *unsigned* long, it may still be okay,
584 * as uid_t may be unsigned long on this platform.
585 */
586 uresult = PyLong_AsUnsignedLong(index);
587 if (PyErr_Occurred()) {
588 if (PyErr_ExceptionMatches(PyExc_OverflowError))
589 goto overflow;
590 goto fail;
591 }
592
593 uid = (uid_t)uresult;
594
595 /*
596 * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
597 * but this value would get interpreted as (uid_t)-1 by chown
598 * and its siblings. That's not what the user meant! So we
599 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100600 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700601 */
602 if (uid == (uid_t)-1)
603 goto overflow;
604
605 /* Ensure the value wasn't truncated. */
606 if (sizeof(uid_t) < sizeof(long) &&
607 (unsigned long)uid != uresult)
608 goto overflow;
609 /* fallthrough */
610
611success:
612 Py_DECREF(index);
613 *(uid_t *)p = uid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200614 return 1;
615
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700616underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200617 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700618 "uid is less than minimum");
619 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200620
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700621overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200622 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700623 "uid is greater than maximum");
624 /* fallthrough */
625
626fail:
627 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200628 return 0;
629}
630
631int
632_Py_Gid_Converter(PyObject *obj, void *p)
633{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700634 gid_t gid;
635 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200636 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200637 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700638 unsigned long uresult;
639
640 index = PyNumber_Index(obj);
641 if (index == NULL) {
642 PyErr_Format(PyExc_TypeError,
643 "gid should be integer, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800644 _PyType_Name(Py_TYPE(obj)));
Serhiy Storchakab4621892013-02-10 23:28:02 +0200645 return 0;
646 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700647
648 /*
649 * Handling gid_t is complicated for two reasons:
650 * * Although gid_t is (always?) unsigned, it still
651 * accepts -1.
652 * * We don't know its size in advance--it may be
653 * bigger than an int, or it may be smaller than
654 * a long.
655 *
656 * So a bit of defensive programming is in order.
657 * Start with interpreting the value passed
658 * in as a signed long and see if it works.
659 */
660
661 result = PyLong_AsLongAndOverflow(index, &overflow);
662
663 if (!overflow) {
664 gid = (gid_t)result;
665
666 if (result == -1) {
667 if (PyErr_Occurred())
668 goto fail;
669 /* It's a legitimate -1, we're done. */
670 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200671 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700672
673 /* Any other negative number is disallowed. */
674 if (result < 0) {
675 goto underflow;
676 }
677
678 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200679 if (sizeof(gid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700680 (long)gid != result)
681 goto underflow;
682 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200683 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700684
685 if (overflow < 0)
686 goto underflow;
687
688 /*
689 * Okay, the value overflowed a signed long. If it
690 * fits in an *unsigned* long, it may still be okay,
691 * as gid_t may be unsigned long on this platform.
692 */
693 uresult = PyLong_AsUnsignedLong(index);
694 if (PyErr_Occurred()) {
695 if (PyErr_ExceptionMatches(PyExc_OverflowError))
696 goto overflow;
697 goto fail;
698 }
699
700 gid = (gid_t)uresult;
701
702 /*
703 * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
704 * but this value would get interpreted as (gid_t)-1 by chown
705 * and its siblings. That's not what the user meant! So we
706 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100707 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700708 */
709 if (gid == (gid_t)-1)
710 goto overflow;
711
712 /* Ensure the value wasn't truncated. */
713 if (sizeof(gid_t) < sizeof(long) &&
714 (unsigned long)gid != uresult)
715 goto overflow;
716 /* fallthrough */
717
718success:
719 Py_DECREF(index);
720 *(gid_t *)p = gid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200721 return 1;
722
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700723underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200724 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700725 "gid is less than minimum");
726 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200727
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700728overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200729 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700730 "gid is greater than maximum");
731 /* fallthrough */
732
733fail:
734 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200735 return 0;
736}
737#endif /* MS_WINDOWS */
738
739
Benjamin Petersoned4aa832016-09-05 17:44:18 -0700740#define _PyLong_FromDev PyLong_FromLongLong
Gregory P. Smith702dada2015-01-28 16:07:52 -0800741
742
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200743#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
744static int
745_Py_Dev_Converter(PyObject *obj, void *p)
746{
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200747 *((dev_t *)p) = PyLong_AsUnsignedLongLong(obj);
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200748 if (PyErr_Occurred())
749 return 0;
750 return 1;
751}
Gregory P. Smith702dada2015-01-28 16:07:52 -0800752#endif /* HAVE_MKNOD && HAVE_MAKEDEV */
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200753
754
Larry Hastings9cf065c2012-06-22 16:30:09 -0700755#ifdef AT_FDCWD
Trent Nelson9a461052012-09-18 21:50:06 -0400756/*
757 * Why the (int) cast? Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
758 * without the int cast, the value gets interpreted as uint (4291925331),
759 * which doesn't play nicely with all the initializer lines in this file that
760 * look like this:
761 * int dir_fd = DEFAULT_DIR_FD;
762 */
763#define DEFAULT_DIR_FD (int)AT_FDCWD
Larry Hastings9cf065c2012-06-22 16:30:09 -0700764#else
765#define DEFAULT_DIR_FD (-100)
766#endif
767
768static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300769_fd_converter(PyObject *o, int *p)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200770{
771 int overflow;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700772 long long_value;
773
774 PyObject *index = PyNumber_Index(o);
775 if (index == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700776 return 0;
777 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700778
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300779 assert(PyLong_Check(index));
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700780 long_value = PyLong_AsLongAndOverflow(index, &overflow);
781 Py_DECREF(index);
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300782 assert(!PyErr_Occurred());
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200783 if (overflow > 0 || long_value > INT_MAX) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700784 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700785 "fd is greater than maximum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700786 return 0;
787 }
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200788 if (overflow < 0 || long_value < INT_MIN) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700789 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700790 "fd is less than minimum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700791 return 0;
792 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700793
Larry Hastings9cf065c2012-06-22 16:30:09 -0700794 *p = (int)long_value;
795 return 1;
796}
797
798static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200799dir_fd_converter(PyObject *o, void *p)
800{
801 if (o == Py_None) {
802 *(int *)p = DEFAULT_DIR_FD;
803 return 1;
804 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300805 else if (PyIndex_Check(o)) {
806 return _fd_converter(o, (int *)p);
807 }
808 else {
809 PyErr_Format(PyExc_TypeError,
810 "argument should be integer or None, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800811 _PyType_Name(Py_TYPE(o)));
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300812 return 0;
813 }
Larry Hastings9cf065c2012-06-22 16:30:09 -0700814}
815
Eddie Elizondob3966632019-11-05 07:16:14 -0800816typedef struct {
817 PyObject *billion;
Eddie Elizondob3966632019-11-05 07:16:14 -0800818 PyObject *DirEntryType;
819 PyObject *ScandirIteratorType;
820#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
821 PyObject *SchedParamType;
822#endif
823 PyObject *StatResultType;
824 PyObject *StatVFSResultType;
825 PyObject *TerminalSizeType;
826 PyObject *TimesResultType;
827 PyObject *UnameResultType;
828#if defined(HAVE_WAITID) && !defined(__APPLE__)
829 PyObject *WaitidResultType;
830#endif
831#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
832 PyObject *struct_rusage;
833#endif
834 PyObject *st_mode;
835} _posixstate;
836
837static struct PyModuleDef posixmodule;
838
Hai Shif707d942020-03-16 21:15:01 +0800839static inline _posixstate*
840get_posix_state(PyObject *module)
841{
842 void *state = PyModule_GetState(module);
843 assert(state != NULL);
844 return (_posixstate *)state;
845}
846
Eddie Elizondob3966632019-11-05 07:16:14 -0800847#define _posixstate_global ((_posixstate *)PyModule_GetState(PyState_FindModule(&posixmodule)))
Larry Hastings9cf065c2012-06-22 16:30:09 -0700848
Larry Hastings9cf065c2012-06-22 16:30:09 -0700849/*
850 * A PyArg_ParseTuple "converter" function
851 * that handles filesystem paths in the manner
852 * preferred by the os module.
853 *
854 * path_converter accepts (Unicode) strings and their
855 * subclasses, and bytes and their subclasses. What
856 * it does with the argument depends on the platform:
857 *
858 * * On Windows, if we get a (Unicode) string we
859 * extract the wchar_t * and return it; if we get
Steve Dowercc16be82016-09-08 10:35:16 -0700860 * bytes we decode to wchar_t * and return that.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700861 *
862 * * On all other platforms, strings are encoded
863 * to bytes using PyUnicode_FSConverter, then we
864 * extract the char * from the bytes object and
865 * return that.
866 *
867 * path_converter also optionally accepts signed
868 * integers (representing open file descriptors) instead
869 * of path strings.
870 *
871 * Input fields:
872 * path.nullable
873 * If nonzero, the path is permitted to be None.
874 * path.allow_fd
875 * If nonzero, the path is permitted to be a file handle
876 * (a signed int) instead of a string.
877 * path.function_name
878 * If non-NULL, path_converter will use that as the name
879 * of the function in error messages.
Larry Hastings31826802013-10-19 00:09:25 -0700880 * (If path.function_name is NULL it omits the function name.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700881 * path.argument_name
882 * If non-NULL, path_converter will use that as the name
883 * of the parameter in error messages.
884 * (If path.argument_name is NULL it uses "path".)
885 *
886 * Output fields:
887 * path.wide
888 * Points to the path if it was expressed as Unicode
889 * and was not encoded. (Only used on Windows.)
890 * path.narrow
891 * Points to the path if it was expressed as bytes,
Steve Dowercc16be82016-09-08 10:35:16 -0700892 * or it was Unicode and was encoded to bytes. (On Windows,
Martin Panterb1321fb2016-10-10 00:38:21 +0000893 * is a non-zero integer if the path was expressed as bytes.
Steve Dowercc16be82016-09-08 10:35:16 -0700894 * The type is deliberately incompatible to prevent misuse.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700895 * path.fd
896 * Contains a file descriptor if path.accept_fd was true
897 * and the caller provided a signed integer instead of any
898 * sort of string.
899 *
900 * WARNING: if your "path" parameter is optional, and is
901 * unspecified, path_converter will never get called.
902 * So if you set allow_fd, you *MUST* initialize path.fd = -1
903 * yourself!
904 * path.length
905 * The length of the path in characters, if specified as
906 * a string.
907 * path.object
Xiang Zhang04316c42017-01-08 23:26:57 +0800908 * The original object passed in (if get a PathLike object,
909 * the result of PyOS_FSPath() is treated as the original object).
910 * Own a reference to the object.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700911 * path.cleanup
912 * For internal use only. May point to a temporary object.
913 * (Pay no attention to the man behind the curtain.)
914 *
915 * At most one of path.wide or path.narrow will be non-NULL.
916 * If path was None and path.nullable was set,
917 * or if path was an integer and path.allow_fd was set,
918 * both path.wide and path.narrow will be NULL
919 * and path.length will be 0.
Georg Brandlf7875592012-06-24 13:58:31 +0200920 *
Larry Hastings9cf065c2012-06-22 16:30:09 -0700921 * path_converter takes care to not write to the path_t
922 * unless it's successful. However it must reset the
923 * "cleanup" field each time it's called.
924 *
925 * Use as follows:
926 * path_t path;
927 * memset(&path, 0, sizeof(path));
928 * PyArg_ParseTuple(args, "O&", path_converter, &path);
929 * // ... use values from path ...
930 * path_cleanup(&path);
931 *
932 * (Note that if PyArg_Parse fails you don't need to call
933 * path_cleanup(). However it is safe to do so.)
934 */
935typedef struct {
Victor Stinner292c8352012-10-30 02:17:38 +0100936 const char *function_name;
937 const char *argument_name;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700938 int nullable;
939 int allow_fd;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300940 const wchar_t *wide;
Steve Dowercc16be82016-09-08 10:35:16 -0700941#ifdef MS_WINDOWS
942 BOOL narrow;
943#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300944 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700945#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700946 int fd;
947 Py_ssize_t length;
948 PyObject *object;
949 PyObject *cleanup;
950} path_t;
951
Steve Dowercc16be82016-09-08 10:35:16 -0700952#ifdef MS_WINDOWS
953#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
954 {function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
955#else
Larry Hastings2f936352014-08-05 14:04:04 +1000956#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
957 {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
Steve Dowercc16be82016-09-08 10:35:16 -0700958#endif
Larry Hastings31826802013-10-19 00:09:25 -0700959
Larry Hastings9cf065c2012-06-22 16:30:09 -0700960static void
Xiang Zhang04316c42017-01-08 23:26:57 +0800961path_cleanup(path_t *path)
962{
963 Py_CLEAR(path->object);
964 Py_CLEAR(path->cleanup);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700965}
966
967static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300968path_converter(PyObject *o, void *p)
969{
Larry Hastings9cf065c2012-06-22 16:30:09 -0700970 path_t *path = (path_t *)p;
Xiang Zhang04316c42017-01-08 23:26:57 +0800971 PyObject *bytes = NULL;
972 Py_ssize_t length = 0;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700973 int is_index, is_buffer, is_bytes, is_unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300974 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700975#ifdef MS_WINDOWS
Xiang Zhang04316c42017-01-08 23:26:57 +0800976 PyObject *wo = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700977 const wchar_t *wide;
978#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700979
980#define FORMAT_EXCEPTION(exc, fmt) \
981 PyErr_Format(exc, "%s%s" fmt, \
982 path->function_name ? path->function_name : "", \
983 path->function_name ? ": " : "", \
984 path->argument_name ? path->argument_name : "path")
985
986 /* Py_CLEANUP_SUPPORTED support */
987 if (o == NULL) {
988 path_cleanup(path);
989 return 1;
990 }
991
Brett Cannon3f9183b2016-08-26 14:44:48 -0700992 /* Ensure it's always safe to call path_cleanup(). */
Xiang Zhang04316c42017-01-08 23:26:57 +0800993 path->object = path->cleanup = NULL;
994 /* path->object owns a reference to the original object */
995 Py_INCREF(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700996
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300997 if ((o == Py_None) && path->nullable) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700998 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700999#ifdef MS_WINDOWS
1000 path->narrow = FALSE;
1001#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001002 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001003#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07001004 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001005 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001006 }
1007
Brett Cannon3f9183b2016-08-26 14:44:48 -07001008 /* Only call this here so that we don't treat the return value of
1009 os.fspath() as an fd or buffer. */
1010 is_index = path->allow_fd && PyIndex_Check(o);
1011 is_buffer = PyObject_CheckBuffer(o);
1012 is_bytes = PyBytes_Check(o);
1013 is_unicode = PyUnicode_Check(o);
1014
1015 if (!is_index && !is_buffer && !is_unicode && !is_bytes) {
1016 /* Inline PyOS_FSPath() for better error messages. */
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001017 PyObject *func, *res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001018
1019 func = _PyObject_LookupSpecial(o, &PyId___fspath__);
1020 if (NULL == func) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001021 goto error_format;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001022 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001023 res = _PyObject_CallNoArg(func);
Brett Cannon3f9183b2016-08-26 14:44:48 -07001024 Py_DECREF(func);
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001025 if (NULL == res) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001026 goto error_exit;
1027 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001028 else if (PyUnicode_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001029 is_unicode = 1;
1030 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001031 else if (PyBytes_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001032 is_bytes = 1;
1033 }
1034 else {
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001035 PyErr_Format(PyExc_TypeError,
1036 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -08001037 "not %.200s", _PyType_Name(Py_TYPE(o)),
1038 _PyType_Name(Py_TYPE(res)));
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001039 Py_DECREF(res);
1040 goto error_exit;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001041 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001042
1043 /* still owns a reference to the original object */
1044 Py_DECREF(o);
1045 o = res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001046 }
1047
1048 if (is_unicode) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001049#ifdef MS_WINDOWS
Victor Stinner26c03bd2016-09-19 11:55:44 +02001050 wide = PyUnicode_AsUnicodeAndSize(o, &length);
Victor Stinner59799a82013-11-13 14:17:30 +01001051 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001052 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001053 }
Victor Stinner59799a82013-11-13 14:17:30 +01001054 if (length > 32767) {
1055 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001056 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001057 }
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001058 if (wcslen(wide) != length) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001059 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001060 goto error_exit;
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001061 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001062
1063 path->wide = wide;
Xiang Zhang04316c42017-01-08 23:26:57 +08001064 path->narrow = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001065 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001066 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001067#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001068 if (!PyUnicode_FSConverter(o, &bytes)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001069 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001070 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001071#endif
1072 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001073 else if (is_bytes) {
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001074 bytes = o;
1075 Py_INCREF(bytes);
1076 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001077 else if (is_buffer) {
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03001078 /* XXX Replace PyObject_CheckBuffer with PyBytes_Check in other code
Ville Skyttä49b27342017-08-03 09:00:59 +03001079 after removing support of non-bytes buffer objects. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001080 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1081 "%s%s%s should be %s, not %.200s",
1082 path->function_name ? path->function_name : "",
1083 path->function_name ? ": " : "",
1084 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001085 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1086 "integer or None" :
1087 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1088 path->nullable ? "string, bytes, os.PathLike or None" :
1089 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001090 _PyType_Name(Py_TYPE(o)))) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001091 goto error_exit;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001092 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001093 bytes = PyBytes_FromObject(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001094 if (!bytes) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001095 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001096 }
1097 }
Steve Dowercc16be82016-09-08 10:35:16 -07001098 else if (is_index) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001099 if (!_fd_converter(o, &path->fd)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001100 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001101 }
1102 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001103#ifdef MS_WINDOWS
1104 path->narrow = FALSE;
1105#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001106 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001107#endif
Xiang Zhang04316c42017-01-08 23:26:57 +08001108 goto success_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001109 }
1110 else {
Xiang Zhang04316c42017-01-08 23:26:57 +08001111 error_format:
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001112 PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
1113 path->function_name ? path->function_name : "",
1114 path->function_name ? ": " : "",
1115 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001116 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1117 "integer or None" :
1118 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1119 path->nullable ? "string, bytes, os.PathLike or None" :
1120 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001121 _PyType_Name(Py_TYPE(o)));
Xiang Zhang04316c42017-01-08 23:26:57 +08001122 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001123 }
1124
Larry Hastings9cf065c2012-06-22 16:30:09 -07001125 length = PyBytes_GET_SIZE(bytes);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001126 narrow = PyBytes_AS_STRING(bytes);
Victor Stinner706768c2014-08-16 01:03:39 +02001127 if ((size_t)length != strlen(narrow)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03001128 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001129 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001130 }
1131
Steve Dowercc16be82016-09-08 10:35:16 -07001132#ifdef MS_WINDOWS
1133 wo = PyUnicode_DecodeFSDefaultAndSize(
1134 narrow,
1135 length
1136 );
1137 if (!wo) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001138 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001139 }
1140
Xiang Zhang04316c42017-01-08 23:26:57 +08001141 wide = PyUnicode_AsUnicodeAndSize(wo, &length);
Steve Dowercc16be82016-09-08 10:35:16 -07001142 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001143 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001144 }
1145 if (length > 32767) {
1146 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001147 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001148 }
1149 if (wcslen(wide) != length) {
1150 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001151 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001152 }
1153 path->wide = wide;
1154 path->narrow = TRUE;
Xiang Zhang04316c42017-01-08 23:26:57 +08001155 path->cleanup = wo;
1156 Py_DECREF(bytes);
Steve Dowercc16be82016-09-08 10:35:16 -07001157#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001158 path->wide = NULL;
1159 path->narrow = narrow;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001160 if (bytes == o) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001161 /* Still a reference owned by path->object, don't have to
1162 worry about path->narrow is used after free. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001163 Py_DECREF(bytes);
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001164 }
1165 else {
1166 path->cleanup = bytes;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001167 }
Xiang Zhang04316c42017-01-08 23:26:57 +08001168#endif
1169 path->fd = -1;
1170
1171 success_exit:
1172 path->length = length;
1173 path->object = o;
1174 return Py_CLEANUP_SUPPORTED;
1175
1176 error_exit:
1177 Py_XDECREF(o);
1178 Py_XDECREF(bytes);
1179#ifdef MS_WINDOWS
1180 Py_XDECREF(wo);
1181#endif
1182 return 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001183}
1184
1185static void
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001186argument_unavailable_error(const char *function_name, const char *argument_name)
1187{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001188 PyErr_Format(PyExc_NotImplementedError,
1189 "%s%s%s unavailable on this platform",
1190 (function_name != NULL) ? function_name : "",
1191 (function_name != NULL) ? ": ": "",
1192 argument_name);
1193}
1194
1195static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001196dir_fd_unavailable(PyObject *o, void *p)
1197{
1198 int dir_fd;
1199 if (!dir_fd_converter(o, &dir_fd))
Larry Hastings9cf065c2012-06-22 16:30:09 -07001200 return 0;
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001201 if (dir_fd != DEFAULT_DIR_FD) {
1202 argument_unavailable_error(NULL, "dir_fd");
1203 return 0;
1204 }
1205 *(int *)p = dir_fd;
1206 return 1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001207}
1208
1209static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001210fd_specified(const char *function_name, int fd)
1211{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001212 if (fd == -1)
1213 return 0;
1214
1215 argument_unavailable_error(function_name, "fd");
1216 return 1;
1217}
1218
1219static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001220follow_symlinks_specified(const char *function_name, int follow_symlinks)
1221{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001222 if (follow_symlinks)
1223 return 0;
1224
1225 argument_unavailable_error(function_name, "follow_symlinks");
1226 return 1;
1227}
1228
1229static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001230path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
1231{
Steve Dowercc16be82016-09-08 10:35:16 -07001232 if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
1233#ifndef MS_WINDOWS
1234 && !path->narrow
1235#endif
1236 ) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001237 PyErr_Format(PyExc_ValueError,
1238 "%s: can't specify dir_fd without matching path",
1239 function_name);
1240 return 1;
1241 }
1242 return 0;
1243}
1244
1245static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001246dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
1247{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001248 if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
1249 PyErr_Format(PyExc_ValueError,
1250 "%s: can't specify both dir_fd and fd",
1251 function_name);
1252 return 1;
1253 }
1254 return 0;
1255}
1256
1257static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001258fd_and_follow_symlinks_invalid(const char *function_name, int fd,
1259 int follow_symlinks)
1260{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001261 if ((fd > 0) && (!follow_symlinks)) {
1262 PyErr_Format(PyExc_ValueError,
1263 "%s: cannot use fd and follow_symlinks together",
1264 function_name);
1265 return 1;
1266 }
1267 return 0;
1268}
1269
1270static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001271dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
1272 int follow_symlinks)
1273{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001274 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
1275 PyErr_Format(PyExc_ValueError,
1276 "%s: cannot use dir_fd and follow_symlinks together",
1277 function_name);
1278 return 1;
1279 }
1280 return 0;
1281}
1282
Larry Hastings2f936352014-08-05 14:04:04 +10001283#ifdef MS_WINDOWS
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001284 typedef long long Py_off_t;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001285#else
Larry Hastings2f936352014-08-05 14:04:04 +10001286 typedef off_t Py_off_t;
1287#endif
1288
1289static int
1290Py_off_t_converter(PyObject *arg, void *addr)
1291{
1292#ifdef HAVE_LARGEFILE_SUPPORT
1293 *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
1294#else
1295 *((Py_off_t *)addr) = PyLong_AsLong(arg);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001296#endif
1297 if (PyErr_Occurred())
1298 return 0;
1299 return 1;
1300}
Larry Hastings2f936352014-08-05 14:04:04 +10001301
1302static PyObject *
1303PyLong_FromPy_off_t(Py_off_t offset)
1304{
1305#ifdef HAVE_LARGEFILE_SUPPORT
1306 return PyLong_FromLongLong(offset);
1307#else
1308 return PyLong_FromLong(offset);
Ross Lagerwallb1e5d592011-09-19 08:30:43 +02001309#endif
Larry Hastings2f936352014-08-05 14:04:04 +10001310}
1311
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001312#ifdef HAVE_SIGSET_T
1313/* Convert an iterable of integers to a sigset.
1314 Return 1 on success, return 0 and raise an exception on error. */
1315int
1316_Py_Sigset_Converter(PyObject *obj, void *addr)
1317{
1318 sigset_t *mask = (sigset_t *)addr;
1319 PyObject *iterator, *item;
1320 long signum;
1321 int overflow;
1322
Rémi Lapeyref0900192019-05-04 01:30:53 +02001323 // The extra parens suppress the unreachable-code warning with clang on MacOS
1324 if (sigemptyset(mask) < (0)) {
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001325 /* Probably only if mask == NULL. */
1326 PyErr_SetFromErrno(PyExc_OSError);
1327 return 0;
1328 }
1329
1330 iterator = PyObject_GetIter(obj);
1331 if (iterator == NULL) {
1332 return 0;
1333 }
1334
1335 while ((item = PyIter_Next(iterator)) != NULL) {
1336 signum = PyLong_AsLongAndOverflow(item, &overflow);
1337 Py_DECREF(item);
1338 if (signum <= 0 || signum >= NSIG) {
1339 if (overflow || signum != -1 || !PyErr_Occurred()) {
1340 PyErr_Format(PyExc_ValueError,
1341 "signal number %ld out of range", signum);
1342 }
1343 goto error;
1344 }
1345 if (sigaddset(mask, (int)signum)) {
1346 if (errno != EINVAL) {
1347 /* Probably impossible */
1348 PyErr_SetFromErrno(PyExc_OSError);
1349 goto error;
1350 }
1351 /* For backwards compatibility, allow idioms such as
1352 * `range(1, NSIG)` but warn about invalid signal numbers
1353 */
1354 const char msg[] =
1355 "invalid signal number %ld, please use valid_signals()";
1356 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
1357 goto error;
1358 }
1359 }
1360 }
1361 if (!PyErr_Occurred()) {
1362 Py_DECREF(iterator);
1363 return 1;
1364 }
1365
1366error:
1367 Py_DECREF(iterator);
1368 return 0;
1369}
1370#endif /* HAVE_SIGSET_T */
1371
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001372#ifdef MS_WINDOWS
Brian Curtinf5e76d02010-11-24 13:14:05 +00001373
1374static int
Brian Curtind25aef52011-06-13 15:16:04 -05001375win32_get_reparse_tag(HANDLE reparse_point_handle, ULONG *reparse_tag)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001376{
Martin Panter70214ad2016-08-04 02:38:59 +00001377 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1378 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001379 DWORD n_bytes_returned;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001380
1381 if (0 == DeviceIoControl(
1382 reparse_point_handle,
1383 FSCTL_GET_REPARSE_POINT,
1384 NULL, 0, /* in buffer */
1385 target_buffer, sizeof(target_buffer),
1386 &n_bytes_returned,
1387 NULL)) /* we're not using OVERLAPPED_IO */
Brian Curtind25aef52011-06-13 15:16:04 -05001388 return FALSE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001389
1390 if (reparse_tag)
1391 *reparse_tag = rdb->ReparseTag;
1392
Brian Curtind25aef52011-06-13 15:16:04 -05001393 return TRUE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001394}
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001395
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001396#endif /* MS_WINDOWS */
Brian Curtinf5e76d02010-11-24 13:14:05 +00001397
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001398/* Return a dictionary corresponding to the POSIX environment table */
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001399#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Jack Jansenea0c3822002-08-01 21:57:49 +00001400/* On Darwin/MacOSX a shared library or framework has no access to
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001401** environ directly, we must obtain it with _NSGetEnviron(). See also
1402** man environ(7).
Jack Jansenea0c3822002-08-01 21:57:49 +00001403*/
1404#include <crt_externs.h>
pxinwrf2d7ac72019-05-21 18:46:37 +08001405#elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001406extern char **environ;
Guido van Rossuma4916fa1996-05-23 22:58:55 +00001407#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001408
Barry Warsaw53699e91996-12-10 23:23:01 +00001409static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001410convertenviron(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001411{
Victor Stinner8c62be82010-05-06 00:08:46 +00001412 PyObject *d;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001413#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00001414 wchar_t **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001415#else
Victor Stinner8c62be82010-05-06 00:08:46 +00001416 char **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001417#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +00001418
Victor Stinner8c62be82010-05-06 00:08:46 +00001419 d = PyDict_New();
1420 if (d == NULL)
1421 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001422#ifdef MS_WINDOWS
1423 /* _wenviron must be initialized in this way if the program is started
1424 through main() instead of wmain(). */
1425 _wgetenv(L"");
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001426 e = _wenviron;
Benoit Hudson723f71a2019-12-06 14:15:03 -05001427#elif defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
1428 /* environ is not accessible as an extern in a shared object on OSX; use
1429 _NSGetEnviron to resolve it. The value changes if you add environment
1430 variables between calls to Py_Initialize, so don't cache the value. */
1431 e = *_NSGetEnviron();
Victor Stinner8c62be82010-05-06 00:08:46 +00001432#else
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001433 e = environ;
1434#endif
1435 if (e == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +00001436 return d;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001437 for (; *e != NULL; e++) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001438 PyObject *k;
1439 PyObject *v;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001440#ifdef MS_WINDOWS
1441 const wchar_t *p = wcschr(*e, L'=');
1442#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03001443 const char *p = strchr(*e, '=');
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001444#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001445 if (p == NULL)
1446 continue;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001447#ifdef MS_WINDOWS
1448 k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
1449#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001450 k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001451#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001452 if (k == NULL) {
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001453 Py_DECREF(d);
1454 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001455 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001456#ifdef MS_WINDOWS
1457 v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
1458#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001459 v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001460#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001461 if (v == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001462 Py_DECREF(k);
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001463 Py_DECREF(d);
1464 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001465 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001466 if (PyDict_GetItemWithError(d, k) == NULL) {
1467 if (PyErr_Occurred() || PyDict_SetItem(d, k, v) != 0) {
1468 Py_DECREF(v);
1469 Py_DECREF(k);
1470 Py_DECREF(d);
1471 return NULL;
1472 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001473 }
1474 Py_DECREF(k);
1475 Py_DECREF(v);
Guido van Rossumd48f2521997-12-05 22:19:34 +00001476 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001477 return d;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001478}
1479
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001480/* Set a POSIX-specific error from errno, and return NULL */
1481
Barry Warsawd58d7641998-07-23 16:14:40 +00001482static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001483posix_error(void)
Guido van Rossumad0ee831995-03-01 10:34:45 +00001484{
Victor Stinner8c62be82010-05-06 00:08:46 +00001485 return PyErr_SetFromErrno(PyExc_OSError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001486}
Mark Hammondef8b6542001-05-13 08:04:26 +00001487
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001488#ifdef MS_WINDOWS
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001489static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001490win32_error(const char* function, const char* filename)
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001491{
Victor Stinner8c62be82010-05-06 00:08:46 +00001492 /* XXX We should pass the function name along in the future.
1493 (winreg.c also wants to pass the function name.)
1494 This would however require an additional param to the
1495 Windows error object, which is non-trivial.
1496 */
1497 errno = GetLastError();
1498 if (filename)
1499 return PyErr_SetFromWindowsErrWithFilename(errno, filename);
1500 else
1501 return PyErr_SetFromWindowsErr(errno);
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001502}
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001503
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001504static PyObject *
Steve Dower2438cdf2019-03-29 16:37:16 -07001505win32_error_object_err(const char* function, PyObject* filename, DWORD err)
Victor Stinnereb5657a2011-09-30 01:44:27 +02001506{
1507 /* XXX - see win32_error for comments on 'function' */
Victor Stinnereb5657a2011-09-30 01:44:27 +02001508 if (filename)
1509 return PyErr_SetExcFromWindowsErrWithFilenameObject(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001510 PyExc_OSError,
Steve Dower2438cdf2019-03-29 16:37:16 -07001511 err,
Victor Stinnereb5657a2011-09-30 01:44:27 +02001512 filename);
1513 else
Steve Dower2438cdf2019-03-29 16:37:16 -07001514 return PyErr_SetFromWindowsErr(err);
1515}
1516
1517static PyObject *
1518win32_error_object(const char* function, PyObject* filename)
1519{
1520 errno = GetLastError();
1521 return win32_error_object_err(function, filename, errno);
Victor Stinnereb5657a2011-09-30 01:44:27 +02001522}
1523
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001524#endif /* MS_WINDOWS */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001525
Larry Hastings9cf065c2012-06-22 16:30:09 -07001526static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001527posix_path_object_error(PyObject *path)
1528{
1529 return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
1530}
1531
1532static PyObject *
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001533path_object_error(PyObject *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001534{
1535#ifdef MS_WINDOWS
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001536 return PyErr_SetExcFromWindowsErrWithFilenameObject(
1537 PyExc_OSError, 0, path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001538#else
Alexey Izbyshev83460312018-10-20 03:28:22 +03001539 return posix_path_object_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001540#endif
1541}
1542
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001543static PyObject *
1544path_object_error2(PyObject *path, PyObject *path2)
1545{
1546#ifdef MS_WINDOWS
1547 return PyErr_SetExcFromWindowsErrWithFilenameObjects(
1548 PyExc_OSError, 0, path, path2);
1549#else
1550 return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
1551#endif
1552}
1553
1554static PyObject *
1555path_error(path_t *path)
1556{
1557 return path_object_error(path->object);
1558}
Larry Hastings31826802013-10-19 00:09:25 -07001559
Larry Hastingsb0827312014-02-09 22:05:19 -08001560static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001561posix_path_error(path_t *path)
1562{
1563 return posix_path_object_error(path->object);
1564}
1565
1566static PyObject *
Larry Hastingsb0827312014-02-09 22:05:19 -08001567path_error2(path_t *path, path_t *path2)
1568{
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001569 return path_object_error2(path->object, path2->object);
Larry Hastingsb0827312014-02-09 22:05:19 -08001570}
1571
1572
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001573/* POSIX generic methods */
1574
Larry Hastings2f936352014-08-05 14:04:04 +10001575static int
1576fildes_converter(PyObject *o, void *p)
Fred Drake4d1e64b2002-04-15 19:40:07 +00001577{
Victor Stinner8c62be82010-05-06 00:08:46 +00001578 int fd;
Larry Hastings2f936352014-08-05 14:04:04 +10001579 int *pointer = (int *)p;
1580 fd = PyObject_AsFileDescriptor(o);
Victor Stinner8c62be82010-05-06 00:08:46 +00001581 if (fd < 0)
Larry Hastings2f936352014-08-05 14:04:04 +10001582 return 0;
Larry Hastings2f936352014-08-05 14:04:04 +10001583 *pointer = fd;
1584 return 1;
1585}
1586
1587static PyObject *
1588posix_fildes_fd(int fd, int (*func)(int))
1589{
1590 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001591 int async_err = 0;
1592
1593 do {
1594 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001595 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001596 res = (*func)(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001597 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001598 Py_END_ALLOW_THREADS
1599 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1600 if (res != 0)
1601 return (!async_err) ? posix_error() : NULL;
1602 Py_RETURN_NONE;
Fred Drake4d1e64b2002-04-15 19:40:07 +00001603}
Guido van Rossum21142a01999-01-08 21:05:37 +00001604
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001605
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001606#ifdef MS_WINDOWS
Thomas Wouters477c8d52006-05-27 19:21:47 +00001607/* This is a reimplementation of the C library's chdir function,
1608 but one that produces Win32 errors instead of DOS error codes.
1609 chdir is essentially a wrapper around SetCurrentDirectory; however,
1610 it also needs to set "magic" environment variables indicating
1611 the per-drive current directory, which are of the form =<drive>: */
Benjamin Peterson206e3072008-10-19 14:07:49 +00001612static BOOL __stdcall
Thomas Wouters477c8d52006-05-27 19:21:47 +00001613win32_wchdir(LPCWSTR path)
1614{
Victor Stinnered537822015-12-13 21:40:26 +01001615 wchar_t path_buf[MAX_PATH], *new_path = path_buf;
Victor Stinner8c62be82010-05-06 00:08:46 +00001616 int result;
1617 wchar_t env[4] = L"=x:";
Thomas Wouters477c8d52006-05-27 19:21:47 +00001618
Victor Stinner8c62be82010-05-06 00:08:46 +00001619 if(!SetCurrentDirectoryW(path))
1620 return FALSE;
Victor Stinnered537822015-12-13 21:40:26 +01001621 result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001622 if (!result)
1623 return FALSE;
Victor Stinnere847d712015-12-14 00:21:50 +01001624 if (result > Py_ARRAY_LENGTH(path_buf)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001625 new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00001626 if (!new_path) {
1627 SetLastError(ERROR_OUTOFMEMORY);
1628 return FALSE;
1629 }
1630 result = GetCurrentDirectoryW(result, new_path);
1631 if (!result) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001632 PyMem_RawFree(new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001633 return FALSE;
1634 }
1635 }
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001636 int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
1637 wcsncmp(new_path, L"//", 2) == 0);
1638 if (!is_unc_like_path) {
1639 env[1] = new_path[0];
1640 result = SetEnvironmentVariableW(env, new_path);
1641 }
Victor Stinnered537822015-12-13 21:40:26 +01001642 if (new_path != path_buf)
Victor Stinnerb6404912013-07-07 16:21:41 +02001643 PyMem_RawFree(new_path);
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001644 return result ? TRUE : FALSE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001645}
1646#endif
1647
Martin v. Löwis14694662006-02-03 12:54:16 +00001648#ifdef MS_WINDOWS
1649/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
1650 - time stamps are restricted to second resolution
1651 - file modification times suffer from forth-and-back conversions between
1652 UTC and local time
1653 Therefore, we implement our own stat, based on the Win32 API directly.
1654*/
Victor Stinner8c62be82010-05-06 00:08:46 +00001655#define HAVE_STAT_NSEC 1
Zachary Ware63f277b2014-06-19 09:46:37 -05001656#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001657#define HAVE_STRUCT_STAT_ST_REPARSE_TAG 1
Martin v. Löwis14694662006-02-03 12:54:16 +00001658
Victor Stinner6036e442015-03-08 01:58:04 +01001659static void
Steve Dowercc16be82016-09-08 10:35:16 -07001660find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
1661 BY_HANDLE_FILE_INFORMATION *info,
1662 ULONG *reparse_tag)
Victor Stinner6036e442015-03-08 01:58:04 +01001663{
1664 memset(info, 0, sizeof(*info));
1665 info->dwFileAttributes = pFileData->dwFileAttributes;
1666 info->ftCreationTime = pFileData->ftCreationTime;
1667 info->ftLastAccessTime = pFileData->ftLastAccessTime;
1668 info->ftLastWriteTime = pFileData->ftLastWriteTime;
1669 info->nFileSizeHigh = pFileData->nFileSizeHigh;
1670 info->nFileSizeLow = pFileData->nFileSizeLow;
1671/* info->nNumberOfLinks = 1; */
1672 if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
1673 *reparse_tag = pFileData->dwReserved0;
1674 else
1675 *reparse_tag = 0;
1676}
1677
Guido van Rossumd8faa362007-04-27 19:54:29 +00001678static BOOL
Steve Dowercc16be82016-09-08 10:35:16 -07001679attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001680{
Victor Stinner8c62be82010-05-06 00:08:46 +00001681 HANDLE hFindFile;
1682 WIN32_FIND_DATAW FileData;
1683 hFindFile = FindFirstFileW(pszFile, &FileData);
1684 if (hFindFile == INVALID_HANDLE_VALUE)
1685 return FALSE;
1686 FindClose(hFindFile);
Steve Dowercc16be82016-09-08 10:35:16 -07001687 find_data_to_file_info(&FileData, info, reparse_tag);
Victor Stinner8c62be82010-05-06 00:08:46 +00001688 return TRUE;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001689}
1690
Brian Curtind25aef52011-06-13 15:16:04 -05001691static int
Steve Dowercc16be82016-09-08 10:35:16 -07001692win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
Brian Curtind25aef52011-06-13 15:16:04 -05001693 BOOL traverse)
1694{
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001695 HANDLE hFile;
1696 BY_HANDLE_FILE_INFORMATION fileInfo;
1697 FILE_ATTRIBUTE_TAG_INFO tagInfo = { 0 };
1698 DWORD fileType, error;
1699 BOOL isUnhandledTag = FALSE;
1700 int retval = 0;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001701
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001702 DWORD access = FILE_READ_ATTRIBUTES;
1703 DWORD flags = FILE_FLAG_BACKUP_SEMANTICS; /* Allow opening directories. */
1704 if (!traverse) {
1705 flags |= FILE_FLAG_OPEN_REPARSE_POINT;
1706 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001707
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001708 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING, flags, NULL);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001709 if (hFile == INVALID_HANDLE_VALUE) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001710 /* Either the path doesn't exist, or the caller lacks access. */
1711 error = GetLastError();
1712 switch (error) {
1713 case ERROR_ACCESS_DENIED: /* Cannot sync or read attributes. */
1714 case ERROR_SHARING_VIOLATION: /* It's a paging file. */
1715 /* Try reading the parent directory. */
1716 if (!attributes_from_dir(path, &fileInfo, &tagInfo.ReparseTag)) {
1717 /* Cannot read the parent directory. */
1718 SetLastError(error);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001719 return -1;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001720 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001721 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1722 if (traverse ||
1723 !IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1724 /* The stat call has to traverse but cannot, so fail. */
1725 SetLastError(error);
Brian Curtind25aef52011-06-13 15:16:04 -05001726 return -1;
Mark Becwarb82bfac2019-02-02 16:08:23 -05001727 }
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001728 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001729 break;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001730
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001731 case ERROR_INVALID_PARAMETER:
1732 /* \\.\con requires read or write access. */
1733 hFile = CreateFileW(path, access | GENERIC_READ,
1734 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1735 OPEN_EXISTING, flags, NULL);
1736 if (hFile == INVALID_HANDLE_VALUE) {
1737 SetLastError(error);
1738 return -1;
1739 }
1740 break;
1741
1742 case ERROR_CANT_ACCESS_FILE:
1743 /* bpo37834: open unhandled reparse points if traverse fails. */
1744 if (traverse) {
1745 traverse = FALSE;
1746 isUnhandledTag = TRUE;
1747 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING,
1748 flags | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
1749 }
1750 if (hFile == INVALID_HANDLE_VALUE) {
1751 SetLastError(error);
1752 return -1;
1753 }
1754 break;
1755
1756 default:
1757 return -1;
1758 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001759 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001760
1761 if (hFile != INVALID_HANDLE_VALUE) {
1762 /* Handle types other than files on disk. */
1763 fileType = GetFileType(hFile);
1764 if (fileType != FILE_TYPE_DISK) {
1765 if (fileType == FILE_TYPE_UNKNOWN && GetLastError() != 0) {
1766 retval = -1;
1767 goto cleanup;
1768 }
1769 DWORD fileAttributes = GetFileAttributesW(path);
1770 memset(result, 0, sizeof(*result));
1771 if (fileAttributes != INVALID_FILE_ATTRIBUTES &&
1772 fileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1773 /* \\.\pipe\ or \\.\mailslot\ */
1774 result->st_mode = _S_IFDIR;
1775 } else if (fileType == FILE_TYPE_CHAR) {
1776 /* \\.\nul */
1777 result->st_mode = _S_IFCHR;
1778 } else if (fileType == FILE_TYPE_PIPE) {
1779 /* \\.\pipe\spam */
1780 result->st_mode = _S_IFIFO;
1781 }
1782 /* FILE_TYPE_UNKNOWN, e.g. \\.\mailslot\waitfor.exe\spam */
1783 goto cleanup;
1784 }
1785
1786 /* Query the reparse tag, and traverse a non-link. */
1787 if (!traverse) {
1788 if (!GetFileInformationByHandleEx(hFile, FileAttributeTagInfo,
1789 &tagInfo, sizeof(tagInfo))) {
1790 /* Allow devices that do not support FileAttributeTagInfo. */
1791 switch (GetLastError()) {
1792 case ERROR_INVALID_PARAMETER:
1793 case ERROR_INVALID_FUNCTION:
1794 case ERROR_NOT_SUPPORTED:
1795 tagInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1796 tagInfo.ReparseTag = 0;
1797 break;
1798 default:
1799 retval = -1;
1800 goto cleanup;
1801 }
1802 } else if (tagInfo.FileAttributes &
1803 FILE_ATTRIBUTE_REPARSE_POINT) {
1804 if (IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1805 if (isUnhandledTag) {
1806 /* Traversing previously failed for either this link
1807 or its target. */
1808 SetLastError(ERROR_CANT_ACCESS_FILE);
1809 retval = -1;
1810 goto cleanup;
1811 }
1812 /* Traverse a non-link, but not if traversing already failed
1813 for an unhandled tag. */
1814 } else if (!isUnhandledTag) {
1815 CloseHandle(hFile);
1816 return win32_xstat_impl(path, result, TRUE);
1817 }
1818 }
1819 }
1820
1821 if (!GetFileInformationByHandle(hFile, &fileInfo)) {
1822 switch (GetLastError()) {
1823 case ERROR_INVALID_PARAMETER:
1824 case ERROR_INVALID_FUNCTION:
1825 case ERROR_NOT_SUPPORTED:
Steve Dower772ec0f2019-09-04 14:42:54 -07001826 /* Volumes and physical disks are block devices, e.g.
1827 \\.\C: and \\.\PhysicalDrive0. */
1828 memset(result, 0, sizeof(*result));
1829 result->st_mode = 0x6000; /* S_IFBLK */
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001830 goto cleanup;
1831 }
Steve Dower772ec0f2019-09-04 14:42:54 -07001832 retval = -1;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001833 goto cleanup;
1834 }
1835 }
1836
1837 _Py_attribute_data_to_stat(&fileInfo, tagInfo.ReparseTag, result);
1838
1839 if (!(fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
1840 /* Fix the file execute permissions. This hack sets S_IEXEC if
1841 the filename has an extension that is commonly used by files
1842 that CreateProcessW can execute. A real implementation calls
1843 GetSecurityInfo, OpenThreadToken/OpenProcessToken, and
1844 AccessCheck to check for generic read, write, and execute
1845 access. */
1846 const wchar_t *fileExtension = wcsrchr(path, '.');
1847 if (fileExtension) {
1848 if (_wcsicmp(fileExtension, L".exe") == 0 ||
1849 _wcsicmp(fileExtension, L".bat") == 0 ||
1850 _wcsicmp(fileExtension, L".cmd") == 0 ||
1851 _wcsicmp(fileExtension, L".com") == 0) {
1852 result->st_mode |= 0111;
1853 }
1854 }
1855 }
1856
1857cleanup:
1858 if (hFile != INVALID_HANDLE_VALUE) {
Steve Dower772ec0f2019-09-04 14:42:54 -07001859 /* Preserve last error if we are failing */
1860 error = retval ? GetLastError() : 0;
1861 if (!CloseHandle(hFile)) {
1862 retval = -1;
1863 } else if (retval) {
1864 /* Restore last error */
1865 SetLastError(error);
1866 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001867 }
1868
1869 return retval;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001870}
1871
1872static int
Steve Dowercc16be82016-09-08 10:35:16 -07001873win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001874{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001875 /* Protocol violation: we explicitly clear errno, instead of
1876 setting it to a POSIX error. Callers should use GetLastError. */
Brian Curtind25aef52011-06-13 15:16:04 -05001877 int code = win32_xstat_impl(path, result, traverse);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001878 errno = 0;
1879 return code;
1880}
Brian Curtind25aef52011-06-13 15:16:04 -05001881/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
Brian Curtind40e6f72010-07-08 21:39:08 +00001882
1883 In Posix, stat automatically traverses symlinks and returns the stat
1884 structure for the target. In Windows, the equivalent GetFileAttributes by
1885 default does not traverse symlinks and instead returns attributes for
1886 the symlink.
1887
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001888 Instead, we will open the file (which *does* traverse symlinks by default)
1889 and GetFileInformationByHandle(). */
Brian Curtind40e6f72010-07-08 21:39:08 +00001890
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001891static int
Steve Dowercc16be82016-09-08 10:35:16 -07001892win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
Martin v. Löwis14694662006-02-03 12:54:16 +00001893{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001894 return win32_xstat(path, result, FALSE);
Martin v. Löwis14694662006-02-03 12:54:16 +00001895}
1896
Victor Stinner8c62be82010-05-06 00:08:46 +00001897static int
Steve Dowercc16be82016-09-08 10:35:16 -07001898win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
Brian Curtind40e6f72010-07-08 21:39:08 +00001899{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001900 return win32_xstat(path, result, TRUE);
Brian Curtind40e6f72010-07-08 21:39:08 +00001901}
1902
Martin v. Löwis14694662006-02-03 12:54:16 +00001903#endif /* MS_WINDOWS */
1904
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001905PyDoc_STRVAR(stat_result__doc__,
Larry Hastings9cf065c2012-06-22 16:30:09 -07001906"stat_result: Result from stat, fstat, or lstat.\n\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001907This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001908 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001909or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1910\n\
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001911Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1912or st_flags, they are available as attributes only.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001913\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001914See os.stat for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001915
1916static PyStructSequence_Field stat_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001917 {"st_mode", "protection bits"},
1918 {"st_ino", "inode"},
1919 {"st_dev", "device"},
1920 {"st_nlink", "number of hard links"},
1921 {"st_uid", "user ID of owner"},
1922 {"st_gid", "group ID of owner"},
1923 {"st_size", "total size, in bytes"},
1924 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1925 {NULL, "integer time of last access"},
1926 {NULL, "integer time of last modification"},
1927 {NULL, "integer time of last change"},
1928 {"st_atime", "time of last access"},
1929 {"st_mtime", "time of last modification"},
1930 {"st_ctime", "time of last change"},
Larry Hastings6fe20b32012-04-19 15:07:49 -07001931 {"st_atime_ns", "time of last access in nanoseconds"},
1932 {"st_mtime_ns", "time of last modification in nanoseconds"},
1933 {"st_ctime_ns", "time of last change in nanoseconds"},
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001934#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00001935 {"st_blksize", "blocksize for filesystem I/O"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001936#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001937#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00001938 {"st_blocks", "number of blocks allocated"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001939#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001940#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00001941 {"st_rdev", "device type (if inode device)"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001942#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001943#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00001944 {"st_flags", "user defined flags for file"},
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001945#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001946#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00001947 {"st_gen", "generation number"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001948#endif
1949#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00001950 {"st_birthtime", "time of creation"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001951#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05001952#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1953 {"st_file_attributes", "Windows file attribute bits"},
1954#endif
jcea6c51d512018-01-28 14:00:08 +01001955#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1956 {"st_fstype", "Type of filesystem"},
1957#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001958#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
1959 {"st_reparse_tag", "Windows reparse tag"},
1960#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001961 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001962};
1963
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001964#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Larry Hastings6fe20b32012-04-19 15:07:49 -07001965#define ST_BLKSIZE_IDX 16
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001966#else
Larry Hastings6fe20b32012-04-19 15:07:49 -07001967#define ST_BLKSIZE_IDX 15
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001968#endif
1969
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001970#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001971#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
1972#else
1973#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
1974#endif
1975
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001976#ifdef HAVE_STRUCT_STAT_ST_RDEV
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001977#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
1978#else
1979#define ST_RDEV_IDX ST_BLOCKS_IDX
1980#endif
1981
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001982#ifdef HAVE_STRUCT_STAT_ST_FLAGS
1983#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
1984#else
1985#define ST_FLAGS_IDX ST_RDEV_IDX
1986#endif
1987
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001988#ifdef HAVE_STRUCT_STAT_ST_GEN
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001989#define ST_GEN_IDX (ST_FLAGS_IDX+1)
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001990#else
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001991#define ST_GEN_IDX ST_FLAGS_IDX
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001992#endif
1993
1994#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1995#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
1996#else
1997#define ST_BIRTHTIME_IDX ST_GEN_IDX
1998#endif
1999
Zachary Ware63f277b2014-06-19 09:46:37 -05002000#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2001#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_IDX+1)
2002#else
2003#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_IDX
2004#endif
2005
jcea6c51d512018-01-28 14:00:08 +01002006#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2007#define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
2008#else
2009#define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
2010#endif
2011
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002012#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2013#define ST_REPARSE_TAG_IDX (ST_FSTYPE_IDX+1)
2014#else
2015#define ST_REPARSE_TAG_IDX ST_FSTYPE_IDX
2016#endif
2017
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002018static PyStructSequence_Desc stat_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002019 "stat_result", /* name */
2020 stat_result__doc__, /* doc */
2021 stat_result_fields,
2022 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002023};
2024
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002025PyDoc_STRVAR(statvfs_result__doc__,
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002026"statvfs_result: Result from statvfs or fstatvfs.\n\n\
2027This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00002028 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
Guido van Rossuma4dc73e2001-10-18 20:53:15 +00002029or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002030\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002031See os.statvfs for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002032
2033static PyStructSequence_Field statvfs_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002034 {"f_bsize", },
2035 {"f_frsize", },
2036 {"f_blocks", },
2037 {"f_bfree", },
2038 {"f_bavail", },
2039 {"f_files", },
2040 {"f_ffree", },
2041 {"f_favail", },
2042 {"f_flag", },
2043 {"f_namemax",},
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +01002044 {"f_fsid", },
Victor Stinner8c62be82010-05-06 00:08:46 +00002045 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002046};
2047
2048static PyStructSequence_Desc statvfs_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002049 "statvfs_result", /* name */
2050 statvfs_result__doc__, /* doc */
2051 statvfs_result_fields,
2052 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002053};
2054
Ross Lagerwall7807c352011-03-17 20:20:30 +02002055#if defined(HAVE_WAITID) && !defined(__APPLE__)
2056PyDoc_STRVAR(waitid_result__doc__,
2057"waitid_result: Result from waitid.\n\n\
2058This object may be accessed either as a tuple of\n\
2059 (si_pid, si_uid, si_signo, si_status, si_code),\n\
2060or via the attributes si_pid, si_uid, and so on.\n\
2061\n\
2062See os.waitid for more information.");
2063
2064static PyStructSequence_Field waitid_result_fields[] = {
2065 {"si_pid", },
2066 {"si_uid", },
2067 {"si_signo", },
2068 {"si_status", },
2069 {"si_code", },
2070 {0}
2071};
2072
2073static PyStructSequence_Desc waitid_result_desc = {
2074 "waitid_result", /* name */
2075 waitid_result__doc__, /* doc */
2076 waitid_result_fields,
2077 5
2078};
Benjamin Petersonbad9c2f2011-08-02 18:42:14 -05002079#endif
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002080static newfunc structseq_new;
2081
2082static PyObject *
2083statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2084{
Victor Stinner8c62be82010-05-06 00:08:46 +00002085 PyStructSequence *result;
2086 int i;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002087
Victor Stinner8c62be82010-05-06 00:08:46 +00002088 result = (PyStructSequence*)structseq_new(type, args, kwds);
2089 if (!result)
2090 return NULL;
2091 /* If we have been initialized from a tuple,
2092 st_?time might be set to None. Initialize it
2093 from the int slots. */
2094 for (i = 7; i <= 9; i++) {
2095 if (result->ob_item[i+3] == Py_None) {
2096 Py_DECREF(Py_None);
2097 Py_INCREF(result->ob_item[i]);
2098 result->ob_item[i+3] = result->ob_item[i];
2099 }
2100 }
2101 return (PyObject*)result;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002102}
2103
Eddie Elizondob3966632019-11-05 07:16:14 -08002104static int
2105_posix_clear(PyObject *module)
2106{
Hai Shif707d942020-03-16 21:15:01 +08002107 Py_CLEAR(get_posix_state(module)->billion);
2108 Py_CLEAR(get_posix_state(module)->DirEntryType);
2109 Py_CLEAR(get_posix_state(module)->ScandirIteratorType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002110#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Hai Shif707d942020-03-16 21:15:01 +08002111 Py_CLEAR(get_posix_state(module)->SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002112#endif
Hai Shif707d942020-03-16 21:15:01 +08002113 Py_CLEAR(get_posix_state(module)->StatResultType);
2114 Py_CLEAR(get_posix_state(module)->StatVFSResultType);
2115 Py_CLEAR(get_posix_state(module)->TerminalSizeType);
2116 Py_CLEAR(get_posix_state(module)->TimesResultType);
2117 Py_CLEAR(get_posix_state(module)->UnameResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002118#if defined(HAVE_WAITID) && !defined(__APPLE__)
Hai Shif707d942020-03-16 21:15:01 +08002119 Py_CLEAR(get_posix_state(module)->WaitidResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002120#endif
2121#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
Hai Shif707d942020-03-16 21:15:01 +08002122 Py_CLEAR(get_posix_state(module)->struct_rusage);
Eddie Elizondob3966632019-11-05 07:16:14 -08002123#endif
Hai Shif707d942020-03-16 21:15:01 +08002124 Py_CLEAR(get_posix_state(module)->st_mode);
Eddie Elizondob3966632019-11-05 07:16:14 -08002125 return 0;
2126}
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002127
Eddie Elizondob3966632019-11-05 07:16:14 -08002128static int
2129_posix_traverse(PyObject *module, visitproc visit, void *arg)
2130{
Hai Shif707d942020-03-16 21:15:01 +08002131 Py_VISIT(get_posix_state(module)->billion);
2132 Py_VISIT(get_posix_state(module)->DirEntryType);
2133 Py_VISIT(get_posix_state(module)->ScandirIteratorType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002134#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Hai Shif707d942020-03-16 21:15:01 +08002135 Py_VISIT(get_posix_state(module)->SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002136#endif
Hai Shif707d942020-03-16 21:15:01 +08002137 Py_VISIT(get_posix_state(module)->StatResultType);
2138 Py_VISIT(get_posix_state(module)->StatVFSResultType);
2139 Py_VISIT(get_posix_state(module)->TerminalSizeType);
2140 Py_VISIT(get_posix_state(module)->TimesResultType);
2141 Py_VISIT(get_posix_state(module)->UnameResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002142#if defined(HAVE_WAITID) && !defined(__APPLE__)
Hai Shif707d942020-03-16 21:15:01 +08002143 Py_VISIT(get_posix_state(module)->WaitidResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002144#endif
2145#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
Hai Shif707d942020-03-16 21:15:01 +08002146 Py_VISIT(get_posix_state(module)->struct_rusage);
Eddie Elizondob3966632019-11-05 07:16:14 -08002147#endif
Hai Shif707d942020-03-16 21:15:01 +08002148 Py_VISIT(get_posix_state(module)->st_mode);
Eddie Elizondob3966632019-11-05 07:16:14 -08002149 return 0;
2150}
2151
2152static void
2153_posix_free(void *module)
2154{
2155 _posix_clear((PyObject *)module);
2156}
Larry Hastings6fe20b32012-04-19 15:07:49 -07002157
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002158static void
Victor Stinner4195b5c2012-02-08 23:03:19 +01002159fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002160{
Larry Hastings6fe20b32012-04-19 15:07:49 -07002161 PyObject *s = _PyLong_FromTime_t(sec);
2162 PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
2163 PyObject *s_in_ns = NULL;
2164 PyObject *ns_total = NULL;
2165 PyObject *float_s = NULL;
2166
2167 if (!(s && ns_fractional))
2168 goto exit;
2169
Eddie Elizondob3966632019-11-05 07:16:14 -08002170 s_in_ns = PyNumber_Multiply(s, _posixstate_global->billion);
Larry Hastings6fe20b32012-04-19 15:07:49 -07002171 if (!s_in_ns)
2172 goto exit;
2173
2174 ns_total = PyNumber_Add(s_in_ns, ns_fractional);
2175 if (!ns_total)
2176 goto exit;
2177
Victor Stinner01b5aab2017-10-24 02:02:00 -07002178 float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
2179 if (!float_s) {
2180 goto exit;
Larry Hastings6fe20b32012-04-19 15:07:49 -07002181 }
2182
2183 PyStructSequence_SET_ITEM(v, index, s);
2184 PyStructSequence_SET_ITEM(v, index+3, float_s);
2185 PyStructSequence_SET_ITEM(v, index+6, ns_total);
2186 s = NULL;
2187 float_s = NULL;
2188 ns_total = NULL;
2189exit:
2190 Py_XDECREF(s);
2191 Py_XDECREF(ns_fractional);
2192 Py_XDECREF(s_in_ns);
2193 Py_XDECREF(ns_total);
2194 Py_XDECREF(float_s);
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002195}
2196
Tim Peters5aa91602002-01-30 05:46:57 +00002197/* pack a system stat C structure into the Python stat tuple
Fred Drake699f3522000-06-29 21:12:41 +00002198 (used by posix_stat() and posix_fstat()) */
2199static PyObject*
Victor Stinner4195b5c2012-02-08 23:03:19 +01002200_pystat_fromstructstat(STRUCT_STAT *st)
Fred Drake699f3522000-06-29 21:12:41 +00002201{
Victor Stinner8c62be82010-05-06 00:08:46 +00002202 unsigned long ansec, mnsec, cnsec;
Eddie Elizondob3966632019-11-05 07:16:14 -08002203 PyObject *StatResultType = _posixstate_global->StatResultType;
2204 PyObject *v = PyStructSequence_New((PyTypeObject *)StatResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +00002205 if (v == NULL)
2206 return NULL;
Fred Drake699f3522000-06-29 21:12:41 +00002207
Victor Stinner8c62be82010-05-06 00:08:46 +00002208 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode));
Victor Stinner0f6d7332017-03-09 17:34:28 +01002209 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(st->st_ino));
xdegaye50e86032017-05-22 11:15:08 +02002210 PyStructSequence_SET_ITEM(v, 1, PyLong_FromUnsignedLongLong(st->st_ino));
Serhiy Storchaka404fa922013-01-02 18:22:23 +02002211#ifdef MS_WINDOWS
2212 PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002213#else
Serhiy Storchakab2653b32015-01-18 11:12:11 +02002214 PyStructSequence_SET_ITEM(v, 2, _PyLong_FromDev(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002215#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002216 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02002217#if defined(MS_WINDOWS)
2218 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong(0));
2219 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong(0));
2220#else
2221 PyStructSequence_SET_ITEM(v, 4, _PyLong_FromUid(st->st_uid));
2222 PyStructSequence_SET_ITEM(v, 5, _PyLong_FromGid(st->st_gid));
2223#endif
xdegaye50e86032017-05-22 11:15:08 +02002224 Py_BUILD_ASSERT(sizeof(long long) >= sizeof(st->st_size));
2225 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLongLong(st->st_size));
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002226
Martin v. Löwis14694662006-02-03 12:54:16 +00002227#if defined(HAVE_STAT_TV_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002228 ansec = st->st_atim.tv_nsec;
2229 mnsec = st->st_mtim.tv_nsec;
2230 cnsec = st->st_ctim.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002231#elif defined(HAVE_STAT_TV_NSEC2)
Victor Stinner8c62be82010-05-06 00:08:46 +00002232 ansec = st->st_atimespec.tv_nsec;
2233 mnsec = st->st_mtimespec.tv_nsec;
2234 cnsec = st->st_ctimespec.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002235#elif defined(HAVE_STAT_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002236 ansec = st->st_atime_nsec;
2237 mnsec = st->st_mtime_nsec;
2238 cnsec = st->st_ctime_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002239#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002240 ansec = mnsec = cnsec = 0;
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002241#endif
Victor Stinner4195b5c2012-02-08 23:03:19 +01002242 fill_time(v, 7, st->st_atime, ansec);
2243 fill_time(v, 8, st->st_mtime, mnsec);
2244 fill_time(v, 9, st->st_ctime, cnsec);
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002245
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002246#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00002247 PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
2248 PyLong_FromLong((long)st->st_blksize));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002249#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002250#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00002251 PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
2252 PyLong_FromLong((long)st->st_blocks));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002253#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002254#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00002255 PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
2256 PyLong_FromLong((long)st->st_rdev));
Fred Drake699f3522000-06-29 21:12:41 +00002257#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002258#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00002259 PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
2260 PyLong_FromLong((long)st->st_gen));
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002261#endif
2262#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00002263 {
Victor Stinner4195b5c2012-02-08 23:03:19 +01002264 PyObject *val;
2265 unsigned long bsec,bnsec;
2266 bsec = (long)st->st_birthtime;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002267#ifdef HAVE_STAT_TV_NSEC2
Victor Stinner4195b5c2012-02-08 23:03:19 +01002268 bnsec = st->st_birthtimespec.tv_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002269#else
Victor Stinner4195b5c2012-02-08 23:03:19 +01002270 bnsec = 0;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002271#endif
Victor Stinner01b5aab2017-10-24 02:02:00 -07002272 val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
Victor Stinner4195b5c2012-02-08 23:03:19 +01002273 PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
2274 val);
Victor Stinner8c62be82010-05-06 00:08:46 +00002275 }
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002276#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002277#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00002278 PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
2279 PyLong_FromLong((long)st->st_flags));
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002280#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05002281#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2282 PyStructSequence_SET_ITEM(v, ST_FILE_ATTRIBUTES_IDX,
2283 PyLong_FromUnsignedLong(st->st_file_attributes));
2284#endif
jcea6c51d512018-01-28 14:00:08 +01002285#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2286 PyStructSequence_SET_ITEM(v, ST_FSTYPE_IDX,
2287 PyUnicode_FromString(st->st_fstype));
2288#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002289#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2290 PyStructSequence_SET_ITEM(v, ST_REPARSE_TAG_IDX,
2291 PyLong_FromUnsignedLong(st->st_reparse_tag));
2292#endif
Fred Drake699f3522000-06-29 21:12:41 +00002293
Victor Stinner8c62be82010-05-06 00:08:46 +00002294 if (PyErr_Occurred()) {
2295 Py_DECREF(v);
2296 return NULL;
2297 }
Fred Drake699f3522000-06-29 21:12:41 +00002298
Victor Stinner8c62be82010-05-06 00:08:46 +00002299 return v;
Fred Drake699f3522000-06-29 21:12:41 +00002300}
2301
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002302/* POSIX methods */
2303
Guido van Rossum94f6f721999-01-06 18:42:14 +00002304
2305static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002306posix_do_stat(const char *function_name, path_t *path,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002307 int dir_fd, int follow_symlinks)
Guido van Rossum94f6f721999-01-06 18:42:14 +00002308{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002309 STRUCT_STAT st;
2310 int result;
2311
2312#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
2313 if (follow_symlinks_specified(function_name, follow_symlinks))
2314 return NULL;
2315#endif
2316
2317 if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
2318 dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
2319 fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
2320 return NULL;
2321
2322 Py_BEGIN_ALLOW_THREADS
2323 if (path->fd != -1)
2324 result = FSTAT(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002325#ifdef MS_WINDOWS
Steve Dower513d7472016-09-08 10:41:50 -07002326 else if (follow_symlinks)
Steve Dowercc16be82016-09-08 10:35:16 -07002327 result = win32_stat(path->wide, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002328 else
Steve Dowercc16be82016-09-08 10:35:16 -07002329 result = win32_lstat(path->wide, &st);
2330#else
2331 else
2332#if defined(HAVE_LSTAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002333 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
2334 result = LSTAT(path->narrow, &st);
2335 else
Steve Dowercc16be82016-09-08 10:35:16 -07002336#endif /* HAVE_LSTAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002337#ifdef HAVE_FSTATAT
2338 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks)
2339 result = fstatat(dir_fd, path->narrow, &st,
2340 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2341 else
Steve Dowercc16be82016-09-08 10:35:16 -07002342#endif /* HAVE_FSTATAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002343 result = STAT(path->narrow, &st);
Steve Dowercc16be82016-09-08 10:35:16 -07002344#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002345 Py_END_ALLOW_THREADS
2346
Victor Stinner292c8352012-10-30 02:17:38 +01002347 if (result != 0) {
2348 return path_error(path);
2349 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07002350
2351 return _pystat_fromstructstat(&st);
2352}
2353
Larry Hastings2f936352014-08-05 14:04:04 +10002354/*[python input]
2355
2356for s in """
2357
2358FACCESSAT
2359FCHMODAT
2360FCHOWNAT
2361FSTATAT
2362LINKAT
2363MKDIRAT
2364MKFIFOAT
2365MKNODAT
2366OPENAT
2367READLINKAT
2368SYMLINKAT
2369UNLINKAT
2370
2371""".strip().split():
2372 s = s.strip()
2373 print("""
2374#ifdef HAVE_{s}
2375 #define {s}_DIR_FD_CONVERTER dir_fd_converter
Larry Hastings31826802013-10-19 00:09:25 -07002376#else
Larry Hastings2f936352014-08-05 14:04:04 +10002377 #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings31826802013-10-19 00:09:25 -07002378#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002379""".rstrip().format(s=s))
2380
2381for s in """
2382
2383FCHDIR
2384FCHMOD
2385FCHOWN
2386FDOPENDIR
2387FEXECVE
2388FPATHCONF
2389FSTATVFS
2390FTRUNCATE
2391
2392""".strip().split():
2393 s = s.strip()
2394 print("""
2395#ifdef HAVE_{s}
2396 #define PATH_HAVE_{s} 1
2397#else
2398 #define PATH_HAVE_{s} 0
2399#endif
2400
2401""".rstrip().format(s=s))
2402[python start generated code]*/
2403
2404#ifdef HAVE_FACCESSAT
2405 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
2406#else
2407 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
2408#endif
2409
2410#ifdef HAVE_FCHMODAT
2411 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
2412#else
2413 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
2414#endif
2415
2416#ifdef HAVE_FCHOWNAT
2417 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
2418#else
2419 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
2420#endif
2421
2422#ifdef HAVE_FSTATAT
2423 #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
2424#else
2425 #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
2426#endif
2427
2428#ifdef HAVE_LINKAT
2429 #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
2430#else
2431 #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2432#endif
2433
2434#ifdef HAVE_MKDIRAT
2435 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
2436#else
2437 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
2438#endif
2439
2440#ifdef HAVE_MKFIFOAT
2441 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
2442#else
2443 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
2444#endif
2445
2446#ifdef HAVE_MKNODAT
2447 #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
2448#else
2449 #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
2450#endif
2451
2452#ifdef HAVE_OPENAT
2453 #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
2454#else
2455 #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
2456#endif
2457
2458#ifdef HAVE_READLINKAT
2459 #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
2460#else
2461 #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2462#endif
2463
2464#ifdef HAVE_SYMLINKAT
2465 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
2466#else
2467 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2468#endif
2469
2470#ifdef HAVE_UNLINKAT
2471 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
2472#else
2473 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2474#endif
2475
2476#ifdef HAVE_FCHDIR
2477 #define PATH_HAVE_FCHDIR 1
2478#else
2479 #define PATH_HAVE_FCHDIR 0
2480#endif
2481
2482#ifdef HAVE_FCHMOD
2483 #define PATH_HAVE_FCHMOD 1
2484#else
2485 #define PATH_HAVE_FCHMOD 0
2486#endif
2487
2488#ifdef HAVE_FCHOWN
2489 #define PATH_HAVE_FCHOWN 1
2490#else
2491 #define PATH_HAVE_FCHOWN 0
2492#endif
2493
2494#ifdef HAVE_FDOPENDIR
2495 #define PATH_HAVE_FDOPENDIR 1
2496#else
2497 #define PATH_HAVE_FDOPENDIR 0
2498#endif
2499
2500#ifdef HAVE_FEXECVE
2501 #define PATH_HAVE_FEXECVE 1
2502#else
2503 #define PATH_HAVE_FEXECVE 0
2504#endif
2505
2506#ifdef HAVE_FPATHCONF
2507 #define PATH_HAVE_FPATHCONF 1
2508#else
2509 #define PATH_HAVE_FPATHCONF 0
2510#endif
2511
2512#ifdef HAVE_FSTATVFS
2513 #define PATH_HAVE_FSTATVFS 1
2514#else
2515 #define PATH_HAVE_FSTATVFS 0
2516#endif
2517
2518#ifdef HAVE_FTRUNCATE
2519 #define PATH_HAVE_FTRUNCATE 1
2520#else
2521 #define PATH_HAVE_FTRUNCATE 0
2522#endif
2523/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
Larry Hastings31826802013-10-19 00:09:25 -07002524
Steve Dowerfe0a41a2015-03-20 19:50:46 -07002525#ifdef MS_WINDOWS
2526 #undef PATH_HAVE_FTRUNCATE
2527 #define PATH_HAVE_FTRUNCATE 1
2528#endif
Larry Hastings31826802013-10-19 00:09:25 -07002529
Larry Hastings61272b72014-01-07 12:41:53 -08002530/*[python input]
Larry Hastings31826802013-10-19 00:09:25 -07002531
2532class path_t_converter(CConverter):
2533
2534 type = "path_t"
2535 impl_by_reference = True
2536 parse_by_reference = True
2537
2538 converter = 'path_converter'
2539
2540 def converter_init(self, *, allow_fd=False, nullable=False):
Larry Hastings31826802013-10-19 00:09:25 -07002541 # right now path_t doesn't support default values.
2542 # to support a default value, you'll need to override initialize().
Larry Hastings2f936352014-08-05 14:04:04 +10002543 if self.default not in (unspecified, None):
Larry Hastings7726ac92014-01-31 22:03:12 -08002544 fail("Can't specify a default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002545
Larry Hastings2f936352014-08-05 14:04:04 +10002546 if self.c_default not in (None, 'Py_None'):
2547 raise RuntimeError("Can't specify a c_default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002548
2549 self.nullable = nullable
2550 self.allow_fd = allow_fd
2551
Larry Hastings7726ac92014-01-31 22:03:12 -08002552 def pre_render(self):
2553 def strify(value):
Larry Hastings2f936352014-08-05 14:04:04 +10002554 if isinstance(value, str):
2555 return value
Larry Hastings7726ac92014-01-31 22:03:12 -08002556 return str(int(bool(value)))
2557
2558 # add self.py_name here when merging with posixmodule conversion
Larry Hastings2f936352014-08-05 14:04:04 +10002559 self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
Larry Hastings31826802013-10-19 00:09:25 -07002560 self.function.name,
Larry Hastings2f936352014-08-05 14:04:04 +10002561 self.name,
Larry Hastings7726ac92014-01-31 22:03:12 -08002562 strify(self.nullable),
2563 strify(self.allow_fd),
Larry Hastings31826802013-10-19 00:09:25 -07002564 )
2565
2566 def cleanup(self):
2567 return "path_cleanup(&" + self.name + ");\n"
2568
2569
2570class dir_fd_converter(CConverter):
2571 type = 'int'
Larry Hastings31826802013-10-19 00:09:25 -07002572
Larry Hastings2f936352014-08-05 14:04:04 +10002573 def converter_init(self, requires=None):
Larry Hastings31826802013-10-19 00:09:25 -07002574 if self.default in (unspecified, None):
2575 self.c_default = 'DEFAULT_DIR_FD'
Larry Hastings2f936352014-08-05 14:04:04 +10002576 if isinstance(requires, str):
2577 self.converter = requires.upper() + '_DIR_FD_CONVERTER'
2578 else:
2579 self.converter = 'dir_fd_converter'
Larry Hastings31826802013-10-19 00:09:25 -07002580
Larry Hastings2f936352014-08-05 14:04:04 +10002581class fildes_converter(CConverter):
2582 type = 'int'
2583 converter = 'fildes_converter'
2584
2585class uid_t_converter(CConverter):
2586 type = "uid_t"
2587 converter = '_Py_Uid_Converter'
2588
2589class gid_t_converter(CConverter):
2590 type = "gid_t"
2591 converter = '_Py_Gid_Converter'
2592
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02002593class dev_t_converter(CConverter):
2594 type = 'dev_t'
2595 converter = '_Py_Dev_Converter'
2596
2597class dev_t_return_converter(unsigned_long_return_converter):
2598 type = 'dev_t'
2599 conversion_fn = '_PyLong_FromDev'
2600 unsigned_cast = '(dev_t)'
2601
Larry Hastings2f936352014-08-05 14:04:04 +10002602class FSConverter_converter(CConverter):
2603 type = 'PyObject *'
2604 converter = 'PyUnicode_FSConverter'
2605 def converter_init(self):
2606 if self.default is not unspecified:
2607 fail("FSConverter_converter does not support default values")
2608 self.c_default = 'NULL'
2609
2610 def cleanup(self):
2611 return "Py_XDECREF(" + self.name + ");\n"
2612
2613class pid_t_converter(CConverter):
2614 type = 'pid_t'
2615 format_unit = '" _Py_PARSE_PID "'
2616
2617class idtype_t_converter(int_converter):
2618 type = 'idtype_t'
2619
2620class id_t_converter(CConverter):
2621 type = 'id_t'
2622 format_unit = '" _Py_PARSE_PID "'
2623
Benjamin Petersonca470632016-09-06 13:47:26 -07002624class intptr_t_converter(CConverter):
2625 type = 'intptr_t'
Larry Hastings2f936352014-08-05 14:04:04 +10002626 format_unit = '" _Py_PARSE_INTPTR "'
2627
2628class Py_off_t_converter(CConverter):
2629 type = 'Py_off_t'
2630 converter = 'Py_off_t_converter'
2631
2632class Py_off_t_return_converter(long_return_converter):
2633 type = 'Py_off_t'
2634 conversion_fn = 'PyLong_FromPy_off_t'
2635
2636class path_confname_converter(CConverter):
2637 type="int"
2638 converter="conv_path_confname"
2639
2640class confstr_confname_converter(path_confname_converter):
2641 converter='conv_confstr_confname'
2642
2643class sysconf_confname_converter(path_confname_converter):
2644 converter="conv_sysconf_confname"
2645
2646class sched_param_converter(CConverter):
2647 type = 'struct sched_param'
2648 converter = 'convert_sched_param'
2649 impl_by_reference = True;
Larry Hastings31826802013-10-19 00:09:25 -07002650
Larry Hastings61272b72014-01-07 12:41:53 -08002651[python start generated code]*/
Victor Stinner581139c2016-09-06 15:54:20 -07002652/*[python end generated code: output=da39a3ee5e6b4b0d input=418fce0e01144461]*/
Larry Hastings31826802013-10-19 00:09:25 -07002653
Larry Hastings61272b72014-01-07 12:41:53 -08002654/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002655
Larry Hastings2a727912014-01-16 11:32:01 -08002656os.stat
Larry Hastings31826802013-10-19 00:09:25 -07002657
2658 path : path_t(allow_fd=True)
BNMetricsb9427072018-11-02 15:20:19 +00002659 Path to be examined; can be string, bytes, a path-like object or
Xiang Zhang4459e002017-01-22 13:04:17 +08002660 open-file-descriptor int.
Larry Hastings31826802013-10-19 00:09:25 -07002661
2662 *
2663
Larry Hastings2f936352014-08-05 14:04:04 +10002664 dir_fd : dir_fd(requires='fstatat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002665 If not None, it should be a file descriptor open to a directory,
2666 and path should be a relative string; path will then be relative to
2667 that directory.
2668
2669 follow_symlinks: bool = True
2670 If False, and the last element of the path is a symbolic link,
2671 stat will examine the symbolic link itself instead of the file
2672 the link points to.
2673
2674Perform a stat system call on the given path.
2675
2676dir_fd and follow_symlinks may not be implemented
2677 on your platform. If they are unavailable, using them will raise a
2678 NotImplementedError.
2679
2680It's an error to use dir_fd or follow_symlinks when specifying path as
2681 an open file descriptor.
2682
Larry Hastings61272b72014-01-07 12:41:53 -08002683[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002684
Larry Hastings31826802013-10-19 00:09:25 -07002685static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002686os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002687/*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
Larry Hastings31826802013-10-19 00:09:25 -07002688{
2689 return posix_do_stat("stat", path, dir_fd, follow_symlinks);
2690}
2691
Larry Hastings2f936352014-08-05 14:04:04 +10002692
2693/*[clinic input]
2694os.lstat
2695
2696 path : path_t
2697
2698 *
2699
2700 dir_fd : dir_fd(requires='fstatat') = None
2701
2702Perform a stat system call on the given path, without following symbolic links.
2703
2704Like stat(), but do not follow symbolic links.
2705Equivalent to stat(path, follow_symlinks=False).
2706[clinic start generated code]*/
2707
Larry Hastings2f936352014-08-05 14:04:04 +10002708static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002709os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
2710/*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002711{
2712 int follow_symlinks = 0;
2713 return posix_do_stat("lstat", path, dir_fd, follow_symlinks);
2714}
Larry Hastings31826802013-10-19 00:09:25 -07002715
Larry Hastings2f936352014-08-05 14:04:04 +10002716
Larry Hastings61272b72014-01-07 12:41:53 -08002717/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10002718os.access -> bool
Larry Hastings31826802013-10-19 00:09:25 -07002719
Benjamin Peterson768f3b42016-09-05 15:29:33 -07002720 path: path_t
BNMetricsb9427072018-11-02 15:20:19 +00002721 Path to be tested; can be string, bytes, or a path-like object.
Larry Hastings31826802013-10-19 00:09:25 -07002722
2723 mode: int
2724 Operating-system mode bitfield. Can be F_OK to test existence,
2725 or the inclusive-OR of R_OK, W_OK, and X_OK.
2726
2727 *
2728
Larry Hastings2f936352014-08-05 14:04:04 +10002729 dir_fd : dir_fd(requires='faccessat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002730 If not None, it should be a file descriptor open to a directory,
2731 and path should be relative; path will then be relative to that
2732 directory.
2733
2734 effective_ids: bool = False
2735 If True, access will use the effective uid/gid instead of
2736 the real uid/gid.
2737
2738 follow_symlinks: bool = True
2739 If False, and the last element of the path is a symbolic link,
2740 access will examine the symbolic link itself instead of the file
2741 the link points to.
2742
2743Use the real uid/gid to test for access to a path.
2744
2745{parameters}
2746dir_fd, effective_ids, and follow_symlinks may not be implemented
2747 on your platform. If they are unavailable, using them will raise a
2748 NotImplementedError.
2749
2750Note that most operations will use the effective uid/gid, therefore this
2751 routine can be used in a suid/sgid environment to test if the invoking user
2752 has the specified access to the path.
2753
Larry Hastings61272b72014-01-07 12:41:53 -08002754[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002755
Larry Hastings2f936352014-08-05 14:04:04 +10002756static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002757os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002758 int effective_ids, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002759/*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
Larry Hastings31826802013-10-19 00:09:25 -07002760{
Larry Hastings2f936352014-08-05 14:04:04 +10002761 int return_value;
Victor Stinner8c62be82010-05-06 00:08:46 +00002762
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002763#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002764 DWORD attr;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002765#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07002766 int result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002767#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07002768
Larry Hastings9cf065c2012-06-22 16:30:09 -07002769#ifndef HAVE_FACCESSAT
2770 if (follow_symlinks_specified("access", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002771 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002772
2773 if (effective_ids) {
2774 argument_unavailable_error("access", "effective_ids");
Larry Hastings2f936352014-08-05 14:04:04 +10002775 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002776 }
2777#endif
2778
2779#ifdef MS_WINDOWS
2780 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002781 attr = GetFileAttributesW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002782 Py_END_ALLOW_THREADS
2783
2784 /*
Georg Brandlf7875592012-06-24 13:58:31 +02002785 * Access is possible if
Larry Hastings9cf065c2012-06-22 16:30:09 -07002786 * * we didn't get a -1, and
2787 * * write access wasn't requested,
2788 * * or the file isn't read-only,
2789 * * or it's a directory.
2790 * (Directories cannot be read-only on Windows.)
2791 */
Larry Hastings2f936352014-08-05 14:04:04 +10002792 return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
Georg Brandl5bb7aa92012-06-23 12:48:40 +02002793 (!(mode & 2) ||
Larry Hastings9cf065c2012-06-22 16:30:09 -07002794 !(attr & FILE_ATTRIBUTE_READONLY) ||
Larry Hastings2f936352014-08-05 14:04:04 +10002795 (attr & FILE_ATTRIBUTE_DIRECTORY));
Larry Hastings9cf065c2012-06-22 16:30:09 -07002796#else
2797
2798 Py_BEGIN_ALLOW_THREADS
2799#ifdef HAVE_FACCESSAT
2800 if ((dir_fd != DEFAULT_DIR_FD) ||
2801 effective_ids ||
2802 !follow_symlinks) {
2803 int flags = 0;
2804 if (!follow_symlinks)
2805 flags |= AT_SYMLINK_NOFOLLOW;
2806 if (effective_ids)
2807 flags |= AT_EACCESS;
Larry Hastings31826802013-10-19 00:09:25 -07002808 result = faccessat(dir_fd, path->narrow, mode, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002809 }
2810 else
2811#endif
Larry Hastings31826802013-10-19 00:09:25 -07002812 result = access(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002813 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10002814 return_value = !result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002815#endif
2816
Larry Hastings9cf065c2012-06-22 16:30:09 -07002817 return return_value;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002818}
2819
Guido van Rossumd371ff11999-01-25 16:12:23 +00002820#ifndef F_OK
2821#define F_OK 0
2822#endif
2823#ifndef R_OK
2824#define R_OK 4
2825#endif
2826#ifndef W_OK
2827#define W_OK 2
2828#endif
2829#ifndef X_OK
2830#define X_OK 1
2831#endif
2832
Larry Hastings31826802013-10-19 00:09:25 -07002833
Guido van Rossumd371ff11999-01-25 16:12:23 +00002834#ifdef HAVE_TTYNAME
Larry Hastings61272b72014-01-07 12:41:53 -08002835/*[clinic input]
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002836os.ttyname
Larry Hastings31826802013-10-19 00:09:25 -07002837
2838 fd: int
2839 Integer file descriptor handle.
2840
2841 /
2842
2843Return the name of the terminal device connected to 'fd'.
Larry Hastings61272b72014-01-07 12:41:53 -08002844[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002845
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002846static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002847os_ttyname_impl(PyObject *module, int fd)
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002848/*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
Larry Hastings31826802013-10-19 00:09:25 -07002849{
Guido van Rossum94f6f721999-01-06 18:42:14 +00002850
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002851 long size = sysconf(_SC_TTY_NAME_MAX);
2852 if (size == -1) {
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002853 return posix_error();
2854 }
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002855 char *buffer = (char *)PyMem_RawMalloc(size);
2856 if (buffer == NULL) {
2857 return PyErr_NoMemory();
2858 }
2859 int ret = ttyname_r(fd, buffer, size);
2860 if (ret != 0) {
2861 PyMem_RawFree(buffer);
2862 errno = ret;
2863 return posix_error();
2864 }
2865 PyObject *res = PyUnicode_DecodeFSDefault(buffer);
2866 PyMem_RawFree(buffer);
2867 return res;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002868}
Guido van Rossumd371ff11999-01-25 16:12:23 +00002869#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +00002870
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002871#ifdef HAVE_CTERMID
Larry Hastings2f936352014-08-05 14:04:04 +10002872/*[clinic input]
2873os.ctermid
2874
2875Return the name of the controlling terminal for this process.
2876[clinic start generated code]*/
2877
Larry Hastings2f936352014-08-05 14:04:04 +10002878static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002879os_ctermid_impl(PyObject *module)
2880/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002881{
Victor Stinner8c62be82010-05-06 00:08:46 +00002882 char *ret;
2883 char buffer[L_ctermid];
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002884
Greg Wardb48bc172000-03-01 21:51:56 +00002885#ifdef USE_CTERMID_R
Victor Stinner8c62be82010-05-06 00:08:46 +00002886 ret = ctermid_r(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002887#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002888 ret = ctermid(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002889#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002890 if (ret == NULL)
2891 return posix_error();
Victor Stinner5fe6de82010-08-15 09:12:51 +00002892 return PyUnicode_DecodeFSDefault(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002893}
Larry Hastings2f936352014-08-05 14:04:04 +10002894#endif /* HAVE_CTERMID */
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002895
Larry Hastings2f936352014-08-05 14:04:04 +10002896
2897/*[clinic input]
2898os.chdir
2899
2900 path: path_t(allow_fd='PATH_HAVE_FCHDIR')
2901
2902Change the current working directory to the specified path.
2903
2904path may always be specified as a string.
2905On some platforms, path may also be specified as an open file descriptor.
2906 If this functionality is unavailable, using it raises an exception.
2907[clinic start generated code]*/
2908
Larry Hastings2f936352014-08-05 14:04:04 +10002909static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002910os_chdir_impl(PyObject *module, path_t *path)
2911/*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002912{
2913 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002914
Saiyang Gou7514f4f2020-02-12 23:47:42 -08002915 if (PySys_Audit("os.chdir", "(O)", path->object) < 0) {
2916 return NULL;
2917 }
2918
Larry Hastings9cf065c2012-06-22 16:30:09 -07002919 Py_BEGIN_ALLOW_THREADS
2920#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07002921 /* on unix, success = 0, on windows, success = !0 */
2922 result = !win32_wchdir(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002923#else
2924#ifdef HAVE_FCHDIR
Larry Hastings2f936352014-08-05 14:04:04 +10002925 if (path->fd != -1)
2926 result = fchdir(path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002927 else
2928#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002929 result = chdir(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002930#endif
2931 Py_END_ALLOW_THREADS
2932
2933 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002934 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002935 }
2936
Larry Hastings2f936352014-08-05 14:04:04 +10002937 Py_RETURN_NONE;
2938}
2939
2940
2941#ifdef HAVE_FCHDIR
2942/*[clinic input]
2943os.fchdir
2944
2945 fd: fildes
2946
2947Change to the directory of the given file descriptor.
2948
2949fd must be opened on a directory, not a file.
2950Equivalent to os.chdir(fd).
2951
2952[clinic start generated code]*/
2953
Fred Drake4d1e64b2002-04-15 19:40:07 +00002954static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002955os_fchdir_impl(PyObject *module, int fd)
2956/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
Fred Drake4d1e64b2002-04-15 19:40:07 +00002957{
Saiyang Gou7514f4f2020-02-12 23:47:42 -08002958 if (PySys_Audit("os.chdir", "(i)", fd) < 0) {
2959 return NULL;
2960 }
Larry Hastings2f936352014-08-05 14:04:04 +10002961 return posix_fildes_fd(fd, fchdir);
Fred Drake4d1e64b2002-04-15 19:40:07 +00002962}
2963#endif /* HAVE_FCHDIR */
2964
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00002965
Larry Hastings2f936352014-08-05 14:04:04 +10002966/*[clinic input]
2967os.chmod
2968
2969 path: path_t(allow_fd='PATH_HAVE_FCHMOD')
BNMetricsb9427072018-11-02 15:20:19 +00002970 Path to be modified. May always be specified as a str, bytes, or a path-like object.
Larry Hastings2f936352014-08-05 14:04:04 +10002971 On some platforms, path may also be specified as an open file descriptor.
2972 If this functionality is unavailable, using it raises an exception.
2973
2974 mode: int
2975 Operating-system mode bitfield.
2976
2977 *
2978
2979 dir_fd : dir_fd(requires='fchmodat') = None
2980 If not None, it should be a file descriptor open to a directory,
2981 and path should be relative; path will then be relative to that
2982 directory.
2983
2984 follow_symlinks: bool = True
2985 If False, and the last element of the path is a symbolic link,
2986 chmod will modify the symbolic link itself instead of the file
2987 the link points to.
2988
2989Change the access permissions of a file.
2990
2991It is an error to use dir_fd or follow_symlinks when specifying path as
2992 an open file descriptor.
2993dir_fd and follow_symlinks may not be implemented on your platform.
2994 If they are unavailable, using them will raise a NotImplementedError.
2995
2996[clinic start generated code]*/
2997
Larry Hastings2f936352014-08-05 14:04:04 +10002998static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002999os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003000 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003001/*[clinic end generated code: output=5cf6a94915cc7bff input=989081551c00293b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003002{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003003 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003004
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003005#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003006 DWORD attr;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003007#endif
Hirokazu Yamamoto892a37a2009-06-28 11:07:03 +00003008
Larry Hastings9cf065c2012-06-22 16:30:09 -07003009#ifdef HAVE_FCHMODAT
3010 int fchmodat_nofollow_unsupported = 0;
3011#endif
3012
Larry Hastings9cf065c2012-06-22 16:30:09 -07003013#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
3014 if (follow_symlinks_specified("chmod", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003015 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003016#endif
3017
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003018 if (PySys_Audit("os.chmod", "Oii", path->object, mode,
3019 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
3020 return NULL;
3021 }
3022
Larry Hastings9cf065c2012-06-22 16:30:09 -07003023#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003024 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003025 attr = GetFileAttributesW(path->wide);
Tim Golden23005082013-10-25 11:22:37 +01003026 if (attr == INVALID_FILE_ATTRIBUTES)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003027 result = 0;
3028 else {
3029 if (mode & _S_IWRITE)
Victor Stinner8c62be82010-05-06 00:08:46 +00003030 attr &= ~FILE_ATTRIBUTE_READONLY;
3031 else
3032 attr |= FILE_ATTRIBUTE_READONLY;
Steve Dowercc16be82016-09-08 10:35:16 -07003033 result = SetFileAttributesW(path->wide, attr);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003034 }
3035 Py_END_ALLOW_THREADS
3036
3037 if (!result) {
Larry Hastings2f936352014-08-05 14:04:04 +10003038 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003039 }
3040#else /* MS_WINDOWS */
3041 Py_BEGIN_ALLOW_THREADS
3042#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003043 if (path->fd != -1)
3044 result = fchmod(path->fd, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003045 else
3046#endif
3047#ifdef HAVE_LCHMOD
3048 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003049 result = lchmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003050 else
3051#endif
3052#ifdef HAVE_FCHMODAT
3053 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
3054 /*
3055 * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
3056 * The documentation specifically shows how to use it,
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003057 * and then says it isn't implemented yet.
3058 * (true on linux with glibc 2.15, and openindiana 3.x)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003059 *
3060 * Once it is supported, os.chmod will automatically
3061 * support dir_fd and follow_symlinks=False. (Hopefully.)
3062 * Until then, we need to be careful what exception we raise.
3063 */
Larry Hastings2f936352014-08-05 14:04:04 +10003064 result = fchmodat(dir_fd, path->narrow, mode,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003065 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3066 /*
3067 * But wait! We can't throw the exception without allowing threads,
3068 * and we can't do that in this nested scope. (Macro trickery, sigh.)
3069 */
3070 fchmodat_nofollow_unsupported =
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003071 result &&
3072 ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
3073 !follow_symlinks;
Victor Stinner8c62be82010-05-06 00:08:46 +00003074 }
3075 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00003076#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003077 result = chmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003078 Py_END_ALLOW_THREADS
3079
3080 if (result) {
3081#ifdef HAVE_FCHMODAT
3082 if (fchmodat_nofollow_unsupported) {
3083 if (dir_fd != DEFAULT_DIR_FD)
3084 dir_fd_and_follow_symlinks_invalid("chmod",
3085 dir_fd, follow_symlinks);
3086 else
3087 follow_symlinks_specified("chmod", follow_symlinks);
Anthony Sottile233ef242017-12-14 08:57:55 -08003088 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003089 }
3090 else
3091#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003092 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003093 }
3094#endif
3095
Larry Hastings2f936352014-08-05 14:04:04 +10003096 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003097}
3098
Larry Hastings9cf065c2012-06-22 16:30:09 -07003099
Christian Heimes4e30a842007-11-30 22:12:06 +00003100#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003101/*[clinic input]
3102os.fchmod
3103
3104 fd: int
3105 mode: int
3106
3107Change the access permissions of the file given by file descriptor fd.
3108
3109Equivalent to os.chmod(fd, mode).
3110[clinic start generated code]*/
3111
Larry Hastings2f936352014-08-05 14:04:04 +10003112static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003113os_fchmod_impl(PyObject *module, int fd, int mode)
3114/*[clinic end generated code: output=afd9bc05b4e426b3 input=8ab11975ca01ee5b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003115{
3116 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003117 int async_err = 0;
3118
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003119 if (PySys_Audit("os.chmod", "iii", fd, mode, -1) < 0) {
3120 return NULL;
3121 }
3122
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003123 do {
3124 Py_BEGIN_ALLOW_THREADS
3125 res = fchmod(fd, mode);
3126 Py_END_ALLOW_THREADS
3127 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3128 if (res != 0)
3129 return (!async_err) ? posix_error() : NULL;
3130
Victor Stinner8c62be82010-05-06 00:08:46 +00003131 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003132}
3133#endif /* HAVE_FCHMOD */
3134
Larry Hastings2f936352014-08-05 14:04:04 +10003135
Christian Heimes4e30a842007-11-30 22:12:06 +00003136#ifdef HAVE_LCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003137/*[clinic input]
3138os.lchmod
3139
3140 path: path_t
3141 mode: int
3142
3143Change the access permissions of a file, without following symbolic links.
3144
3145If path is a symlink, this affects the link itself rather than the target.
3146Equivalent to chmod(path, mode, follow_symlinks=False)."
3147[clinic start generated code]*/
3148
Larry Hastings2f936352014-08-05 14:04:04 +10003149static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003150os_lchmod_impl(PyObject *module, path_t *path, int mode)
3151/*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003152{
Victor Stinner8c62be82010-05-06 00:08:46 +00003153 int res;
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003154 if (PySys_Audit("os.chmod", "Oii", path->object, mode, -1) < 0) {
3155 return NULL;
3156 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003157 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003158 res = lchmod(path->narrow, mode);
Victor Stinner8c62be82010-05-06 00:08:46 +00003159 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003160 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003161 path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003162 return NULL;
3163 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003164 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003165}
3166#endif /* HAVE_LCHMOD */
3167
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003168
Thomas Wouterscf297e42007-02-23 15:07:44 +00003169#ifdef HAVE_CHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003170/*[clinic input]
3171os.chflags
3172
3173 path: path_t
3174 flags: unsigned_long(bitwise=True)
3175 follow_symlinks: bool=True
3176
3177Set file flags.
3178
3179If follow_symlinks is False, and the last element of the path is a symbolic
3180 link, chflags will change flags on the symbolic link itself instead of the
3181 file the link points to.
3182follow_symlinks may not be implemented on your platform. If it is
3183unavailable, using it will raise a NotImplementedError.
3184
3185[clinic start generated code]*/
3186
Larry Hastings2f936352014-08-05 14:04:04 +10003187static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003188os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
Larry Hastings89964c42015-04-14 18:07:59 -04003189 int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003190/*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003191{
3192 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003193
3194#ifndef HAVE_LCHFLAGS
3195 if (follow_symlinks_specified("chflags", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003196 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003197#endif
3198
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003199 if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
3200 return NULL;
3201 }
3202
Victor Stinner8c62be82010-05-06 00:08:46 +00003203 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003204#ifdef HAVE_LCHFLAGS
3205 if (!follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +10003206 result = lchflags(path->narrow, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003207 else
3208#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003209 result = chflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003210 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003211
Larry Hastings2f936352014-08-05 14:04:04 +10003212 if (result)
3213 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003214
Larry Hastings2f936352014-08-05 14:04:04 +10003215 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003216}
3217#endif /* HAVE_CHFLAGS */
3218
Larry Hastings2f936352014-08-05 14:04:04 +10003219
Thomas Wouterscf297e42007-02-23 15:07:44 +00003220#ifdef HAVE_LCHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003221/*[clinic input]
3222os.lchflags
3223
3224 path: path_t
3225 flags: unsigned_long(bitwise=True)
3226
3227Set file flags.
3228
3229This function will not follow symbolic links.
3230Equivalent to chflags(path, flags, follow_symlinks=False).
3231[clinic start generated code]*/
3232
Larry Hastings2f936352014-08-05 14:04:04 +10003233static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003234os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
3235/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003236{
Victor Stinner8c62be82010-05-06 00:08:46 +00003237 int res;
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003238 if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
3239 return NULL;
3240 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003241 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003242 res = lchflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003243 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003244 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003245 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003246 }
Victor Stinner292c8352012-10-30 02:17:38 +01003247 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003248}
3249#endif /* HAVE_LCHFLAGS */
3250
Larry Hastings2f936352014-08-05 14:04:04 +10003251
Martin v. Löwis244edc82001-10-04 22:44:26 +00003252#ifdef HAVE_CHROOT
Larry Hastings2f936352014-08-05 14:04:04 +10003253/*[clinic input]
3254os.chroot
3255 path: path_t
3256
3257Change root directory to path.
3258
3259[clinic start generated code]*/
3260
Larry Hastings2f936352014-08-05 14:04:04 +10003261static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003262os_chroot_impl(PyObject *module, path_t *path)
3263/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003264{
3265 int res;
3266 Py_BEGIN_ALLOW_THREADS
3267 res = chroot(path->narrow);
3268 Py_END_ALLOW_THREADS
3269 if (res < 0)
3270 return path_error(path);
3271 Py_RETURN_NONE;
3272}
3273#endif /* HAVE_CHROOT */
3274
Martin v. Löwis244edc82001-10-04 22:44:26 +00003275
Guido van Rossum21142a01999-01-08 21:05:37 +00003276#ifdef HAVE_FSYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003277/*[clinic input]
3278os.fsync
3279
3280 fd: fildes
3281
3282Force write of fd to disk.
3283[clinic start generated code]*/
3284
Larry Hastings2f936352014-08-05 14:04:04 +10003285static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003286os_fsync_impl(PyObject *module, int fd)
3287/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003288{
3289 return posix_fildes_fd(fd, fsync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003290}
3291#endif /* HAVE_FSYNC */
3292
Larry Hastings2f936352014-08-05 14:04:04 +10003293
Ross Lagerwall7807c352011-03-17 20:20:30 +02003294#ifdef HAVE_SYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003295/*[clinic input]
3296os.sync
3297
3298Force write of everything to disk.
3299[clinic start generated code]*/
3300
Larry Hastings2f936352014-08-05 14:04:04 +10003301static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003302os_sync_impl(PyObject *module)
3303/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
Ross Lagerwall7807c352011-03-17 20:20:30 +02003304{
3305 Py_BEGIN_ALLOW_THREADS
3306 sync();
3307 Py_END_ALLOW_THREADS
3308 Py_RETURN_NONE;
3309}
Larry Hastings2f936352014-08-05 14:04:04 +10003310#endif /* HAVE_SYNC */
3311
Ross Lagerwall7807c352011-03-17 20:20:30 +02003312
Guido van Rossum21142a01999-01-08 21:05:37 +00003313#ifdef HAVE_FDATASYNC
Guido van Rossum7f58e2e2000-09-22 17:26:14 +00003314#ifdef __hpux
Guido van Rossumecc23b02000-09-22 16:01:05 +00003315extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
3316#endif
3317
Larry Hastings2f936352014-08-05 14:04:04 +10003318/*[clinic input]
3319os.fdatasync
3320
3321 fd: fildes
3322
3323Force write of fd to disk without forcing update of metadata.
3324[clinic start generated code]*/
3325
Larry Hastings2f936352014-08-05 14:04:04 +10003326static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003327os_fdatasync_impl(PyObject *module, int fd)
3328/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003329{
3330 return posix_fildes_fd(fd, fdatasync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003331}
3332#endif /* HAVE_FDATASYNC */
3333
3334
Fredrik Lundh10723342000-07-10 16:38:09 +00003335#ifdef HAVE_CHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003336/*[clinic input]
3337os.chown
3338
3339 path : path_t(allow_fd='PATH_HAVE_FCHOWN')
BNMetricsb9427072018-11-02 15:20:19 +00003340 Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
Larry Hastings2f936352014-08-05 14:04:04 +10003341
3342 uid: uid_t
3343
3344 gid: gid_t
3345
3346 *
3347
3348 dir_fd : dir_fd(requires='fchownat') = None
3349 If not None, it should be a file descriptor open to a directory,
3350 and path should be relative; path will then be relative to that
3351 directory.
3352
3353 follow_symlinks: bool = True
3354 If False, and the last element of the path is a symbolic link,
3355 stat will examine the symbolic link itself instead of the file
3356 the link points to.
3357
3358Change the owner and group id of path to the numeric uid and gid.\
3359
3360path may always be specified as a string.
3361On some platforms, path may also be specified as an open file descriptor.
3362 If this functionality is unavailable, using it raises an exception.
3363If dir_fd is not None, it should be a file descriptor open to a directory,
3364 and path should be relative; path will then be relative to that directory.
3365If follow_symlinks is False, and the last element of the path is a symbolic
3366 link, chown will modify the symbolic link itself instead of the file the
3367 link points to.
3368It is an error to use dir_fd or follow_symlinks when specifying path as
3369 an open file descriptor.
3370dir_fd and follow_symlinks may not be implemented on your platform.
3371 If they are unavailable, using them will raise a NotImplementedError.
3372
3373[clinic start generated code]*/
3374
Larry Hastings2f936352014-08-05 14:04:04 +10003375static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003376os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
Larry Hastings89964c42015-04-14 18:07:59 -04003377 int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003378/*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003379{
3380 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003381
3382#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
3383 if (follow_symlinks_specified("chown", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003384 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003385#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003386 if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
3387 fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
3388 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003389
3390#ifdef __APPLE__
3391 /*
3392 * This is for Mac OS X 10.3, which doesn't have lchown.
3393 * (But we still have an lchown symbol because of weak-linking.)
3394 * It doesn't have fchownat either. So there's no possibility
3395 * of a graceful failover.
Georg Brandlf7875592012-06-24 13:58:31 +02003396 */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003397 if ((!follow_symlinks) && (lchown == NULL)) {
3398 follow_symlinks_specified("chown", follow_symlinks);
Larry Hastings2f936352014-08-05 14:04:04 +10003399 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003400 }
3401#endif
3402
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003403 if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid,
3404 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
3405 return NULL;
3406 }
3407
Victor Stinner8c62be82010-05-06 00:08:46 +00003408 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003409#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003410 if (path->fd != -1)
3411 result = fchown(path->fd, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003412 else
3413#endif
3414#ifdef HAVE_LCHOWN
3415 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003416 result = lchown(path->narrow, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003417 else
3418#endif
3419#ifdef HAVE_FCHOWNAT
3420 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003421 result = fchownat(dir_fd, path->narrow, uid, gid,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003422 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3423 else
3424#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003425 result = chown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003426 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003427
Larry Hastings2f936352014-08-05 14:04:04 +10003428 if (result)
3429 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003430
Larry Hastings2f936352014-08-05 14:04:04 +10003431 Py_RETURN_NONE;
Guido van Rossumb6775db1994-08-01 11:34:53 +00003432}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003433#endif /* HAVE_CHOWN */
Guido van Rossumb6775db1994-08-01 11:34:53 +00003434
Larry Hastings2f936352014-08-05 14:04:04 +10003435
Christian Heimes4e30a842007-11-30 22:12:06 +00003436#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003437/*[clinic input]
3438os.fchown
3439
3440 fd: int
3441 uid: uid_t
3442 gid: gid_t
3443
3444Change the owner and group id of the file specified by file descriptor.
3445
3446Equivalent to os.chown(fd, uid, gid).
3447
3448[clinic start generated code]*/
3449
Larry Hastings2f936352014-08-05 14:04:04 +10003450static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003451os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
3452/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003453{
Victor Stinner8c62be82010-05-06 00:08:46 +00003454 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003455 int async_err = 0;
3456
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003457 if (PySys_Audit("os.chown", "iIIi", fd, uid, gid, -1) < 0) {
3458 return NULL;
3459 }
3460
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003461 do {
3462 Py_BEGIN_ALLOW_THREADS
3463 res = fchown(fd, uid, gid);
3464 Py_END_ALLOW_THREADS
3465 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3466 if (res != 0)
3467 return (!async_err) ? posix_error() : NULL;
3468
Victor Stinner8c62be82010-05-06 00:08:46 +00003469 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003470}
3471#endif /* HAVE_FCHOWN */
3472
Larry Hastings2f936352014-08-05 14:04:04 +10003473
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003474#ifdef HAVE_LCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003475/*[clinic input]
3476os.lchown
3477
3478 path : path_t
3479 uid: uid_t
3480 gid: gid_t
3481
3482Change the owner and group id of path to the numeric uid and gid.
3483
3484This function will not follow symbolic links.
3485Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
3486[clinic start generated code]*/
3487
Larry Hastings2f936352014-08-05 14:04:04 +10003488static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003489os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
3490/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003491{
Victor Stinner8c62be82010-05-06 00:08:46 +00003492 int res;
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003493 if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid, -1) < 0) {
3494 return NULL;
3495 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003496 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10003497 res = lchown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003498 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003499 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003500 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003501 }
Larry Hastings2f936352014-08-05 14:04:04 +10003502 Py_RETURN_NONE;
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003503}
3504#endif /* HAVE_LCHOWN */
3505
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003506
Barry Warsaw53699e91996-12-10 23:23:01 +00003507static PyObject *
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003508posix_getcwd(int use_bytes)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003509{
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003510#ifdef MS_WINDOWS
Victor Stinner689830e2019-06-26 17:31:12 +02003511 wchar_t wbuf[MAXPATHLEN];
3512 wchar_t *wbuf2 = wbuf;
3513 DWORD len;
3514
3515 Py_BEGIN_ALLOW_THREADS
3516 len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
3517 /* If the buffer is large enough, len does not include the
3518 terminating \0. If the buffer is too small, len includes
3519 the space needed for the terminator. */
3520 if (len >= Py_ARRAY_LENGTH(wbuf)) {
Victor Stinnerec3e20a2019-06-28 18:01:59 +02003521 if (len <= PY_SSIZE_T_MAX / sizeof(wchar_t)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02003522 wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00003523 }
Victor Stinner689830e2019-06-26 17:31:12 +02003524 else {
3525 wbuf2 = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003526 }
Victor Stinner689830e2019-06-26 17:31:12 +02003527 if (wbuf2) {
3528 len = GetCurrentDirectoryW(len, wbuf2);
Victor Stinner8c62be82010-05-06 00:08:46 +00003529 }
Victor Stinner689830e2019-06-26 17:31:12 +02003530 }
3531 Py_END_ALLOW_THREADS
3532
3533 if (!wbuf2) {
3534 PyErr_NoMemory();
3535 return NULL;
3536 }
3537 if (!len) {
Victor Stinnerb024e842012-10-31 22:24:06 +01003538 if (wbuf2 != wbuf)
Victor Stinnerb6404912013-07-07 16:21:41 +02003539 PyMem_RawFree(wbuf2);
Victor Stinner689830e2019-06-26 17:31:12 +02003540 return PyErr_SetFromWindowsErr(0);
Victor Stinner8c62be82010-05-06 00:08:46 +00003541 }
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01003542
Victor Stinner689830e2019-06-26 17:31:12 +02003543 PyObject *resobj = PyUnicode_FromWideChar(wbuf2, len);
3544 if (wbuf2 != wbuf) {
3545 PyMem_RawFree(wbuf2);
3546 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003547
Victor Stinner689830e2019-06-26 17:31:12 +02003548 if (use_bytes) {
3549 if (resobj == NULL) {
3550 return NULL;
3551 }
3552 Py_SETREF(resobj, PyUnicode_EncodeFSDefault(resobj));
3553 }
3554
3555 return resobj;
3556#else
3557 const size_t chunk = 1024;
3558
3559 char *buf = NULL;
3560 char *cwd = NULL;
3561 size_t buflen = 0;
3562
Victor Stinner8c62be82010-05-06 00:08:46 +00003563 Py_BEGIN_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003564 do {
Victor Stinner689830e2019-06-26 17:31:12 +02003565 char *newbuf;
3566 if (buflen <= PY_SSIZE_T_MAX - chunk) {
3567 buflen += chunk;
3568 newbuf = PyMem_RawRealloc(buf, buflen);
3569 }
3570 else {
3571 newbuf = NULL;
3572 }
3573 if (newbuf == NULL) {
3574 PyMem_RawFree(buf);
3575 buf = NULL;
Victor Stinnerc44f7072016-03-14 18:07:53 +01003576 break;
3577 }
Victor Stinner689830e2019-06-26 17:31:12 +02003578 buf = newbuf;
Victor Stinner4403d7d2015-04-25 00:16:10 +02003579
Victor Stinner4403d7d2015-04-25 00:16:10 +02003580 cwd = getcwd(buf, buflen);
3581 } while (cwd == NULL && errno == ERANGE);
Victor Stinner8c62be82010-05-06 00:08:46 +00003582 Py_END_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003583
Victor Stinner689830e2019-06-26 17:31:12 +02003584 if (buf == NULL) {
3585 return PyErr_NoMemory();
3586 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003587 if (cwd == NULL) {
3588 PyMem_RawFree(buf);
Victor Stinner8c62be82010-05-06 00:08:46 +00003589 return posix_error();
Victor Stinner4403d7d2015-04-25 00:16:10 +02003590 }
3591
Victor Stinner689830e2019-06-26 17:31:12 +02003592 PyObject *obj;
3593 if (use_bytes) {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003594 obj = PyBytes_FromStringAndSize(buf, strlen(buf));
Victor Stinner689830e2019-06-26 17:31:12 +02003595 }
3596 else {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003597 obj = PyUnicode_DecodeFSDefault(buf);
Victor Stinner689830e2019-06-26 17:31:12 +02003598 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003599 PyMem_RawFree(buf);
3600
3601 return obj;
Victor Stinner689830e2019-06-26 17:31:12 +02003602#endif /* !MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003603}
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003604
Larry Hastings2f936352014-08-05 14:04:04 +10003605
3606/*[clinic input]
3607os.getcwd
3608
3609Return a unicode string representing the current working directory.
3610[clinic start generated code]*/
3611
Larry Hastings2f936352014-08-05 14:04:04 +10003612static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003613os_getcwd_impl(PyObject *module)
3614/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003615{
3616 return posix_getcwd(0);
3617}
3618
Larry Hastings2f936352014-08-05 14:04:04 +10003619
3620/*[clinic input]
3621os.getcwdb
3622
3623Return a bytes string representing the current working directory.
3624[clinic start generated code]*/
3625
Larry Hastings2f936352014-08-05 14:04:04 +10003626static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003627os_getcwdb_impl(PyObject *module)
3628/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003629{
3630 return posix_getcwd(1);
3631}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003632
Larry Hastings2f936352014-08-05 14:04:04 +10003633
Larry Hastings9cf065c2012-06-22 16:30:09 -07003634#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
3635#define HAVE_LINK 1
3636#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003637
Guido van Rossumb6775db1994-08-01 11:34:53 +00003638#ifdef HAVE_LINK
Larry Hastings2f936352014-08-05 14:04:04 +10003639/*[clinic input]
3640
3641os.link
3642
3643 src : path_t
3644 dst : path_t
3645 *
3646 src_dir_fd : dir_fd = None
3647 dst_dir_fd : dir_fd = None
3648 follow_symlinks: bool = True
3649
3650Create a hard link to a file.
3651
3652If either src_dir_fd or dst_dir_fd is not None, it should be a file
3653 descriptor open to a directory, and the respective path string (src or dst)
3654 should be relative; the path will then be relative to that directory.
3655If follow_symlinks is False, and the last element of src is a symbolic
3656 link, link will create a link to the symbolic link itself instead of the
3657 file the link points to.
3658src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
3659 platform. If they are unavailable, using them will raise a
3660 NotImplementedError.
3661[clinic start generated code]*/
3662
Larry Hastings2f936352014-08-05 14:04:04 +10003663static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003664os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003665 int dst_dir_fd, int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003666/*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003667{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003668#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07003669 BOOL result = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003670#else
3671 int result;
3672#endif
3673
Larry Hastings9cf065c2012-06-22 16:30:09 -07003674#ifndef HAVE_LINKAT
3675 if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
3676 argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10003677 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003678 }
3679#endif
3680
Steve Dowercc16be82016-09-08 10:35:16 -07003681#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10003682 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003683 PyErr_SetString(PyExc_NotImplementedError,
3684 "link: src and dst must be the same type");
Larry Hastings2f936352014-08-05 14:04:04 +10003685 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003686 }
Steve Dowercc16be82016-09-08 10:35:16 -07003687#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003688
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003689 if (PySys_Audit("os.link", "OOii", src->object, dst->object,
3690 src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
3691 dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
3692 return NULL;
3693 }
3694
Brian Curtin1b9df392010-11-24 20:24:31 +00003695#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003696 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08003697 result = CreateHardLinkW(dst->wide, src->wide, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003698 Py_END_ALLOW_THREADS
Brian Curtin1b9df392010-11-24 20:24:31 +00003699
Larry Hastings2f936352014-08-05 14:04:04 +10003700 if (!result)
3701 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003702#else
3703 Py_BEGIN_ALLOW_THREADS
Larry Hastings67cbf7b2012-06-22 17:06:48 -07003704#ifdef HAVE_LINKAT
Larry Hastings9cf065c2012-06-22 16:30:09 -07003705 if ((src_dir_fd != DEFAULT_DIR_FD) ||
3706 (dst_dir_fd != DEFAULT_DIR_FD) ||
3707 (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003708 result = linkat(src_dir_fd, src->narrow,
3709 dst_dir_fd, dst->narrow,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003710 follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
3711 else
Steve Dowercc16be82016-09-08 10:35:16 -07003712#endif /* HAVE_LINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10003713 result = link(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003714 Py_END_ALLOW_THREADS
Brian Curtinfc889c42010-11-28 23:59:46 +00003715
Larry Hastings2f936352014-08-05 14:04:04 +10003716 if (result)
3717 return path_error2(src, dst);
Steve Dowercc16be82016-09-08 10:35:16 -07003718#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003719
Larry Hastings2f936352014-08-05 14:04:04 +10003720 Py_RETURN_NONE;
Brian Curtin1b9df392010-11-24 20:24:31 +00003721}
Larry Hastings9cf065c2012-06-22 16:30:09 -07003722#endif
3723
Brian Curtin1b9df392010-11-24 20:24:31 +00003724
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003725#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
Barry Warsaw53699e91996-12-10 23:23:01 +00003726static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003727_listdir_windows_no_opendir(path_t *path, PyObject *list)
Guido van Rossumb6775db1994-08-01 11:34:53 +00003728{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003729 PyObject *v;
3730 HANDLE hFindFile = INVALID_HANDLE_VALUE;
3731 BOOL result;
Steve Dowercc16be82016-09-08 10:35:16 -07003732 wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003733 /* only claim to have space for MAX_PATH */
Victor Stinner75875072013-11-24 19:23:25 +01003734 Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003735 wchar_t *wnamebuf = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003736
Steve Dowercc16be82016-09-08 10:35:16 -07003737 WIN32_FIND_DATAW wFileData;
3738 const wchar_t *po_wchars;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003739
Steve Dowercc16be82016-09-08 10:35:16 -07003740 if (!path->wide) { /* Default arg: "." */
3741 po_wchars = L".";
3742 len = 1;
3743 } else {
3744 po_wchars = path->wide;
3745 len = wcslen(path->wide);
3746 }
3747 /* The +5 is so we can append "\\*.*\0" */
3748 wnamebuf = PyMem_New(wchar_t, len + 5);
3749 if (!wnamebuf) {
3750 PyErr_NoMemory();
Larry Hastings9cf065c2012-06-22 16:30:09 -07003751 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003752 }
Steve Dowercc16be82016-09-08 10:35:16 -07003753 wcscpy(wnamebuf, po_wchars);
Victor Stinner8c62be82010-05-06 00:08:46 +00003754 if (len > 0) {
Steve Dowercc16be82016-09-08 10:35:16 -07003755 wchar_t wch = wnamebuf[len-1];
3756 if (wch != SEP && wch != ALTSEP && wch != L':')
3757 wnamebuf[len++] = SEP;
3758 wcscpy(wnamebuf + len, L"*.*");
Victor Stinner8c62be82010-05-06 00:08:46 +00003759 }
Steve Dowercc16be82016-09-08 10:35:16 -07003760 if ((list = PyList_New(0)) == NULL) {
3761 goto exit;
3762 }
Antoine Pitroub73caab2010-08-09 23:39:31 +00003763 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003764 hFindFile = FindFirstFileW(wnamebuf, &wFileData);
Antoine Pitroub73caab2010-08-09 23:39:31 +00003765 Py_END_ALLOW_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +00003766 if (hFindFile == INVALID_HANDLE_VALUE) {
3767 int error = GetLastError();
3768 if (error == ERROR_FILE_NOT_FOUND)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003769 goto exit;
3770 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003771 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003772 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003773 }
3774 do {
3775 /* Skip over . and .. */
Steve Dowercc16be82016-09-08 10:35:16 -07003776 if (wcscmp(wFileData.cFileName, L".") != 0 &&
3777 wcscmp(wFileData.cFileName, L"..") != 0) {
3778 v = PyUnicode_FromWideChar(wFileData.cFileName,
3779 wcslen(wFileData.cFileName));
3780 if (path->narrow && v) {
3781 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3782 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003783 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003784 Py_DECREF(list);
3785 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003786 break;
3787 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003788 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003789 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003790 Py_DECREF(list);
3791 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003792 break;
3793 }
3794 Py_DECREF(v);
3795 }
3796 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003797 result = FindNextFileW(hFindFile, &wFileData);
Victor Stinner8c62be82010-05-06 00:08:46 +00003798 Py_END_ALLOW_THREADS
3799 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
3800 it got to the end of the directory. */
3801 if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003802 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003803 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003804 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003805 }
3806 } while (result == TRUE);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003807
Larry Hastings9cf065c2012-06-22 16:30:09 -07003808exit:
3809 if (hFindFile != INVALID_HANDLE_VALUE) {
3810 if (FindClose(hFindFile) == FALSE) {
3811 if (list != NULL) {
3812 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003813 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003814 }
3815 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003816 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003817 PyMem_Free(wnamebuf);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003818
Larry Hastings9cf065c2012-06-22 16:30:09 -07003819 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003820} /* end of _listdir_windows_no_opendir */
3821
3822#else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
3823
3824static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003825_posix_listdir(path_t *path, PyObject *list)
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003826{
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003827 PyObject *v;
3828 DIR *dirp = NULL;
3829 struct dirent *ep;
3830 int return_str; /* if false, return bytes */
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003831#ifdef HAVE_FDOPENDIR
3832 int fd = -1;
3833#endif
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003834
Victor Stinner8c62be82010-05-06 00:08:46 +00003835 errno = 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003836#ifdef HAVE_FDOPENDIR
Gregory P. Smith40a21602013-03-20 20:52:50 -07003837 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003838 /* closedir() closes the FD, so we duplicate it */
Victor Stinnerdaf45552013-08-28 00:53:59 +02003839 fd = _Py_dup(path->fd);
Victor Stinnerf3266652013-12-19 13:24:49 +01003840 if (fd == -1)
3841 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003842
Larry Hastingsfdaea062012-06-25 04:42:23 -07003843 return_str = 1;
3844
Larry Hastings9cf065c2012-06-22 16:30:09 -07003845 Py_BEGIN_ALLOW_THREADS
3846 dirp = fdopendir(fd);
3847 Py_END_ALLOW_THREADS
3848 }
3849 else
3850#endif
3851 {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003852 const char *name;
Gregory P. Smith40a21602013-03-20 20:52:50 -07003853 if (path->narrow) {
3854 name = path->narrow;
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03003855 /* only return bytes if they specified a bytes-like object */
3856 return_str = !PyObject_CheckBuffer(path->object);
Larry Hastingsfdaea062012-06-25 04:42:23 -07003857 }
3858 else {
3859 name = ".";
3860 return_str = 1;
3861 }
3862
Larry Hastings9cf065c2012-06-22 16:30:09 -07003863 Py_BEGIN_ALLOW_THREADS
3864 dirp = opendir(name);
3865 Py_END_ALLOW_THREADS
3866 }
3867
3868 if (dirp == NULL) {
Gregory P. Smith40a21602013-03-20 20:52:50 -07003869 list = path_error(path);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003870#ifdef HAVE_FDOPENDIR
3871 if (fd != -1) {
3872 Py_BEGIN_ALLOW_THREADS
3873 close(fd);
3874 Py_END_ALLOW_THREADS
3875 }
3876#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003877 goto exit;
3878 }
3879 if ((list = PyList_New(0)) == NULL) {
3880 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003881 }
3882 for (;;) {
3883 errno = 0;
3884 Py_BEGIN_ALLOW_THREADS
3885 ep = readdir(dirp);
3886 Py_END_ALLOW_THREADS
3887 if (ep == NULL) {
3888 if (errno == 0) {
3889 break;
3890 } else {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003891 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003892 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003893 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003894 }
3895 }
3896 if (ep->d_name[0] == '.' &&
3897 (NAMLEN(ep) == 1 ||
3898 (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
3899 continue;
Larry Hastingsfdaea062012-06-25 04:42:23 -07003900 if (return_str)
Victor Stinnera45598a2010-05-14 16:35:39 +00003901 v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
3902 else
3903 v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
Victor Stinner8c62be82010-05-06 00:08:46 +00003904 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003905 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003906 break;
3907 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003908 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003909 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003910 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003911 break;
3912 }
3913 Py_DECREF(v);
3914 }
Guido van Rossum0ee42cd1991-04-08 21:01:03 +00003915
Larry Hastings9cf065c2012-06-22 16:30:09 -07003916exit:
3917 if (dirp != NULL) {
3918 Py_BEGIN_ALLOW_THREADS
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003919#ifdef HAVE_FDOPENDIR
Larry Hastings9cf065c2012-06-22 16:30:09 -07003920 if (fd > -1)
3921 rewinddir(dirp);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003922#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003923 closedir(dirp);
3924 Py_END_ALLOW_THREADS
3925 }
3926
Larry Hastings9cf065c2012-06-22 16:30:09 -07003927 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003928} /* end of _posix_listdir */
3929#endif /* which OS */
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003930
Larry Hastings2f936352014-08-05 14:04:04 +10003931
3932/*[clinic input]
3933os.listdir
3934
3935 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
3936
3937Return a list containing the names of the files in the directory.
3938
BNMetricsb9427072018-11-02 15:20:19 +00003939path can be specified as either str, bytes, or a path-like object. If path is bytes,
Larry Hastings2f936352014-08-05 14:04:04 +10003940 the filenames returned will also be bytes; in all other circumstances
3941 the filenames returned will be str.
3942If path is None, uses the path='.'.
3943On some platforms, path may also be specified as an open file descriptor;\
3944 the file descriptor must refer to a directory.
3945 If this functionality is unavailable, using it raises NotImplementedError.
3946
3947The list is in arbitrary order. It does not include the special
3948entries '.' and '..' even if they are present in the directory.
3949
3950
3951[clinic start generated code]*/
3952
Larry Hastings2f936352014-08-05 14:04:04 +10003953static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003954os_listdir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +00003955/*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003956{
Steve Dower60419a72019-06-24 08:42:54 -07003957 if (PySys_Audit("os.listdir", "O",
3958 path->object ? path->object : Py_None) < 0) {
3959 return NULL;
3960 }
Larry Hastings2f936352014-08-05 14:04:04 +10003961#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
3962 return _listdir_windows_no_opendir(path, NULL);
3963#else
3964 return _posix_listdir(path, NULL);
3965#endif
3966}
3967
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00003968#ifdef MS_WINDOWS
Mark Hammondef8b6542001-05-13 08:04:26 +00003969/* A helper function for abspath on win32 */
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003970/*[clinic input]
3971os._getfullpathname
Victor Stinnereb5657a2011-09-30 01:44:27 +02003972
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003973 path: path_t
3974 /
3975
3976[clinic start generated code]*/
3977
3978static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003979os__getfullpathname_impl(PyObject *module, path_t *path)
3980/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003981{
Victor Stinner3939c322019-06-25 15:02:43 +02003982 wchar_t *abspath;
Victor Stinnereb5657a2011-09-30 01:44:27 +02003983
Victor Stinner3939c322019-06-25 15:02:43 +02003984 /* _Py_abspath() is implemented with GetFullPathNameW() on Windows */
3985 if (_Py_abspath(path->wide, &abspath) < 0) {
3986 return win32_error_object("GetFullPathNameW", path->object);
Victor Stinner8c62be82010-05-06 00:08:46 +00003987 }
Victor Stinner3939c322019-06-25 15:02:43 +02003988 if (abspath == NULL) {
3989 return PyErr_NoMemory();
3990 }
3991
3992 PyObject *str = PyUnicode_FromWideChar(abspath, wcslen(abspath));
3993 PyMem_RawFree(abspath);
3994 if (str == NULL) {
3995 return NULL;
3996 }
3997 if (path->narrow) {
3998 Py_SETREF(str, PyUnicode_EncodeFSDefault(str));
3999 }
4000 return str;
Larry Hastings2f936352014-08-05 14:04:04 +10004001}
Brian Curtind40e6f72010-07-08 21:39:08 +00004002
Brian Curtind25aef52011-06-13 15:16:04 -05004003
Larry Hastings2f936352014-08-05 14:04:04 +10004004/*[clinic input]
4005os._getfinalpathname
Brian Curtinf5e76d02010-11-24 13:14:05 +00004006
Steve Dower23ad6d02018-02-22 10:39:10 -08004007 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10004008 /
4009
4010A helper function for samepath on windows.
4011[clinic start generated code]*/
4012
Larry Hastings2f936352014-08-05 14:04:04 +10004013static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08004014os__getfinalpathname_impl(PyObject *module, path_t *path)
4015/*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
Brian Curtind40e6f72010-07-08 21:39:08 +00004016{
4017 HANDLE hFile;
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004018 wchar_t buf[MAXPATHLEN], *target_path = buf;
4019 int buf_size = Py_ARRAY_LENGTH(buf);
Brian Curtind40e6f72010-07-08 21:39:08 +00004020 int result_length;
Larry Hastings2f936352014-08-05 14:04:04 +10004021 PyObject *result;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004022
Steve Dower23ad6d02018-02-22 10:39:10 -08004023 Py_BEGIN_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00004024 hFile = CreateFileW(
Steve Dower23ad6d02018-02-22 10:39:10 -08004025 path->wide,
Brian Curtind40e6f72010-07-08 21:39:08 +00004026 0, /* desired access */
4027 0, /* share mode */
4028 NULL, /* security attributes */
4029 OPEN_EXISTING,
4030 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
4031 FILE_FLAG_BACKUP_SEMANTICS,
4032 NULL);
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004033 Py_END_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004034
Steve Dower23ad6d02018-02-22 10:39:10 -08004035 if (hFile == INVALID_HANDLE_VALUE) {
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004036 return win32_error_object("CreateFileW", path->object);
Steve Dower23ad6d02018-02-22 10:39:10 -08004037 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004038
4039 /* We have a good handle to the target, use it to determine the
4040 target path name. */
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004041 while (1) {
4042 Py_BEGIN_ALLOW_THREADS
4043 result_length = GetFinalPathNameByHandleW(hFile, target_path,
4044 buf_size, VOLUME_NAME_DOS);
4045 Py_END_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00004046
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004047 if (!result_length) {
4048 result = win32_error_object("GetFinalPathNameByHandleW",
4049 path->object);
4050 goto cleanup;
4051 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004052
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004053 if (result_length < buf_size) {
4054 break;
4055 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004056
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004057 wchar_t *tmp;
4058 tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
4059 result_length * sizeof(*tmp));
4060 if (!tmp) {
4061 result = PyErr_NoMemory();
4062 goto cleanup;
4063 }
4064
4065 buf_size = result_length;
4066 target_path = tmp;
Steve Dower23ad6d02018-02-22 10:39:10 -08004067 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004068
Victor Stinner9d3b93b2011-11-22 02:27:30 +01004069 result = PyUnicode_FromWideChar(target_path, result_length);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004070 if (result && path->narrow) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004071 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004072 }
Steve Dower23ad6d02018-02-22 10:39:10 -08004073
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004074cleanup:
4075 if (target_path != buf) {
4076 PyMem_Free(target_path);
4077 }
4078 CloseHandle(hFile);
4079 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10004080}
Brian Curtin62857742010-09-06 17:07:27 +00004081
Tim Golden6b528062013-08-01 12:44:00 +01004082
Larry Hastings2f936352014-08-05 14:04:04 +10004083/*[clinic input]
4084os._getvolumepathname
4085
Steve Dower23ad6d02018-02-22 10:39:10 -08004086 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10004087
4088A helper function for ismount on Win32.
4089[clinic start generated code]*/
4090
Larry Hastings2f936352014-08-05 14:04:04 +10004091static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08004092os__getvolumepathname_impl(PyObject *module, path_t *path)
4093/*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004094{
4095 PyObject *result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004096 wchar_t *mountpath=NULL;
Victor Stinner6edddfa2013-11-24 19:22:57 +01004097 size_t buflen;
Tim Golden6b528062013-08-01 12:44:00 +01004098 BOOL ret;
4099
Tim Golden6b528062013-08-01 12:44:00 +01004100 /* Volume path should be shorter than entire path */
Steve Dower23ad6d02018-02-22 10:39:10 -08004101 buflen = Py_MAX(path->length, MAX_PATH);
Victor Stinner6edddfa2013-11-24 19:22:57 +01004102
Victor Stinner850a18e2017-10-24 16:53:32 -07004103 if (buflen > PY_DWORD_MAX) {
Victor Stinner6edddfa2013-11-24 19:22:57 +01004104 PyErr_SetString(PyExc_OverflowError, "path too long");
4105 return NULL;
4106 }
4107
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004108 mountpath = PyMem_New(wchar_t, buflen);
Tim Golden6b528062013-08-01 12:44:00 +01004109 if (mountpath == NULL)
4110 return PyErr_NoMemory();
4111
4112 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -08004113 ret = GetVolumePathNameW(path->wide, mountpath,
Victor Stinner6edddfa2013-11-24 19:22:57 +01004114 Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
Tim Golden6b528062013-08-01 12:44:00 +01004115 Py_END_ALLOW_THREADS
4116
4117 if (!ret) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004118 result = win32_error_object("_getvolumepathname", path->object);
Tim Golden6b528062013-08-01 12:44:00 +01004119 goto exit;
4120 }
4121 result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
Steve Dower23ad6d02018-02-22 10:39:10 -08004122 if (path->narrow)
4123 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Tim Golden6b528062013-08-01 12:44:00 +01004124
4125exit:
4126 PyMem_Free(mountpath);
4127 return result;
4128}
Tim Golden6b528062013-08-01 12:44:00 +01004129
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004130#endif /* MS_WINDOWS */
Mark Hammondef8b6542001-05-13 08:04:26 +00004131
Larry Hastings2f936352014-08-05 14:04:04 +10004132
4133/*[clinic input]
4134os.mkdir
4135
4136 path : path_t
4137
4138 mode: int = 0o777
4139
4140 *
4141
4142 dir_fd : dir_fd(requires='mkdirat') = None
4143
4144# "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
4145
4146Create a directory.
4147
4148If dir_fd is not None, it should be a file descriptor open to a directory,
4149 and path should be relative; path will then be relative to that directory.
4150dir_fd may not be implemented on your platform.
4151 If it is unavailable, using it will raise a NotImplementedError.
4152
4153The mode argument is ignored on Windows.
4154[clinic start generated code]*/
4155
Larry Hastings2f936352014-08-05 14:04:04 +10004156static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004157os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
4158/*[clinic end generated code: output=a70446903abe821f input=e965f68377e9b1ce]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004159{
4160 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004161
Saiyang Gou7514f4f2020-02-12 23:47:42 -08004162 if (PySys_Audit("os.mkdir", "Oii", path->object, mode,
4163 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4164 return NULL;
4165 }
4166
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004167#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004168 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004169 result = CreateDirectoryW(path->wide, NULL);
Victor Stinner8c62be82010-05-06 00:08:46 +00004170 Py_END_ALLOW_THREADS
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004171
Larry Hastings2f936352014-08-05 14:04:04 +10004172 if (!result)
4173 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004174#else
Victor Stinner8c62be82010-05-06 00:08:46 +00004175 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004176#if HAVE_MKDIRAT
4177 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004178 result = mkdirat(dir_fd, path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004179 else
4180#endif
Erik Bray03eb11f2017-10-27 14:27:06 +02004181#if defined(__WATCOMC__) && !defined(__QNX__)
Larry Hastings2f936352014-08-05 14:04:04 +10004182 result = mkdir(path->narrow);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004183#else
Larry Hastings2f936352014-08-05 14:04:04 +10004184 result = mkdir(path->narrow, mode);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004185#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004186 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004187 if (result < 0)
4188 return path_error(path);
Steve Dowercc16be82016-09-08 10:35:16 -07004189#endif /* MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10004190 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004191}
4192
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004193
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004194/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
4195#if defined(HAVE_SYS_RESOURCE_H)
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004196#include <sys/resource.h>
4197#endif
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004198
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004199
4200#ifdef HAVE_NICE
Larry Hastings2f936352014-08-05 14:04:04 +10004201/*[clinic input]
4202os.nice
4203
4204 increment: int
4205 /
4206
4207Add increment to the priority of process and return the new priority.
4208[clinic start generated code]*/
4209
Larry Hastings2f936352014-08-05 14:04:04 +10004210static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004211os_nice_impl(PyObject *module, int increment)
4212/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004213{
4214 int value;
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004215
Victor Stinner8c62be82010-05-06 00:08:46 +00004216 /* There are two flavours of 'nice': one that returns the new
4217 priority (as required by almost all standards out there) and the
Benjamin Peterson288d1da2017-09-28 22:44:27 -07004218 Linux/FreeBSD one, which returns '0' on success and advices
Victor Stinner8c62be82010-05-06 00:08:46 +00004219 the use of getpriority() to get the new priority.
Tim Peters5aa91602002-01-30 05:46:57 +00004220
Victor Stinner8c62be82010-05-06 00:08:46 +00004221 If we are of the nice family that returns the new priority, we
4222 need to clear errno before the call, and check if errno is filled
4223 before calling posix_error() on a returnvalue of -1, because the
4224 -1 may be the actual new priority! */
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004225
Victor Stinner8c62be82010-05-06 00:08:46 +00004226 errno = 0;
4227 value = nice(increment);
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004228#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
Victor Stinner8c62be82010-05-06 00:08:46 +00004229 if (value == 0)
4230 value = getpriority(PRIO_PROCESS, 0);
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004231#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004232 if (value == -1 && errno != 0)
4233 /* either nice() or getpriority() returned an error */
4234 return posix_error();
4235 return PyLong_FromLong((long) value);
Guido van Rossum775f4da1993-01-09 17:18:52 +00004236}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004237#endif /* HAVE_NICE */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004238
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004239
4240#ifdef HAVE_GETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004241/*[clinic input]
4242os.getpriority
4243
4244 which: int
4245 who: int
4246
4247Return program scheduling priority.
4248[clinic start generated code]*/
4249
Larry Hastings2f936352014-08-05 14:04:04 +10004250static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004251os_getpriority_impl(PyObject *module, int which, int who)
4252/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004253{
4254 int retval;
4255
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004256 errno = 0;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004257 retval = getpriority(which, who);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004258 if (errno != 0)
4259 return posix_error();
4260 return PyLong_FromLong((long)retval);
4261}
4262#endif /* HAVE_GETPRIORITY */
4263
4264
4265#ifdef HAVE_SETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004266/*[clinic input]
4267os.setpriority
4268
4269 which: int
4270 who: int
4271 priority: int
4272
4273Set program scheduling priority.
4274[clinic start generated code]*/
4275
Larry Hastings2f936352014-08-05 14:04:04 +10004276static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004277os_setpriority_impl(PyObject *module, int which, int who, int priority)
4278/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004279{
4280 int retval;
4281
4282 retval = setpriority(which, who, priority);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004283 if (retval == -1)
4284 return posix_error();
4285 Py_RETURN_NONE;
4286}
4287#endif /* HAVE_SETPRIORITY */
4288
4289
Barry Warsaw53699e91996-12-10 23:23:01 +00004290static PyObject *
Larry Hastings2f936352014-08-05 14:04:04 +10004291internal_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 +00004292{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004293 const char *function_name = is_replace ? "replace" : "rename";
Larry Hastings9cf065c2012-06-22 16:30:09 -07004294 int dir_fd_specified;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004295
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004296#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004297 BOOL result;
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004298 int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004299#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004300 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004301#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004302
Larry Hastings9cf065c2012-06-22 16:30:09 -07004303 dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
4304 (dst_dir_fd != DEFAULT_DIR_FD);
4305#ifndef HAVE_RENAMEAT
4306 if (dir_fd_specified) {
4307 argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10004308 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004309 }
4310#endif
4311
Saiyang Gou7514f4f2020-02-12 23:47:42 -08004312 if (PySys_Audit("os.rename", "OOii", src->object, dst->object,
4313 src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
4314 dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
4315 return NULL;
4316 }
4317
Larry Hastings9cf065c2012-06-22 16:30:09 -07004318#ifdef MS_WINDOWS
4319 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004320 result = MoveFileExW(src->wide, dst->wide, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004321 Py_END_ALLOW_THREADS
4322
Larry Hastings2f936352014-08-05 14:04:04 +10004323 if (!result)
4324 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004325
4326#else
Steve Dowercc16be82016-09-08 10:35:16 -07004327 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
4328 PyErr_Format(PyExc_ValueError,
4329 "%s: src and dst must be the same type", function_name);
4330 return NULL;
4331 }
4332
Larry Hastings9cf065c2012-06-22 16:30:09 -07004333 Py_BEGIN_ALLOW_THREADS
4334#ifdef HAVE_RENAMEAT
4335 if (dir_fd_specified)
Larry Hastings2f936352014-08-05 14:04:04 +10004336 result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004337 else
4338#endif
Steve Dowercc16be82016-09-08 10:35:16 -07004339 result = rename(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004340 Py_END_ALLOW_THREADS
4341
Larry Hastings2f936352014-08-05 14:04:04 +10004342 if (result)
4343 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004344#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004345 Py_RETURN_NONE;
4346}
Larry Hastings9cf065c2012-06-22 16:30:09 -07004347
Larry Hastings2f936352014-08-05 14:04:04 +10004348
4349/*[clinic input]
4350os.rename
4351
4352 src : path_t
4353 dst : path_t
4354 *
4355 src_dir_fd : dir_fd = None
4356 dst_dir_fd : dir_fd = None
4357
4358Rename a file or directory.
4359
4360If either src_dir_fd or dst_dir_fd is not None, it should be a file
4361 descriptor open to a directory, and the respective path string (src or dst)
4362 should be relative; the path will then be relative to that directory.
4363src_dir_fd and dst_dir_fd, may not be implemented on your platform.
4364 If they are unavailable, using them will raise a NotImplementedError.
4365[clinic start generated code]*/
4366
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004367static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004368os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04004369 int dst_dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004370/*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004371{
Larry Hastings2f936352014-08-05 14:04:04 +10004372 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004373}
4374
Larry Hastings2f936352014-08-05 14:04:04 +10004375
4376/*[clinic input]
4377os.replace = os.rename
4378
4379Rename a file or directory, overwriting the destination.
4380
4381If either src_dir_fd or dst_dir_fd is not None, it should be a file
4382 descriptor open to a directory, and the respective path string (src or dst)
4383 should be relative; the path will then be relative to that directory.
4384src_dir_fd and dst_dir_fd, may not be implemented on your platform.
Anthony Sottile73d60022019-02-12 23:15:54 -05004385 If they are unavailable, using them will raise a NotImplementedError.
Larry Hastings2f936352014-08-05 14:04:04 +10004386[clinic start generated code]*/
4387
Larry Hastings2f936352014-08-05 14:04:04 +10004388static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004389os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
4390 int dst_dir_fd)
Anthony Sottile73d60022019-02-12 23:15:54 -05004391/*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004392{
4393 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
4394}
4395
4396
4397/*[clinic input]
4398os.rmdir
4399
4400 path: path_t
4401 *
4402 dir_fd: dir_fd(requires='unlinkat') = None
4403
4404Remove a directory.
4405
4406If dir_fd is not None, it should be a file descriptor open to a directory,
4407 and path should be relative; path will then be relative to that directory.
4408dir_fd may not be implemented on your platform.
4409 If it is unavailable, using it will raise a NotImplementedError.
4410[clinic start generated code]*/
4411
Larry Hastings2f936352014-08-05 14:04:04 +10004412static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004413os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
4414/*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004415{
4416 int result;
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004417
Saiyang Gou7514f4f2020-02-12 23:47:42 -08004418 if (PySys_Audit("os.rmdir", "Oi", path->object,
4419 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4420 return NULL;
4421 }
4422
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004423 Py_BEGIN_ALLOW_THREADS
4424#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004425 /* Windows, success=1, UNIX, success=0 */
4426 result = !RemoveDirectoryW(path->wide);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004427#else
4428#ifdef HAVE_UNLINKAT
4429 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004430 result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004431 else
4432#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004433 result = rmdir(path->narrow);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004434#endif
4435 Py_END_ALLOW_THREADS
4436
Larry Hastings2f936352014-08-05 14:04:04 +10004437 if (result)
4438 return path_error(path);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004439
Larry Hastings2f936352014-08-05 14:04:04 +10004440 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004441}
4442
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004443
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004444#ifdef HAVE_SYSTEM
Larry Hastings2f936352014-08-05 14:04:04 +10004445#ifdef MS_WINDOWS
4446/*[clinic input]
4447os.system -> long
4448
4449 command: Py_UNICODE
4450
4451Execute the command in a subshell.
4452[clinic start generated code]*/
4453
Larry Hastings2f936352014-08-05 14:04:04 +10004454static long
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02004455os_system_impl(PyObject *module, const Py_UNICODE *command)
4456/*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004457{
4458 long result;
Steve Dowerb82e17e2019-05-23 08:45:22 -07004459
Steve Dowerfbe3c762019-10-18 00:52:15 -07004460 if (PySys_Audit("os.system", "(u)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004461 return -1;
4462 }
4463
Victor Stinner8c62be82010-05-06 00:08:46 +00004464 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08004465 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10004466 result = _wsystem(command);
Steve Dowerc3630612016-11-19 18:41:16 -08004467 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00004468 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004469 return result;
4470}
4471#else /* MS_WINDOWS */
4472/*[clinic input]
4473os.system -> long
4474
4475 command: FSConverter
4476
4477Execute the command in a subshell.
4478[clinic start generated code]*/
4479
Larry Hastings2f936352014-08-05 14:04:04 +10004480static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004481os_system_impl(PyObject *module, PyObject *command)
4482/*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004483{
4484 long result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004485 const char *bytes = PyBytes_AsString(command);
Steve Dowerb82e17e2019-05-23 08:45:22 -07004486
Steve Dowerfbe3c762019-10-18 00:52:15 -07004487 if (PySys_Audit("os.system", "(O)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004488 return -1;
4489 }
4490
Larry Hastings2f936352014-08-05 14:04:04 +10004491 Py_BEGIN_ALLOW_THREADS
4492 result = system(bytes);
4493 Py_END_ALLOW_THREADS
4494 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004495}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004496#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004497#endif /* HAVE_SYSTEM */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004498
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004499
Larry Hastings2f936352014-08-05 14:04:04 +10004500/*[clinic input]
4501os.umask
4502
4503 mask: int
4504 /
4505
4506Set the current numeric umask and return the previous umask.
4507[clinic start generated code]*/
4508
Larry Hastings2f936352014-08-05 14:04:04 +10004509static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004510os_umask_impl(PyObject *module, int mask)
4511/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004512{
4513 int i = (int)umask(mask);
Victor Stinner8c62be82010-05-06 00:08:46 +00004514 if (i < 0)
4515 return posix_error();
4516 return PyLong_FromLong((long)i);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004517}
4518
Brian Curtind40e6f72010-07-08 21:39:08 +00004519#ifdef MS_WINDOWS
4520
4521/* override the default DeleteFileW behavior so that directory
4522symlinks can be removed with this function, the same as with
4523Unix symlinks */
4524BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
4525{
4526 WIN32_FILE_ATTRIBUTE_DATA info;
4527 WIN32_FIND_DATAW find_data;
4528 HANDLE find_data_handle;
4529 int is_directory = 0;
4530 int is_link = 0;
4531
4532 if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
4533 is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004534
Brian Curtind40e6f72010-07-08 21:39:08 +00004535 /* Get WIN32_FIND_DATA structure for the path to determine if
4536 it is a symlink */
4537 if(is_directory &&
4538 info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
4539 find_data_handle = FindFirstFileW(lpFileName, &find_data);
4540
4541 if(find_data_handle != INVALID_HANDLE_VALUE) {
Tim Golden0321cf22014-05-05 19:46:17 +01004542 /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
4543 IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
4544 is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
4545 find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
Brian Curtind40e6f72010-07-08 21:39:08 +00004546 FindClose(find_data_handle);
4547 }
4548 }
4549 }
4550
4551 if (is_directory && is_link)
4552 return RemoveDirectoryW(lpFileName);
4553
4554 return DeleteFileW(lpFileName);
4555}
4556#endif /* MS_WINDOWS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004557
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004558
Larry Hastings2f936352014-08-05 14:04:04 +10004559/*[clinic input]
4560os.unlink
4561
4562 path: path_t
4563 *
4564 dir_fd: dir_fd(requires='unlinkat')=None
4565
4566Remove a file (same as remove()).
4567
4568If dir_fd is not None, it should be a file descriptor open to a directory,
4569 and path should be relative; path will then be relative to that directory.
4570dir_fd may not be implemented on your platform.
4571 If it is unavailable, using it will raise a NotImplementedError.
4572
4573[clinic start generated code]*/
4574
Larry Hastings2f936352014-08-05 14:04:04 +10004575static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004576os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
4577/*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004578{
4579 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004580
Saiyang Gou7514f4f2020-02-12 23:47:42 -08004581 if (PySys_Audit("os.remove", "Oi", path->object,
4582 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4583 return NULL;
4584 }
4585
Larry Hastings9cf065c2012-06-22 16:30:09 -07004586 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04004587 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004588#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004589 /* Windows, success=1, UNIX, success=0 */
4590 result = !Py_DeleteFileW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004591#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004592#ifdef HAVE_UNLINKAT
4593 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004594 result = unlinkat(dir_fd, path->narrow, 0);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004595 else
4596#endif /* HAVE_UNLINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10004597 result = unlink(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004598#endif
Steve Dower8fc89802015-04-12 00:26:27 -04004599 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004600 Py_END_ALLOW_THREADS
4601
Larry Hastings2f936352014-08-05 14:04:04 +10004602 if (result)
4603 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004604
Larry Hastings2f936352014-08-05 14:04:04 +10004605 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004606}
4607
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004608
Larry Hastings2f936352014-08-05 14:04:04 +10004609/*[clinic input]
4610os.remove = os.unlink
4611
4612Remove a file (same as unlink()).
4613
4614If dir_fd is not None, it should be a file descriptor open to a directory,
4615 and path should be relative; path will then be relative to that directory.
4616dir_fd may not be implemented on your platform.
4617 If it is unavailable, using it will raise a NotImplementedError.
4618[clinic start generated code]*/
4619
Larry Hastings2f936352014-08-05 14:04:04 +10004620static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004621os_remove_impl(PyObject *module, path_t *path, int dir_fd)
4622/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004623{
4624 return os_unlink_impl(module, path, dir_fd);
4625}
4626
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004627
Larry Hastings605a62d2012-06-24 04:33:36 -07004628static PyStructSequence_Field uname_result_fields[] = {
4629 {"sysname", "operating system name"},
4630 {"nodename", "name of machine on network (implementation-defined)"},
4631 {"release", "operating system release"},
4632 {"version", "operating system version"},
4633 {"machine", "hardware identifier"},
4634 {NULL}
4635};
4636
4637PyDoc_STRVAR(uname_result__doc__,
4638"uname_result: Result from os.uname().\n\n\
4639This object may be accessed either as a tuple of\n\
4640 (sysname, nodename, release, version, machine),\n\
4641or via the attributes sysname, nodename, release, version, and machine.\n\
4642\n\
4643See os.uname for more information.");
4644
4645static PyStructSequence_Desc uname_result_desc = {
Eddie Elizondob3966632019-11-05 07:16:14 -08004646 MODNAME ".uname_result", /* name */
Larry Hastings605a62d2012-06-24 04:33:36 -07004647 uname_result__doc__, /* doc */
4648 uname_result_fields,
4649 5
4650};
4651
Larry Hastings605a62d2012-06-24 04:33:36 -07004652#ifdef HAVE_UNAME
Larry Hastings2f936352014-08-05 14:04:04 +10004653/*[clinic input]
4654os.uname
4655
4656Return an object identifying the current operating system.
4657
4658The object behaves like a named tuple with the following fields:
4659 (sysname, nodename, release, version, machine)
4660
4661[clinic start generated code]*/
4662
Larry Hastings2f936352014-08-05 14:04:04 +10004663static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004664os_uname_impl(PyObject *module)
4665/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004666{
Victor Stinner8c62be82010-05-06 00:08:46 +00004667 struct utsname u;
4668 int res;
Larry Hastings605a62d2012-06-24 04:33:36 -07004669 PyObject *value;
Neal Norwitze241ce82003-02-17 18:17:05 +00004670
Victor Stinner8c62be82010-05-06 00:08:46 +00004671 Py_BEGIN_ALLOW_THREADS
4672 res = uname(&u);
4673 Py_END_ALLOW_THREADS
4674 if (res < 0)
4675 return posix_error();
Larry Hastings605a62d2012-06-24 04:33:36 -07004676
Hai Shif707d942020-03-16 21:15:01 +08004677 PyObject *UnameResultType = get_posix_state(module)->UnameResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -08004678 value = PyStructSequence_New((PyTypeObject *)UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07004679 if (value == NULL)
4680 return NULL;
4681
4682#define SET(i, field) \
4683 { \
Victor Stinnera534fc42013-06-03 22:07:27 +02004684 PyObject *o = PyUnicode_DecodeFSDefault(field); \
Larry Hastings605a62d2012-06-24 04:33:36 -07004685 if (!o) { \
4686 Py_DECREF(value); \
4687 return NULL; \
4688 } \
4689 PyStructSequence_SET_ITEM(value, i, o); \
4690 } \
4691
4692 SET(0, u.sysname);
4693 SET(1, u.nodename);
4694 SET(2, u.release);
4695 SET(3, u.version);
4696 SET(4, u.machine);
4697
4698#undef SET
4699
4700 return value;
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004701}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004702#endif /* HAVE_UNAME */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004703
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004704
Larry Hastings9cf065c2012-06-22 16:30:09 -07004705
4706typedef struct {
4707 int now;
4708 time_t atime_s;
4709 long atime_ns;
4710 time_t mtime_s;
4711 long mtime_ns;
4712} utime_t;
4713
4714/*
Victor Stinner484df002014-10-09 13:52:31 +02004715 * these macros assume that "ut" is a pointer to a utime_t
Larry Hastings9cf065c2012-06-22 16:30:09 -07004716 * they also intentionally leak the declaration of a pointer named "time"
4717 */
4718#define UTIME_TO_TIMESPEC \
4719 struct timespec ts[2]; \
4720 struct timespec *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004721 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004722 time = NULL; \
4723 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004724 ts[0].tv_sec = ut->atime_s; \
4725 ts[0].tv_nsec = ut->atime_ns; \
4726 ts[1].tv_sec = ut->mtime_s; \
4727 ts[1].tv_nsec = ut->mtime_ns; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004728 time = ts; \
4729 } \
4730
4731#define UTIME_TO_TIMEVAL \
4732 struct timeval tv[2]; \
4733 struct timeval *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004734 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004735 time = NULL; \
4736 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004737 tv[0].tv_sec = ut->atime_s; \
4738 tv[0].tv_usec = ut->atime_ns / 1000; \
4739 tv[1].tv_sec = ut->mtime_s; \
4740 tv[1].tv_usec = ut->mtime_ns / 1000; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004741 time = tv; \
4742 } \
4743
4744#define UTIME_TO_UTIMBUF \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004745 struct utimbuf u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004746 struct utimbuf *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004747 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004748 time = NULL; \
4749 else { \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004750 u.actime = ut->atime_s; \
4751 u.modtime = ut->mtime_s; \
4752 time = &u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004753 }
4754
4755#define UTIME_TO_TIME_T \
4756 time_t timet[2]; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004757 time_t *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004758 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004759 time = NULL; \
4760 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004761 timet[0] = ut->atime_s; \
4762 timet[1] = ut->mtime_s; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004763 time = timet; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004764 } \
4765
4766
Victor Stinner528a9ab2015-09-03 21:30:26 +02004767#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004768
4769static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004770utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004771{
4772#ifdef HAVE_UTIMENSAT
4773 int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
4774 UTIME_TO_TIMESPEC;
4775 return utimensat(dir_fd, path, time, flags);
4776#elif defined(HAVE_FUTIMESAT)
4777 UTIME_TO_TIMEVAL;
4778 /*
4779 * follow_symlinks will never be false here;
4780 * we only allow !follow_symlinks and dir_fd together
4781 * if we have utimensat()
4782 */
4783 assert(follow_symlinks);
4784 return futimesat(dir_fd, path, time);
4785#endif
4786}
4787
Larry Hastings2f936352014-08-05 14:04:04 +10004788 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
4789#else
4790 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings9cf065c2012-06-22 16:30:09 -07004791#endif
4792
Victor Stinner528a9ab2015-09-03 21:30:26 +02004793#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004794
4795static int
Victor Stinner484df002014-10-09 13:52:31 +02004796utime_fd(utime_t *ut, int fd)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004797{
4798#ifdef HAVE_FUTIMENS
4799 UTIME_TO_TIMESPEC;
4800 return futimens(fd, time);
4801#else
4802 UTIME_TO_TIMEVAL;
4803 return futimes(fd, time);
4804#endif
4805}
4806
Larry Hastings2f936352014-08-05 14:04:04 +10004807 #define PATH_UTIME_HAVE_FD 1
4808#else
4809 #define PATH_UTIME_HAVE_FD 0
Larry Hastings9cf065c2012-06-22 16:30:09 -07004810#endif
4811
Victor Stinner5ebae872015-09-22 01:29:33 +02004812#if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
4813# define UTIME_HAVE_NOFOLLOW_SYMLINKS
4814#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004815
Victor Stinner4552ced2015-09-21 22:37:15 +02004816#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004817
4818static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004819utime_nofollow_symlinks(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004820{
4821#ifdef HAVE_UTIMENSAT
4822 UTIME_TO_TIMESPEC;
4823 return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
4824#else
4825 UTIME_TO_TIMEVAL;
4826 return lutimes(path, time);
4827#endif
4828}
4829
4830#endif
4831
4832#ifndef MS_WINDOWS
4833
4834static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004835utime_default(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004836{
4837#ifdef HAVE_UTIMENSAT
4838 UTIME_TO_TIMESPEC;
4839 return utimensat(DEFAULT_DIR_FD, path, time, 0);
4840#elif defined(HAVE_UTIMES)
4841 UTIME_TO_TIMEVAL;
4842 return utimes(path, time);
4843#elif defined(HAVE_UTIME_H)
4844 UTIME_TO_UTIMBUF;
4845 return utime(path, time);
4846#else
4847 UTIME_TO_TIME_T;
4848 return utime(path, time);
4849#endif
4850}
4851
4852#endif
4853
Larry Hastings76ad59b2012-05-03 00:30:07 -07004854static int
4855split_py_long_to_s_and_ns(PyObject *py_long, time_t *s, long *ns)
4856{
4857 int result = 0;
Benjamin Petersonfbd85a02012-05-04 11:06:09 -04004858 PyObject *divmod;
Eddie Elizondob3966632019-11-05 07:16:14 -08004859 divmod = PyNumber_Divmod(py_long, _posixstate_global->billion);
Larry Hastings76ad59b2012-05-03 00:30:07 -07004860 if (!divmod)
4861 goto exit;
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004862 if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
4863 PyErr_Format(PyExc_TypeError,
4864 "%.200s.__divmod__() must return a 2-tuple, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -08004865 _PyType_Name(Py_TYPE(py_long)), _PyType_Name(Py_TYPE(divmod)));
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004866 goto exit;
4867 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004868 *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
4869 if ((*s == -1) && PyErr_Occurred())
4870 goto exit;
4871 *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
Benjamin Peterson35a8f0d2012-05-04 01:10:59 -04004872 if ((*ns == -1) && PyErr_Occurred())
Larry Hastings76ad59b2012-05-03 00:30:07 -07004873 goto exit;
4874
4875 result = 1;
4876exit:
4877 Py_XDECREF(divmod);
4878 return result;
4879}
4880
Larry Hastings2f936352014-08-05 14:04:04 +10004881
4882/*[clinic input]
4883os.utime
4884
4885 path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004886 times: object = None
Larry Hastings2f936352014-08-05 14:04:04 +10004887 *
4888 ns: object = NULL
4889 dir_fd: dir_fd(requires='futimensat') = None
4890 follow_symlinks: bool=True
4891
Martin Panter0ff89092015-09-09 01:56:53 +00004892# "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
Larry Hastings2f936352014-08-05 14:04:04 +10004893
4894Set the access and modified time of path.
4895
4896path may always be specified as a string.
4897On some platforms, path may also be specified as an open file descriptor.
4898 If this functionality is unavailable, using it raises an exception.
4899
4900If times is not None, it must be a tuple (atime, mtime);
4901 atime and mtime should be expressed as float seconds since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004902If ns is specified, it must be a tuple (atime_ns, mtime_ns);
Larry Hastings2f936352014-08-05 14:04:04 +10004903 atime_ns and mtime_ns should be expressed as integer nanoseconds
4904 since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004905If times is None and ns is unspecified, utime uses the current time.
Larry Hastings2f936352014-08-05 14:04:04 +10004906Specifying tuples for both times and ns is an error.
4907
4908If dir_fd is not None, it should be a file descriptor open to a directory,
4909 and path should be relative; path will then be relative to that directory.
4910If follow_symlinks is False, and the last element of the path is a symbolic
4911 link, utime will modify the symbolic link itself instead of the file the
4912 link points to.
4913It is an error to use dir_fd or follow_symlinks when specifying path
4914 as an open file descriptor.
4915dir_fd and follow_symlinks may not be available on your platform.
4916 If they are unavailable, using them will raise a NotImplementedError.
4917
4918[clinic start generated code]*/
4919
Larry Hastings2f936352014-08-05 14:04:04 +10004920static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004921os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
4922 int dir_fd, int follow_symlinks)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004923/*[clinic end generated code: output=cfcac69d027b82cf input=2fbd62a2f228f8f4]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004924{
Larry Hastings9cf065c2012-06-22 16:30:09 -07004925#ifdef MS_WINDOWS
4926 HANDLE hFile;
4927 FILETIME atime, mtime;
4928#else
4929 int result;
4930#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004931
Larry Hastings2f936352014-08-05 14:04:04 +10004932 utime_t utime;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004933
Christian Heimesb3c87242013-08-01 00:08:16 +02004934 memset(&utime, 0, sizeof(utime_t));
Larry Hastings76ad59b2012-05-03 00:30:07 -07004935
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004936 if (times != Py_None && ns) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004937 PyErr_SetString(PyExc_ValueError,
4938 "utime: you may specify either 'times'"
4939 " or 'ns' but not both");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004940 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004941 }
4942
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004943 if (times != Py_None) {
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004944 time_t a_sec, m_sec;
4945 long a_nsec, m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004946 if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004947 PyErr_SetString(PyExc_TypeError,
4948 "utime: 'times' must be either"
4949 " a tuple of two ints or None");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004950 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004951 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004952 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004953 if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004954 &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004955 _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004956 &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004957 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004958 }
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004959 utime.atime_s = a_sec;
4960 utime.atime_ns = a_nsec;
4961 utime.mtime_s = m_sec;
4962 utime.mtime_ns = m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004963 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004964 else if (ns) {
Larry Hastings76ad59b2012-05-03 00:30:07 -07004965 if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004966 PyErr_SetString(PyExc_TypeError,
4967 "utime: 'ns' must be a tuple of two ints");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004968 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004969 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004970 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004971 if (!split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 0),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004972 &utime.atime_s, &utime.atime_ns) ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004973 !split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 1),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004974 &utime.mtime_s, &utime.mtime_ns)) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004975 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004976 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004977 }
4978 else {
4979 /* times and ns are both None/unspecified. use "now". */
4980 utime.now = 1;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004981 }
4982
Victor Stinner4552ced2015-09-21 22:37:15 +02004983#if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004984 if (follow_symlinks_specified("utime", follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004985 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004986#endif
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004987
Larry Hastings2f936352014-08-05 14:04:04 +10004988 if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
4989 dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
4990 fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004991 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004992
Larry Hastings9cf065c2012-06-22 16:30:09 -07004993#if !defined(HAVE_UTIMENSAT)
4994 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
Georg Brandl969288e2012-06-26 09:25:44 +02004995 PyErr_SetString(PyExc_ValueError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07004996 "utime: cannot use dir_fd and follow_symlinks "
4997 "together on this platform");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004998 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004999 }
5000#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07005001
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005002 if (PySys_Audit("os.utime", "OOOi", path->object, times, ns ? ns : Py_None,
5003 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
5004 return NULL;
5005 }
5006
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00005007#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07005008 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07005009 hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
5010 NULL, OPEN_EXISTING,
5011 FILE_FLAG_BACKUP_SEMANTICS, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005012 Py_END_ALLOW_THREADS
5013 if (hFile == INVALID_HANDLE_VALUE) {
Larry Hastings2f936352014-08-05 14:04:04 +10005014 path_error(path);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005015 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07005016 }
5017
Larry Hastings9cf065c2012-06-22 16:30:09 -07005018 if (utime.now) {
Antoine Pitrou91a7af32013-11-23 15:23:26 +01005019 GetSystemTimeAsFileTime(&mtime);
5020 atime = mtime;
Victor Stinner8c62be82010-05-06 00:08:46 +00005021 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005022 else {
Steve Dowerbf1f3762015-02-21 15:26:02 -08005023 _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
5024 _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
Victor Stinner8c62be82010-05-06 00:08:46 +00005025 }
5026 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
5027 /* Avoid putting the file name into the error here,
5028 as that may confuse the user into believing that
5029 something is wrong with the file, when it also
5030 could be the time stamp that gives a problem. */
Victor Stinnerb024e842012-10-31 22:24:06 +01005031 PyErr_SetFromWindowsErr(0);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005032 CloseHandle(hFile);
5033 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00005034 }
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005035 CloseHandle(hFile);
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00005036#else /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07005037 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00005038
Victor Stinner4552ced2015-09-21 22:37:15 +02005039#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07005040 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10005041 result = utime_nofollow_symlinks(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005042 else
Larry Hastings9e3e70b2011-09-08 19:29:07 -07005043#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07005044
Victor Stinner528a9ab2015-09-03 21:30:26 +02005045#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07005046 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10005047 result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005048 else
5049#endif
5050
Victor Stinner528a9ab2015-09-03 21:30:26 +02005051#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings2f936352014-08-05 14:04:04 +10005052 if (path->fd != -1)
5053 result = utime_fd(&utime, path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005054 else
5055#endif
5056
Larry Hastings2f936352014-08-05 14:04:04 +10005057 result = utime_default(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005058
5059 Py_END_ALLOW_THREADS
5060
5061 if (result < 0) {
5062 /* see previous comment about not putting filename in error here */
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005063 posix_error();
5064 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00005065 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07005066
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00005067#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07005068
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005069 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005070}
5071
Guido van Rossum3b066191991-06-04 19:40:25 +00005072/* Process operations */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005073
Larry Hastings2f936352014-08-05 14:04:04 +10005074
5075/*[clinic input]
5076os._exit
5077
5078 status: int
5079
5080Exit to the system with specified status, without normal exit processing.
5081[clinic start generated code]*/
5082
Larry Hastings2f936352014-08-05 14:04:04 +10005083static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005084os__exit_impl(PyObject *module, int status)
5085/*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005086{
5087 _exit(status);
Victor Stinner8c62be82010-05-06 00:08:46 +00005088 return NULL; /* Make gcc -Wall happy */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005089}
5090
Steve Dowercc16be82016-09-08 10:35:16 -07005091#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5092#define EXECV_CHAR wchar_t
5093#else
5094#define EXECV_CHAR char
5095#endif
5096
pxinwrf2d7ac72019-05-21 18:46:37 +08005097#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005098static void
Steve Dowercc16be82016-09-08 10:35:16 -07005099free_string_array(EXECV_CHAR **array, Py_ssize_t count)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005100{
Victor Stinner8c62be82010-05-06 00:08:46 +00005101 Py_ssize_t i;
5102 for (i = 0; i < count; i++)
5103 PyMem_Free(array[i]);
5104 PyMem_DEL(array);
Martin v. Löwis114619e2002-10-07 06:44:21 +00005105}
Martin v. Löwis011e8422009-05-05 04:43:17 +00005106
Berker Peksag81816462016-09-15 20:19:47 +03005107static int
5108fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
Martin v. Löwis011e8422009-05-05 04:43:17 +00005109{
Victor Stinner8c62be82010-05-06 00:08:46 +00005110 Py_ssize_t size;
Berker Peksag81816462016-09-15 20:19:47 +03005111 PyObject *ub;
5112 int result = 0;
Steve Dowercc16be82016-09-08 10:35:16 -07005113#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
Berker Peksag81816462016-09-15 20:19:47 +03005114 if (!PyUnicode_FSDecoder(o, &ub))
Steve Dowercc16be82016-09-08 10:35:16 -07005115 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005116 *out = PyUnicode_AsWideCharString(ub, &size);
5117 if (*out)
5118 result = 1;
Steve Dowercc16be82016-09-08 10:35:16 -07005119#else
Berker Peksag81816462016-09-15 20:19:47 +03005120 if (!PyUnicode_FSConverter(o, &ub))
Victor Stinner8c62be82010-05-06 00:08:46 +00005121 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005122 size = PyBytes_GET_SIZE(ub);
5123 *out = PyMem_Malloc(size + 1);
5124 if (*out) {
5125 memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
5126 result = 1;
5127 } else
Victor Stinner50abf222013-11-07 23:56:10 +01005128 PyErr_NoMemory();
Steve Dowercc16be82016-09-08 10:35:16 -07005129#endif
Berker Peksag81816462016-09-15 20:19:47 +03005130 Py_DECREF(ub);
5131 return result;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005132}
Martin v. Löwis114619e2002-10-07 06:44:21 +00005133#endif
5134
pxinwrf2d7ac72019-05-21 18:46:37 +08005135#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
Steve Dowercc16be82016-09-08 10:35:16 -07005136static EXECV_CHAR**
Victor Stinner13bb71c2010-04-23 21:41:56 +00005137parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
5138{
Victor Stinner8c62be82010-05-06 00:08:46 +00005139 Py_ssize_t i, pos, envc;
5140 PyObject *keys=NULL, *vals=NULL;
Berker Peksag81816462016-09-15 20:19:47 +03005141 PyObject *key, *val, *key2, *val2, *keyval;
Steve Dowercc16be82016-09-08 10:35:16 -07005142 EXECV_CHAR **envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005143
Victor Stinner8c62be82010-05-06 00:08:46 +00005144 i = PyMapping_Size(env);
5145 if (i < 0)
5146 return NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07005147 envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005148 if (envlist == NULL) {
5149 PyErr_NoMemory();
5150 return NULL;
5151 }
5152 envc = 0;
5153 keys = PyMapping_Keys(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005154 if (!keys)
5155 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00005156 vals = PyMapping_Values(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005157 if (!vals)
Victor Stinner8c62be82010-05-06 00:08:46 +00005158 goto error;
5159 if (!PyList_Check(keys) || !PyList_Check(vals)) {
5160 PyErr_Format(PyExc_TypeError,
5161 "env.keys() or env.values() is not a list");
5162 goto error;
5163 }
Victor Stinner13bb71c2010-04-23 21:41:56 +00005164
Victor Stinner8c62be82010-05-06 00:08:46 +00005165 for (pos = 0; pos < i; pos++) {
5166 key = PyList_GetItem(keys, pos);
5167 val = PyList_GetItem(vals, pos);
5168 if (!key || !val)
5169 goto error;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005170
Berker Peksag81816462016-09-15 20:19:47 +03005171#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5172 if (!PyUnicode_FSDecoder(key, &key2))
5173 goto error;
5174 if (!PyUnicode_FSDecoder(val, &val2)) {
5175 Py_DECREF(key2);
5176 goto error;
5177 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005178 /* Search from index 1 because on Windows starting '=' is allowed for
5179 defining hidden environment variables. */
5180 if (PyUnicode_GET_LENGTH(key2) == 0 ||
5181 PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
5182 {
5183 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005184 Py_DECREF(key2);
5185 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005186 goto error;
5187 }
Berker Peksag81816462016-09-15 20:19:47 +03005188 keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
5189#else
5190 if (!PyUnicode_FSConverter(key, &key2))
5191 goto error;
5192 if (!PyUnicode_FSConverter(val, &val2)) {
5193 Py_DECREF(key2);
5194 goto error;
5195 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005196 if (PyBytes_GET_SIZE(key2) == 0 ||
5197 strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
5198 {
5199 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005200 Py_DECREF(key2);
5201 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005202 goto error;
5203 }
Berker Peksag81816462016-09-15 20:19:47 +03005204 keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
5205 PyBytes_AS_STRING(val2));
5206#endif
5207 Py_DECREF(key2);
5208 Py_DECREF(val2);
Steve Dowercc16be82016-09-08 10:35:16 -07005209 if (!keyval)
Victor Stinner8c62be82010-05-06 00:08:46 +00005210 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -07005211
5212 if (!fsconvert_strdup(keyval, &envlist[envc++])) {
5213 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005214 goto error;
5215 }
Berker Peksag81816462016-09-15 20:19:47 +03005216
Steve Dowercc16be82016-09-08 10:35:16 -07005217 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005218 }
5219 Py_DECREF(vals);
5220 Py_DECREF(keys);
Victor Stinner13bb71c2010-04-23 21:41:56 +00005221
Victor Stinner8c62be82010-05-06 00:08:46 +00005222 envlist[envc] = 0;
5223 *envc_ptr = envc;
5224 return envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005225
5226error:
Victor Stinner8c62be82010-05-06 00:08:46 +00005227 Py_XDECREF(keys);
5228 Py_XDECREF(vals);
Steve Dowercc16be82016-09-08 10:35:16 -07005229 free_string_array(envlist, envc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005230 return NULL;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005231}
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005232
Steve Dowercc16be82016-09-08 10:35:16 -07005233static EXECV_CHAR**
Ross Lagerwall7807c352011-03-17 20:20:30 +02005234parse_arglist(PyObject* argv, Py_ssize_t *argc)
5235{
5236 int i;
Steve Dowercc16be82016-09-08 10:35:16 -07005237 EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005238 if (argvlist == NULL) {
5239 PyErr_NoMemory();
5240 return NULL;
5241 }
5242 for (i = 0; i < *argc; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005243 PyObject* item = PySequence_ITEM(argv, i);
5244 if (item == NULL)
5245 goto fail;
5246 if (!fsconvert_strdup(item, &argvlist[i])) {
5247 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005248 goto fail;
5249 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005250 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005251 }
5252 argvlist[*argc] = NULL;
5253 return argvlist;
5254fail:
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005255 *argc = i;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005256 free_string_array(argvlist, *argc);
5257 return NULL;
5258}
Steve Dowercc16be82016-09-08 10:35:16 -07005259
Ross Lagerwall7807c352011-03-17 20:20:30 +02005260#endif
5261
Larry Hastings2f936352014-08-05 14:04:04 +10005262
Ross Lagerwall7807c352011-03-17 20:20:30 +02005263#ifdef HAVE_EXECV
Larry Hastings2f936352014-08-05 14:04:04 +10005264/*[clinic input]
5265os.execv
5266
Steve Dowercc16be82016-09-08 10:35:16 -07005267 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005268 Path of executable file.
5269 argv: object
5270 Tuple or list of strings.
5271 /
5272
5273Execute an executable path with arguments, replacing current process.
5274[clinic start generated code]*/
5275
Larry Hastings2f936352014-08-05 14:04:04 +10005276static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005277os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
5278/*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005279{
Steve Dowercc16be82016-09-08 10:35:16 -07005280 EXECV_CHAR **argvlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005281 Py_ssize_t argc;
5282
5283 /* execv has two arguments: (path, argv), where
5284 argv is a list or tuple of strings. */
5285
Ross Lagerwall7807c352011-03-17 20:20:30 +02005286 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
5287 PyErr_SetString(PyExc_TypeError,
5288 "execv() arg 2 must be a tuple or list");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005289 return NULL;
5290 }
5291 argc = PySequence_Size(argv);
5292 if (argc < 1) {
5293 PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005294 return NULL;
5295 }
5296
5297 argvlist = parse_arglist(argv, &argc);
5298 if (argvlist == NULL) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02005299 return NULL;
5300 }
Steve Dowerbce26262016-11-19 19:17:26 -08005301 if (!argvlist[0][0]) {
5302 PyErr_SetString(PyExc_ValueError,
5303 "execv() arg 2 first element cannot be empty");
5304 free_string_array(argvlist, argc);
5305 return NULL;
5306 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005307
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005308 if (PySys_Audit("os.exec", "OOO", path->object, argv, Py_None) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -08005309 free_string_array(argvlist, argc);
5310 return NULL;
5311 }
5312
Steve Dowerbce26262016-11-19 19:17:26 -08005313 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005314#ifdef HAVE_WEXECV
5315 _wexecv(path->wide, argvlist);
5316#else
5317 execv(path->narrow, argvlist);
5318#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005319 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005320
5321 /* If we get here it's definitely an error */
5322
5323 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005324 return posix_error();
5325}
5326
Larry Hastings2f936352014-08-05 14:04:04 +10005327
5328/*[clinic input]
5329os.execve
5330
5331 path: path_t(allow_fd='PATH_HAVE_FEXECVE')
5332 Path of executable file.
5333 argv: object
5334 Tuple or list of strings.
5335 env: object
5336 Dictionary of strings mapping to strings.
5337
5338Execute an executable path with arguments, replacing current process.
5339[clinic start generated code]*/
5340
Larry Hastings2f936352014-08-05 14:04:04 +10005341static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005342os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
5343/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005344{
Steve Dowercc16be82016-09-08 10:35:16 -07005345 EXECV_CHAR **argvlist = NULL;
5346 EXECV_CHAR **envlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005347 Py_ssize_t argc, envc;
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005348
Victor Stinner8c62be82010-05-06 00:08:46 +00005349 /* execve has three arguments: (path, argv, env), where
5350 argv is a list or tuple of strings and env is a dictionary
5351 like posix.environ. */
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005352
Ross Lagerwall7807c352011-03-17 20:20:30 +02005353 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005354 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005355 "execve: argv must be a tuple or list");
Saiyang Gou95f60012020-02-04 16:15:00 -08005356 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005357 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005358 argc = PySequence_Size(argv);
Steve Dowerbce26262016-11-19 19:17:26 -08005359 if (argc < 1) {
5360 PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
5361 return NULL;
5362 }
5363
Victor Stinner8c62be82010-05-06 00:08:46 +00005364 if (!PyMapping_Check(env)) {
5365 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005366 "execve: environment must be a mapping object");
Saiyang Gou95f60012020-02-04 16:15:00 -08005367 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005368 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005369
Ross Lagerwall7807c352011-03-17 20:20:30 +02005370 argvlist = parse_arglist(argv, &argc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005371 if (argvlist == NULL) {
Saiyang Gou95f60012020-02-04 16:15:00 -08005372 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005373 }
Steve Dowerbce26262016-11-19 19:17:26 -08005374 if (!argvlist[0][0]) {
5375 PyErr_SetString(PyExc_ValueError,
5376 "execve: argv first element cannot be empty");
Saiyang Gou95f60012020-02-04 16:15:00 -08005377 goto fail_0;
Steve Dowerbce26262016-11-19 19:17:26 -08005378 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005379
Victor Stinner8c62be82010-05-06 00:08:46 +00005380 envlist = parse_envlist(env, &envc);
5381 if (envlist == NULL)
Saiyang Gou95f60012020-02-04 16:15:00 -08005382 goto fail_0;
5383
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005384 if (PySys_Audit("os.exec", "OOO", path->object, argv, env) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -08005385 goto fail_1;
5386 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005387
Steve Dowerbce26262016-11-19 19:17:26 -08005388 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07005389#ifdef HAVE_FEXECVE
Larry Hastings2f936352014-08-05 14:04:04 +10005390 if (path->fd > -1)
5391 fexecve(path->fd, argvlist, envlist);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005392 else
5393#endif
Steve Dowercc16be82016-09-08 10:35:16 -07005394#ifdef HAVE_WEXECV
5395 _wexecve(path->wide, argvlist, envlist);
5396#else
Larry Hastings2f936352014-08-05 14:04:04 +10005397 execve(path->narrow, argvlist, envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07005398#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005399 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005400
5401 /* If we get here it's definitely an error */
5402
Alexey Izbyshev83460312018-10-20 03:28:22 +03005403 posix_path_error(path);
Saiyang Gou95f60012020-02-04 16:15:00 -08005404 fail_1:
Steve Dowercc16be82016-09-08 10:35:16 -07005405 free_string_array(envlist, envc);
Saiyang Gou95f60012020-02-04 16:15:00 -08005406 fail_0:
Larry Hastings9cf065c2012-06-22 16:30:09 -07005407 if (argvlist)
5408 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005409 return NULL;
5410}
Steve Dowercc16be82016-09-08 10:35:16 -07005411
Larry Hastings9cf065c2012-06-22 16:30:09 -07005412#endif /* HAVE_EXECV */
5413
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005414#ifdef HAVE_POSIX_SPAWN
5415
5416enum posix_spawn_file_actions_identifier {
5417 POSIX_SPAWN_OPEN,
5418 POSIX_SPAWN_CLOSE,
5419 POSIX_SPAWN_DUP2
5420};
5421
William Orr81574b82018-10-01 22:19:56 -07005422#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005423static int
Pablo Galindo254a4662018-09-07 16:44:24 +01005424convert_sched_param(PyObject *param, struct sched_param *res);
William Orr81574b82018-10-01 22:19:56 -07005425#endif
Pablo Galindo254a4662018-09-07 16:44:24 +01005426
5427static int
Victor Stinner325e4ba2019-02-01 15:47:24 +01005428parse_posix_spawn_flags(const char *func_name, PyObject *setpgroup,
5429 int resetids, int setsid, PyObject *setsigmask,
Pablo Galindo254a4662018-09-07 16:44:24 +01005430 PyObject *setsigdef, PyObject *scheduler,
5431 posix_spawnattr_t *attrp)
5432{
5433 long all_flags = 0;
5434
5435 errno = posix_spawnattr_init(attrp);
5436 if (errno) {
5437 posix_error();
5438 return -1;
5439 }
5440
5441 if (setpgroup) {
5442 pid_t pgid = PyLong_AsPid(setpgroup);
5443 if (pgid == (pid_t)-1 && PyErr_Occurred()) {
5444 goto fail;
5445 }
5446 errno = posix_spawnattr_setpgroup(attrp, pgid);
5447 if (errno) {
5448 posix_error();
5449 goto fail;
5450 }
5451 all_flags |= POSIX_SPAWN_SETPGROUP;
5452 }
5453
5454 if (resetids) {
5455 all_flags |= POSIX_SPAWN_RESETIDS;
5456 }
5457
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005458 if (setsid) {
5459#ifdef POSIX_SPAWN_SETSID
5460 all_flags |= POSIX_SPAWN_SETSID;
5461#elif defined(POSIX_SPAWN_SETSID_NP)
5462 all_flags |= POSIX_SPAWN_SETSID_NP;
5463#else
5464 argument_unavailable_error(func_name, "setsid");
5465 return -1;
5466#endif
5467 }
5468
Pablo Galindo254a4662018-09-07 16:44:24 +01005469 if (setsigmask) {
5470 sigset_t set;
5471 if (!_Py_Sigset_Converter(setsigmask, &set)) {
5472 goto fail;
5473 }
5474 errno = posix_spawnattr_setsigmask(attrp, &set);
5475 if (errno) {
5476 posix_error();
5477 goto fail;
5478 }
5479 all_flags |= POSIX_SPAWN_SETSIGMASK;
5480 }
5481
5482 if (setsigdef) {
5483 sigset_t set;
5484 if (!_Py_Sigset_Converter(setsigdef, &set)) {
5485 goto fail;
5486 }
5487 errno = posix_spawnattr_setsigdefault(attrp, &set);
5488 if (errno) {
5489 posix_error();
5490 goto fail;
5491 }
5492 all_flags |= POSIX_SPAWN_SETSIGDEF;
5493 }
5494
5495 if (scheduler) {
5496#ifdef POSIX_SPAWN_SETSCHEDULER
5497 PyObject *py_schedpolicy;
5498 struct sched_param schedparam;
5499
5500 if (!PyArg_ParseTuple(scheduler, "OO&"
5501 ";A scheduler tuple must have two elements",
5502 &py_schedpolicy, convert_sched_param, &schedparam)) {
5503 goto fail;
5504 }
5505 if (py_schedpolicy != Py_None) {
5506 int schedpolicy = _PyLong_AsInt(py_schedpolicy);
5507
5508 if (schedpolicy == -1 && PyErr_Occurred()) {
5509 goto fail;
5510 }
5511 errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
5512 if (errno) {
5513 posix_error();
5514 goto fail;
5515 }
5516 all_flags |= POSIX_SPAWN_SETSCHEDULER;
5517 }
5518 errno = posix_spawnattr_setschedparam(attrp, &schedparam);
5519 if (errno) {
5520 posix_error();
5521 goto fail;
5522 }
5523 all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
5524#else
5525 PyErr_SetString(PyExc_NotImplementedError,
5526 "The scheduler option is not supported in this system.");
5527 goto fail;
5528#endif
5529 }
5530
5531 errno = posix_spawnattr_setflags(attrp, all_flags);
5532 if (errno) {
5533 posix_error();
5534 goto fail;
5535 }
5536
5537 return 0;
5538
5539fail:
5540 (void)posix_spawnattr_destroy(attrp);
5541 return -1;
5542}
5543
5544static int
Serhiy Storchakaef347532018-05-01 16:45:04 +03005545parse_file_actions(PyObject *file_actions,
Pablo Galindocb970732018-06-19 09:19:50 +01005546 posix_spawn_file_actions_t *file_actionsp,
5547 PyObject *temp_buffer)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005548{
5549 PyObject *seq;
5550 PyObject *file_action = NULL;
5551 PyObject *tag_obj;
5552
5553 seq = PySequence_Fast(file_actions,
5554 "file_actions must be a sequence or None");
5555 if (seq == NULL) {
5556 return -1;
5557 }
5558
5559 errno = posix_spawn_file_actions_init(file_actionsp);
5560 if (errno) {
5561 posix_error();
5562 Py_DECREF(seq);
5563 return -1;
5564 }
5565
Zackery Spytzd52a83a2019-06-26 14:54:20 -06005566 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
Serhiy Storchakaef347532018-05-01 16:45:04 +03005567 file_action = PySequence_Fast_GET_ITEM(seq, i);
5568 Py_INCREF(file_action);
5569 if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
5570 PyErr_SetString(PyExc_TypeError,
5571 "Each file_actions element must be a non-empty tuple");
5572 goto fail;
5573 }
5574 long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
5575 if (tag == -1 && PyErr_Occurred()) {
5576 goto fail;
5577 }
5578
5579 /* Populate the file_actions object */
5580 switch (tag) {
5581 case POSIX_SPAWN_OPEN: {
5582 int fd, oflag;
5583 PyObject *path;
5584 unsigned long mode;
5585 if (!PyArg_ParseTuple(file_action, "OiO&ik"
5586 ";A open file_action tuple must have 5 elements",
5587 &tag_obj, &fd, PyUnicode_FSConverter, &path,
5588 &oflag, &mode))
5589 {
5590 goto fail;
5591 }
Pablo Galindocb970732018-06-19 09:19:50 +01005592 if (PyList_Append(temp_buffer, path)) {
5593 Py_DECREF(path);
5594 goto fail;
5595 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005596 errno = posix_spawn_file_actions_addopen(file_actionsp,
5597 fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
Pablo Galindocb970732018-06-19 09:19:50 +01005598 Py_DECREF(path);
Serhiy Storchakaef347532018-05-01 16:45:04 +03005599 if (errno) {
5600 posix_error();
5601 goto fail;
5602 }
5603 break;
5604 }
5605 case POSIX_SPAWN_CLOSE: {
5606 int fd;
5607 if (!PyArg_ParseTuple(file_action, "Oi"
5608 ";A close file_action tuple must have 2 elements",
5609 &tag_obj, &fd))
5610 {
5611 goto fail;
5612 }
5613 errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
5614 if (errno) {
5615 posix_error();
5616 goto fail;
5617 }
5618 break;
5619 }
5620 case POSIX_SPAWN_DUP2: {
5621 int fd1, fd2;
5622 if (!PyArg_ParseTuple(file_action, "Oii"
5623 ";A dup2 file_action tuple must have 3 elements",
5624 &tag_obj, &fd1, &fd2))
5625 {
5626 goto fail;
5627 }
5628 errno = posix_spawn_file_actions_adddup2(file_actionsp,
5629 fd1, fd2);
5630 if (errno) {
5631 posix_error();
5632 goto fail;
5633 }
5634 break;
5635 }
5636 default: {
5637 PyErr_SetString(PyExc_TypeError,
5638 "Unknown file_actions identifier");
5639 goto fail;
5640 }
5641 }
5642 Py_DECREF(file_action);
5643 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005644
Serhiy Storchakaef347532018-05-01 16:45:04 +03005645 Py_DECREF(seq);
5646 return 0;
5647
5648fail:
5649 Py_DECREF(seq);
5650 Py_DECREF(file_action);
5651 (void)posix_spawn_file_actions_destroy(file_actionsp);
5652 return -1;
5653}
5654
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005655
5656static PyObject *
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005657py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
5658 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005659 PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005660 PyObject *setsigdef, PyObject *scheduler)
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005661{
Victor Stinner325e4ba2019-02-01 15:47:24 +01005662 const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005663 EXECV_CHAR **argvlist = NULL;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005664 EXECV_CHAR **envlist = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005665 posix_spawn_file_actions_t file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005666 posix_spawn_file_actions_t *file_actionsp = NULL;
Pablo Galindo254a4662018-09-07 16:44:24 +01005667 posix_spawnattr_t attr;
5668 posix_spawnattr_t *attrp = NULL;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005669 Py_ssize_t argc, envc;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005670 PyObject *result = NULL;
Pablo Galindocb970732018-06-19 09:19:50 +01005671 PyObject *temp_buffer = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005672 pid_t pid;
5673 int err_code;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005674
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005675 /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
Serhiy Storchakaef347532018-05-01 16:45:04 +03005676 argv is a list or tuple of strings and env is a dictionary
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005677 like posix.environ. */
5678
Serhiy Storchakaef347532018-05-01 16:45:04 +03005679 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005680 PyErr_Format(PyExc_TypeError,
5681 "%s: argv must be a tuple or list", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005682 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005683 }
5684 argc = PySequence_Size(argv);
5685 if (argc < 1) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005686 PyErr_Format(PyExc_ValueError,
5687 "%s: argv must not be empty", func_name);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005688 return NULL;
5689 }
5690
5691 if (!PyMapping_Check(env)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005692 PyErr_Format(PyExc_TypeError,
5693 "%s: environment must be a mapping object", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005694 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005695 }
5696
5697 argvlist = parse_arglist(argv, &argc);
5698 if (argvlist == NULL) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005699 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005700 }
5701 if (!argvlist[0][0]) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005702 PyErr_Format(PyExc_ValueError,
5703 "%s: argv first element cannot be empty", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005704 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005705 }
5706
5707 envlist = parse_envlist(env, &envc);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005708 if (envlist == NULL) {
5709 goto exit;
5710 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005711
Anthony Shaw948ed8c2019-05-10 12:00:06 +10005712 if (file_actions != NULL && file_actions != Py_None) {
Pablo Galindocb970732018-06-19 09:19:50 +01005713 /* There is a bug in old versions of glibc that makes some of the
5714 * helper functions for manipulating file actions not copy the provided
5715 * buffers. The problem is that posix_spawn_file_actions_addopen does not
5716 * copy the value of path for some old versions of glibc (<2.20).
5717 * The use of temp_buffer here is a workaround that keeps the
5718 * python objects that own the buffers alive until posix_spawn gets called.
5719 * Check https://bugs.python.org/issue33630 and
5720 * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
5721 temp_buffer = PyList_New(0);
5722 if (!temp_buffer) {
5723 goto exit;
5724 }
5725 if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005726 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005727 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005728 file_actionsp = &file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005729 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005730
Victor Stinner325e4ba2019-02-01 15:47:24 +01005731 if (parse_posix_spawn_flags(func_name, setpgroup, resetids, setsid,
5732 setsigmask, setsigdef, scheduler, &attr)) {
Pablo Galindo254a4662018-09-07 16:44:24 +01005733 goto exit;
5734 }
5735 attrp = &attr;
5736
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005737 if (PySys_Audit("os.posix_spawn", "OOO", path->object, argv, env) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -08005738 goto exit;
5739 }
5740
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005741 _Py_BEGIN_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005742#ifdef HAVE_POSIX_SPAWNP
5743 if (use_posix_spawnp) {
5744 err_code = posix_spawnp(&pid, path->narrow,
5745 file_actionsp, attrp, argvlist, envlist);
5746 }
5747 else
5748#endif /* HAVE_POSIX_SPAWNP */
5749 {
5750 err_code = posix_spawn(&pid, path->narrow,
5751 file_actionsp, attrp, argvlist, envlist);
5752 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005753 _Py_END_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005754
Serhiy Storchakaef347532018-05-01 16:45:04 +03005755 if (err_code) {
5756 errno = err_code;
5757 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005758 goto exit;
5759 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08005760#ifdef _Py_MEMORY_SANITIZER
5761 __msan_unpoison(&pid, sizeof(pid));
5762#endif
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005763 result = PyLong_FromPid(pid);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005764
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005765exit:
Serhiy Storchakaef347532018-05-01 16:45:04 +03005766 if (file_actionsp) {
5767 (void)posix_spawn_file_actions_destroy(file_actionsp);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005768 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005769 if (attrp) {
5770 (void)posix_spawnattr_destroy(attrp);
5771 }
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005772 if (envlist) {
5773 free_string_array(envlist, envc);
5774 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005775 if (argvlist) {
5776 free_string_array(argvlist, argc);
5777 }
Pablo Galindocb970732018-06-19 09:19:50 +01005778 Py_XDECREF(temp_buffer);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005779 return result;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005780}
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005781
5782
5783/*[clinic input]
5784
5785os.posix_spawn
5786 path: path_t
5787 Path of executable file.
5788 argv: object
5789 Tuple or list of strings.
5790 env: object
5791 Dictionary of strings mapping to strings.
5792 /
5793 *
5794 file_actions: object(c_default='NULL') = ()
5795 A sequence of file action tuples.
5796 setpgroup: object = NULL
5797 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5798 resetids: bool(accept={int}) = False
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005799 If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
5800 setsid: bool(accept={int}) = False
5801 If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005802 setsigmask: object(c_default='NULL') = ()
5803 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5804 setsigdef: object(c_default='NULL') = ()
5805 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5806 scheduler: object = NULL
5807 A tuple with the scheduler policy (optional) and parameters.
5808
5809Execute the program specified by path in a new process.
5810[clinic start generated code]*/
5811
5812static PyObject *
5813os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
5814 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005815 PyObject *setpgroup, int resetids, int setsid,
5816 PyObject *setsigmask, PyObject *setsigdef,
5817 PyObject *scheduler)
5818/*[clinic end generated code: output=14a1098c566bc675 input=8c6305619a00ad04]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005819{
5820 return py_posix_spawn(0, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005821 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005822 scheduler);
5823}
5824 #endif /* HAVE_POSIX_SPAWN */
5825
5826
5827
5828#ifdef HAVE_POSIX_SPAWNP
5829/*[clinic input]
5830
5831os.posix_spawnp
5832 path: path_t
5833 Path of executable file.
5834 argv: object
5835 Tuple or list of strings.
5836 env: object
5837 Dictionary of strings mapping to strings.
5838 /
5839 *
5840 file_actions: object(c_default='NULL') = ()
5841 A sequence of file action tuples.
5842 setpgroup: object = NULL
5843 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5844 resetids: bool(accept={int}) = False
5845 If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005846 setsid: bool(accept={int}) = False
5847 If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005848 setsigmask: object(c_default='NULL') = ()
5849 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5850 setsigdef: object(c_default='NULL') = ()
5851 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5852 scheduler: object = NULL
5853 A tuple with the scheduler policy (optional) and parameters.
5854
5855Execute the program specified by path in a new process.
5856[clinic start generated code]*/
5857
5858static PyObject *
5859os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
5860 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005861 PyObject *setpgroup, int resetids, int setsid,
5862 PyObject *setsigmask, PyObject *setsigdef,
5863 PyObject *scheduler)
5864/*[clinic end generated code: output=7b9aaefe3031238d input=c1911043a22028da]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005865{
5866 return py_posix_spawn(1, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005867 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005868 scheduler);
5869}
5870#endif /* HAVE_POSIX_SPAWNP */
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005871
pxinwrf2d7ac72019-05-21 18:46:37 +08005872#ifdef HAVE_RTPSPAWN
5873static intptr_t
5874_rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
5875 const char *envp[])
5876{
5877 RTP_ID rtpid;
5878 int status;
5879 pid_t res;
5880 int async_err = 0;
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005881
pxinwrf2d7ac72019-05-21 18:46:37 +08005882 /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
5883 uStackSize=0 cannot be used, the default stack size is too small for
5884 Python. */
5885 if (envp) {
5886 rtpid = rtpSpawn(rtpFileName, argv, envp,
5887 100, 0x1000000, 0, VX_FP_TASK);
5888 }
5889 else {
5890 rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
5891 100, 0x1000000, 0, VX_FP_TASK);
5892 }
5893 if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
5894 do {
5895 res = waitpid((pid_t)rtpid, &status, 0);
5896 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
5897
5898 if (res < 0)
5899 return RTP_ID_ERROR;
5900 return ((intptr_t)status);
5901 }
5902 return ((intptr_t)rtpid);
5903}
5904#endif
5905
5906#if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
Larry Hastings2f936352014-08-05 14:04:04 +10005907/*[clinic input]
5908os.spawnv
5909
5910 mode: int
5911 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005912 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005913 Path of executable file.
5914 argv: object
5915 Tuple or list of strings.
5916 /
5917
5918Execute the program specified by path in a new process.
5919[clinic start generated code]*/
5920
Larry Hastings2f936352014-08-05 14:04:04 +10005921static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005922os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
5923/*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005924{
Steve Dowercc16be82016-09-08 10:35:16 -07005925 EXECV_CHAR **argvlist;
Larry Hastings2f936352014-08-05 14:04:04 +10005926 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00005927 Py_ssize_t argc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005928 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005929 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Guido van Rossuma1065681999-01-25 23:20:23 +00005930
Victor Stinner8c62be82010-05-06 00:08:46 +00005931 /* spawnv has three arguments: (mode, path, argv), where
5932 argv is a list or tuple of strings. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005933
Victor Stinner8c62be82010-05-06 00:08:46 +00005934 if (PyList_Check(argv)) {
5935 argc = PyList_Size(argv);
5936 getitem = PyList_GetItem;
5937 }
5938 else if (PyTuple_Check(argv)) {
5939 argc = PyTuple_Size(argv);
5940 getitem = PyTuple_GetItem;
5941 }
5942 else {
5943 PyErr_SetString(PyExc_TypeError,
5944 "spawnv() arg 2 must be a tuple or list");
Victor Stinner8c62be82010-05-06 00:08:46 +00005945 return NULL;
5946 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005947 if (argc == 0) {
5948 PyErr_SetString(PyExc_ValueError,
5949 "spawnv() arg 2 cannot be empty");
5950 return NULL;
5951 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005952
Steve Dowercc16be82016-09-08 10:35:16 -07005953 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005954 if (argvlist == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005955 return PyErr_NoMemory();
5956 }
5957 for (i = 0; i < argc; i++) {
5958 if (!fsconvert_strdup((*getitem)(argv, i),
5959 &argvlist[i])) {
5960 free_string_array(argvlist, i);
5961 PyErr_SetString(
5962 PyExc_TypeError,
5963 "spawnv() arg 2 must contain only strings");
Victor Stinner8c62be82010-05-06 00:08:46 +00005964 return NULL;
5965 }
Steve Dower93ff8722016-11-19 19:03:54 -08005966 if (i == 0 && !argvlist[0][0]) {
Victor Stinner8acb4cf2017-06-15 15:30:40 +02005967 free_string_array(argvlist, i + 1);
Steve Dower93ff8722016-11-19 19:03:54 -08005968 PyErr_SetString(
5969 PyExc_ValueError,
5970 "spawnv() arg 2 first element cannot be empty");
5971 return NULL;
5972 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005973 }
5974 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005975
pxinwrf2d7ac72019-05-21 18:46:37 +08005976#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00005977 if (mode == _OLD_P_OVERLAY)
5978 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08005979#endif
Tim Peters5aa91602002-01-30 05:46:57 +00005980
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005981 if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv,
Saiyang Gou95f60012020-02-04 16:15:00 -08005982 Py_None) < 0) {
5983 free_string_array(argvlist, argc);
5984 return NULL;
5985 }
5986
Victor Stinner8c62be82010-05-06 00:08:46 +00005987 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07005988 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005989#ifdef HAVE_WSPAWNV
5990 spawnval = _wspawnv(mode, path->wide, argvlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08005991#elif defined(HAVE_RTPSPAWN)
5992 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
Steve Dowercc16be82016-09-08 10:35:16 -07005993#else
5994 spawnval = _spawnv(mode, path->narrow, argvlist);
5995#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07005996 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00005997 Py_END_ALLOW_THREADS
Tim Peters5aa91602002-01-30 05:46:57 +00005998
Victor Stinner8c62be82010-05-06 00:08:46 +00005999 free_string_array(argvlist, argc);
Guido van Rossuma1065681999-01-25 23:20:23 +00006000
Victor Stinner8c62be82010-05-06 00:08:46 +00006001 if (spawnval == -1)
6002 return posix_error();
6003 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01006004 return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00006005}
6006
Larry Hastings2f936352014-08-05 14:04:04 +10006007/*[clinic input]
6008os.spawnve
6009
6010 mode: int
6011 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07006012 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10006013 Path of executable file.
6014 argv: object
6015 Tuple or list of strings.
6016 env: object
6017 Dictionary of strings mapping to strings.
6018 /
6019
6020Execute the program specified by path in a new process.
6021[clinic start generated code]*/
6022
Larry Hastings2f936352014-08-05 14:04:04 +10006023static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07006024os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006025 PyObject *env)
Steve Dowercc16be82016-09-08 10:35:16 -07006026/*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006027{
Steve Dowercc16be82016-09-08 10:35:16 -07006028 EXECV_CHAR **argvlist;
6029 EXECV_CHAR **envlist;
Victor Stinner8c62be82010-05-06 00:08:46 +00006030 PyObject *res = NULL;
Antoine Pitrou22e41552010-08-15 18:07:50 +00006031 Py_ssize_t argc, i, envc;
Benjamin Petersonca470632016-09-06 13:47:26 -07006032 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00006033 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006034 Py_ssize_t lastarg = 0;
Guido van Rossuma1065681999-01-25 23:20:23 +00006035
Victor Stinner8c62be82010-05-06 00:08:46 +00006036 /* spawnve has four arguments: (mode, path, argv, env), where
6037 argv is a list or tuple of strings and env is a dictionary
6038 like posix.environ. */
Guido van Rossuma1065681999-01-25 23:20:23 +00006039
Victor Stinner8c62be82010-05-06 00:08:46 +00006040 if (PyList_Check(argv)) {
6041 argc = PyList_Size(argv);
6042 getitem = PyList_GetItem;
6043 }
6044 else if (PyTuple_Check(argv)) {
6045 argc = PyTuple_Size(argv);
6046 getitem = PyTuple_GetItem;
6047 }
6048 else {
6049 PyErr_SetString(PyExc_TypeError,
6050 "spawnve() arg 2 must be a tuple or list");
6051 goto fail_0;
6052 }
Steve Dower859fd7b2016-11-19 18:53:19 -08006053 if (argc == 0) {
6054 PyErr_SetString(PyExc_ValueError,
6055 "spawnve() arg 2 cannot be empty");
6056 goto fail_0;
6057 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006058 if (!PyMapping_Check(env)) {
6059 PyErr_SetString(PyExc_TypeError,
6060 "spawnve() arg 3 must be a mapping object");
6061 goto fail_0;
6062 }
Guido van Rossuma1065681999-01-25 23:20:23 +00006063
Steve Dowercc16be82016-09-08 10:35:16 -07006064 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00006065 if (argvlist == NULL) {
6066 PyErr_NoMemory();
6067 goto fail_0;
6068 }
6069 for (i = 0; i < argc; i++) {
6070 if (!fsconvert_strdup((*getitem)(argv, i),
6071 &argvlist[i]))
6072 {
6073 lastarg = i;
6074 goto fail_1;
6075 }
Steve Dowerbce26262016-11-19 19:17:26 -08006076 if (i == 0 && !argvlist[0][0]) {
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006077 lastarg = i + 1;
Steve Dowerbce26262016-11-19 19:17:26 -08006078 PyErr_SetString(
6079 PyExc_ValueError,
6080 "spawnv() arg 2 first element cannot be empty");
6081 goto fail_1;
6082 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006083 }
6084 lastarg = argc;
6085 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00006086
Victor Stinner8c62be82010-05-06 00:08:46 +00006087 envlist = parse_envlist(env, &envc);
6088 if (envlist == NULL)
6089 goto fail_1;
Guido van Rossuma1065681999-01-25 23:20:23 +00006090
pxinwrf2d7ac72019-05-21 18:46:37 +08006091#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00006092 if (mode == _OLD_P_OVERLAY)
6093 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08006094#endif
Tim Peters25059d32001-12-07 20:35:43 +00006095
Saiyang Gou7514f4f2020-02-12 23:47:42 -08006096 if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv, env) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -08006097 goto fail_2;
6098 }
6099
Victor Stinner8c62be82010-05-06 00:08:46 +00006100 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07006101 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07006102#ifdef HAVE_WSPAWNV
6103 spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08006104#elif defined(HAVE_RTPSPAWN)
6105 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
6106 (const char **)envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07006107#else
6108 spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
6109#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07006110 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00006111 Py_END_ALLOW_THREADS
Tim Peters25059d32001-12-07 20:35:43 +00006112
Victor Stinner8c62be82010-05-06 00:08:46 +00006113 if (spawnval == -1)
6114 (void) posix_error();
6115 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01006116 res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00006117
Saiyang Gou95f60012020-02-04 16:15:00 -08006118 fail_2:
Victor Stinner8c62be82010-05-06 00:08:46 +00006119 while (--envc >= 0)
6120 PyMem_DEL(envlist[envc]);
6121 PyMem_DEL(envlist);
Guido van Rossum0847c5c2002-12-13 18:36:22 +00006122 fail_1:
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006123 free_string_array(argvlist, lastarg);
Martin v. Löwis114619e2002-10-07 06:44:21 +00006124 fail_0:
Victor Stinner8c62be82010-05-06 00:08:46 +00006125 return res;
Guido van Rossuma1065681999-01-25 23:20:23 +00006126}
Andrew MacIntyre69e18c92004-04-04 07:11:43 +00006127
Guido van Rossuma1065681999-01-25 23:20:23 +00006128#endif /* HAVE_SPAWNV */
6129
6130
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006131#ifdef HAVE_FORK
Gregory P. Smith163468a2017-05-29 10:03:41 -07006132
6133/* Helper function to validate arguments.
6134 Returns 0 on success. non-zero on failure with a TypeError raised.
6135 If obj is non-NULL it must be callable. */
6136static int
6137check_null_or_callable(PyObject *obj, const char* obj_name)
6138{
6139 if (obj && !PyCallable_Check(obj)) {
6140 PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
Eddie Elizondob3966632019-11-05 07:16:14 -08006141 obj_name, _PyType_Name(Py_TYPE(obj)));
Gregory P. Smith163468a2017-05-29 10:03:41 -07006142 return -1;
6143 }
6144 return 0;
6145}
6146
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006147/*[clinic input]
6148os.register_at_fork
6149
Gregory P. Smith163468a2017-05-29 10:03:41 -07006150 *
6151 before: object=NULL
6152 A callable to be called in the parent before the fork() syscall.
6153 after_in_child: object=NULL
6154 A callable to be called in the child after fork().
6155 after_in_parent: object=NULL
6156 A callable to be called in the parent after fork().
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006157
Gregory P. Smith163468a2017-05-29 10:03:41 -07006158Register callables to be called when forking a new process.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006159
Gregory P. Smith163468a2017-05-29 10:03:41 -07006160'before' callbacks are called in reverse order.
6161'after_in_child' and 'after_in_parent' callbacks are called in order.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006162
6163[clinic start generated code]*/
6164
6165static PyObject *
Gregory P. Smith163468a2017-05-29 10:03:41 -07006166os_register_at_fork_impl(PyObject *module, PyObject *before,
6167 PyObject *after_in_child, PyObject *after_in_parent)
6168/*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006169{
6170 PyInterpreterState *interp;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006171
Gregory P. Smith163468a2017-05-29 10:03:41 -07006172 if (!before && !after_in_child && !after_in_parent) {
6173 PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
6174 return NULL;
6175 }
6176 if (check_null_or_callable(before, "before") ||
6177 check_null_or_callable(after_in_child, "after_in_child") ||
6178 check_null_or_callable(after_in_parent, "after_in_parent")) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006179 return NULL;
6180 }
Victor Stinner81a7be32020-04-14 15:14:01 +02006181 interp = _PyInterpreterState_GET();
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006182
Gregory P. Smith163468a2017-05-29 10:03:41 -07006183 if (register_at_forker(&interp->before_forkers, before)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006184 return NULL;
6185 }
Gregory P. Smith163468a2017-05-29 10:03:41 -07006186 if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006187 return NULL;
Gregory P. Smith163468a2017-05-29 10:03:41 -07006188 }
6189 if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
6190 return NULL;
6191 }
6192 Py_RETURN_NONE;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006193}
6194#endif /* HAVE_FORK */
6195
6196
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006197#ifdef HAVE_FORK1
Larry Hastings2f936352014-08-05 14:04:04 +10006198/*[clinic input]
6199os.fork1
6200
6201Fork a child process with a single multiplexed (i.e., not bound) thread.
6202
6203Return 0 to child process and PID of child to parent process.
6204[clinic start generated code]*/
6205
Larry Hastings2f936352014-08-05 14:04:04 +10006206static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006207os_fork1_impl(PyObject *module)
6208/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006209{
Victor Stinner8c62be82010-05-06 00:08:46 +00006210 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006211
Victor Stinner81a7be32020-04-14 15:14:01 +02006212 if (_PyInterpreterState_GET() != PyInterpreterState_Main()) {
Eric Snow59032962018-09-14 14:17:20 -07006213 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6214 return NULL;
6215 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006216 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006217 pid = fork1();
6218 if (pid == 0) {
6219 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006220 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006221 } else {
6222 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006223 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006224 }
6225 if (pid == -1)
6226 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006227 return PyLong_FromPid(pid);
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006228}
Larry Hastings2f936352014-08-05 14:04:04 +10006229#endif /* HAVE_FORK1 */
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006230
6231
Guido van Rossumad0ee831995-03-01 10:34:45 +00006232#ifdef HAVE_FORK
Larry Hastings2f936352014-08-05 14:04:04 +10006233/*[clinic input]
6234os.fork
6235
6236Fork a child process.
6237
6238Return 0 to child process and PID of child to parent process.
6239[clinic start generated code]*/
6240
Larry Hastings2f936352014-08-05 14:04:04 +10006241static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006242os_fork_impl(PyObject *module)
6243/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006244{
Victor Stinner8c62be82010-05-06 00:08:46 +00006245 pid_t pid;
Victor Stinner252346a2020-05-01 11:33:44 +02006246 PyInterpreterState *interp = _PyInterpreterState_GET();
6247 if (interp->config._isolated_interpreter) {
6248 PyErr_SetString(PyExc_RuntimeError,
6249 "fork not supported for isolated subinterpreters");
Eric Snow59032962018-09-14 14:17:20 -07006250 return NULL;
6251 }
Saiyang Gou7514f4f2020-02-12 23:47:42 -08006252 if (PySys_Audit("os.fork", NULL) < 0) {
6253 return NULL;
6254 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006255 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006256 pid = fork();
6257 if (pid == 0) {
6258 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006259 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006260 } else {
6261 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006262 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006263 }
6264 if (pid == -1)
6265 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006266 return PyLong_FromPid(pid);
Guido van Rossum85e3b011991-06-03 12:42:10 +00006267}
Larry Hastings2f936352014-08-05 14:04:04 +10006268#endif /* HAVE_FORK */
6269
Guido van Rossum85e3b011991-06-03 12:42:10 +00006270
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006271#ifdef HAVE_SCHED_H
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006272#ifdef HAVE_SCHED_GET_PRIORITY_MAX
Larry Hastings2f936352014-08-05 14:04:04 +10006273/*[clinic input]
6274os.sched_get_priority_max
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006275
Larry Hastings2f936352014-08-05 14:04:04 +10006276 policy: int
6277
6278Get the maximum scheduling priority for policy.
6279[clinic start generated code]*/
6280
Larry Hastings2f936352014-08-05 14:04:04 +10006281static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006282os_sched_get_priority_max_impl(PyObject *module, int policy)
6283/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006284{
6285 int max;
6286
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006287 max = sched_get_priority_max(policy);
6288 if (max < 0)
6289 return posix_error();
6290 return PyLong_FromLong(max);
6291}
6292
Larry Hastings2f936352014-08-05 14:04:04 +10006293
6294/*[clinic input]
6295os.sched_get_priority_min
6296
6297 policy: int
6298
6299Get the minimum scheduling priority for policy.
6300[clinic start generated code]*/
6301
Larry Hastings2f936352014-08-05 14:04:04 +10006302static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006303os_sched_get_priority_min_impl(PyObject *module, int policy)
6304/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006305{
6306 int min = sched_get_priority_min(policy);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006307 if (min < 0)
6308 return posix_error();
6309 return PyLong_FromLong(min);
6310}
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006311#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
6312
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006313
Larry Hastings2f936352014-08-05 14:04:04 +10006314#ifdef HAVE_SCHED_SETSCHEDULER
6315/*[clinic input]
6316os.sched_getscheduler
6317 pid: pid_t
6318 /
6319
Min ho Kimc4cacc82019-07-31 08:16:13 +10006320Get the scheduling policy for the process identified by pid.
Larry Hastings2f936352014-08-05 14:04:04 +10006321
6322Passing 0 for pid returns the scheduling policy for the calling process.
6323[clinic start generated code]*/
6324
Larry Hastings2f936352014-08-05 14:04:04 +10006325static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006326os_sched_getscheduler_impl(PyObject *module, pid_t pid)
Min ho Kimc4cacc82019-07-31 08:16:13 +10006327/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=8d99dac505485ac8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006328{
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006329 int policy;
6330
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006331 policy = sched_getscheduler(pid);
6332 if (policy < 0)
6333 return posix_error();
6334 return PyLong_FromLong(policy);
6335}
Larry Hastings2f936352014-08-05 14:04:04 +10006336#endif /* HAVE_SCHED_SETSCHEDULER */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006337
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006338
William Orr81574b82018-10-01 22:19:56 -07006339#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Larry Hastings2f936352014-08-05 14:04:04 +10006340/*[clinic input]
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006341class os.sched_param "PyObject *" "SchedParamType"
Larry Hastings2f936352014-08-05 14:04:04 +10006342
6343@classmethod
6344os.sched_param.__new__
6345
6346 sched_priority: object
6347 A scheduling parameter.
6348
Eddie Elizondob3966632019-11-05 07:16:14 -08006349Currently has only one field: sched_priority
Larry Hastings2f936352014-08-05 14:04:04 +10006350[clinic start generated code]*/
6351
Larry Hastings2f936352014-08-05 14:04:04 +10006352static PyObject *
6353os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
Eddie Elizondob3966632019-11-05 07:16:14 -08006354/*[clinic end generated code: output=48f4067d60f48c13 input=eb42909a2c0e3e6c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006355{
6356 PyObject *res;
6357
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006358 res = PyStructSequence_New(type);
6359 if (!res)
6360 return NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10006361 Py_INCREF(sched_priority);
6362 PyStructSequence_SET_ITEM(res, 0, sched_priority);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006363 return res;
6364}
6365
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03006366PyDoc_VAR(os_sched_param__doc__);
6367
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006368static PyStructSequence_Field sched_param_fields[] = {
6369 {"sched_priority", "the scheduling priority"},
6370 {0}
6371};
6372
6373static PyStructSequence_Desc sched_param_desc = {
6374 "sched_param", /* name */
Larry Hastings2f936352014-08-05 14:04:04 +10006375 os_sched_param__doc__, /* doc */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006376 sched_param_fields,
6377 1
6378};
6379
6380static int
6381convert_sched_param(PyObject *param, struct sched_param *res)
6382{
6383 long priority;
6384
Andy Lester55728702020-03-06 16:53:17 -06006385 if (!Py_IS_TYPE(param, (PyTypeObject *)_posixstate_global->SchedParamType)) {
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006386 PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
6387 return 0;
6388 }
6389 priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
6390 if (priority == -1 && PyErr_Occurred())
6391 return 0;
6392 if (priority > INT_MAX || priority < INT_MIN) {
6393 PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
6394 return 0;
6395 }
6396 res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
6397 return 1;
6398}
William Orr81574b82018-10-01 22:19:56 -07006399#endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006400
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006401
6402#ifdef HAVE_SCHED_SETSCHEDULER
Larry Hastings2f936352014-08-05 14:04:04 +10006403/*[clinic input]
6404os.sched_setscheduler
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006405
Larry Hastings2f936352014-08-05 14:04:04 +10006406 pid: pid_t
6407 policy: int
6408 param: sched_param
6409 /
6410
6411Set the scheduling policy for the process identified by pid.
6412
6413If pid is 0, the calling process is changed.
6414param is an instance of sched_param.
6415[clinic start generated code]*/
6416
Larry Hastings2f936352014-08-05 14:04:04 +10006417static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006418os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
Larry Hastings89964c42015-04-14 18:07:59 -04006419 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006420/*[clinic end generated code: output=b0ac0a70d3b1d705 input=c581f9469a5327dd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006421{
Jesus Cea9c822272011-09-10 01:40:52 +02006422 /*
Jesus Cea54b01492011-09-10 01:53:19 +02006423 ** sched_setscheduler() returns 0 in Linux, but the previous
6424 ** scheduling policy under Solaris/Illumos, and others.
6425 ** On error, -1 is returned in all Operating Systems.
Jesus Cea9c822272011-09-10 01:40:52 +02006426 */
Larry Hastings2f936352014-08-05 14:04:04 +10006427 if (sched_setscheduler(pid, policy, param) == -1)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006428 return posix_error();
6429 Py_RETURN_NONE;
6430}
Larry Hastings2f936352014-08-05 14:04:04 +10006431#endif /* HAVE_SCHED_SETSCHEDULER*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006432
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006433
6434#ifdef HAVE_SCHED_SETPARAM
Larry Hastings2f936352014-08-05 14:04:04 +10006435/*[clinic input]
6436os.sched_getparam
6437 pid: pid_t
6438 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006439
Larry Hastings2f936352014-08-05 14:04:04 +10006440Returns scheduling parameters for the process identified by pid.
6441
6442If pid is 0, returns parameters for the calling process.
6443Return value is an instance of sched_param.
6444[clinic start generated code]*/
6445
Larry Hastings2f936352014-08-05 14:04:04 +10006446static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006447os_sched_getparam_impl(PyObject *module, pid_t pid)
6448/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006449{
6450 struct sched_param param;
6451 PyObject *result;
6452 PyObject *priority;
6453
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006454 if (sched_getparam(pid, &param))
6455 return posix_error();
Eddie Elizondob3966632019-11-05 07:16:14 -08006456 PyObject *SchedParamType = _posixstate_global->SchedParamType;
6457 result = PyStructSequence_New((PyTypeObject *)SchedParamType);
Larry Hastings2f936352014-08-05 14:04:04 +10006458 if (!result)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006459 return NULL;
6460 priority = PyLong_FromLong(param.sched_priority);
6461 if (!priority) {
Larry Hastings2f936352014-08-05 14:04:04 +10006462 Py_DECREF(result);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006463 return NULL;
6464 }
Larry Hastings2f936352014-08-05 14:04:04 +10006465 PyStructSequence_SET_ITEM(result, 0, priority);
6466 return result;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006467}
6468
Larry Hastings2f936352014-08-05 14:04:04 +10006469
6470/*[clinic input]
6471os.sched_setparam
6472 pid: pid_t
6473 param: sched_param
6474 /
6475
6476Set scheduling parameters for the process identified by pid.
6477
6478If pid is 0, sets parameters for the calling process.
6479param should be an instance of sched_param.
6480[clinic start generated code]*/
6481
Larry Hastings2f936352014-08-05 14:04:04 +10006482static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006483os_sched_setparam_impl(PyObject *module, pid_t pid,
Larry Hastings89964c42015-04-14 18:07:59 -04006484 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006485/*[clinic end generated code: output=8af013f78a32b591 input=6b8d6dfcecdc21bd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006486{
6487 if (sched_setparam(pid, param))
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006488 return posix_error();
6489 Py_RETURN_NONE;
6490}
Larry Hastings2f936352014-08-05 14:04:04 +10006491#endif /* HAVE_SCHED_SETPARAM */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006492
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006493
6494#ifdef HAVE_SCHED_RR_GET_INTERVAL
Larry Hastings2f936352014-08-05 14:04:04 +10006495/*[clinic input]
6496os.sched_rr_get_interval -> double
6497 pid: pid_t
6498 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006499
Larry Hastings2f936352014-08-05 14:04:04 +10006500Return the round-robin quantum for the process identified by pid, in seconds.
6501
6502Value returned is a float.
6503[clinic start generated code]*/
6504
Larry Hastings2f936352014-08-05 14:04:04 +10006505static double
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006506os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
6507/*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006508{
6509 struct timespec interval;
6510 if (sched_rr_get_interval(pid, &interval)) {
6511 posix_error();
6512 return -1.0;
6513 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006514#ifdef _Py_MEMORY_SANITIZER
6515 __msan_unpoison(&interval, sizeof(interval));
6516#endif
Larry Hastings2f936352014-08-05 14:04:04 +10006517 return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
6518}
6519#endif /* HAVE_SCHED_RR_GET_INTERVAL */
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006520
Larry Hastings2f936352014-08-05 14:04:04 +10006521
6522/*[clinic input]
6523os.sched_yield
6524
6525Voluntarily relinquish the CPU.
6526[clinic start generated code]*/
6527
Larry Hastings2f936352014-08-05 14:04:04 +10006528static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006529os_sched_yield_impl(PyObject *module)
6530/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006531{
6532 if (sched_yield())
6533 return posix_error();
6534 Py_RETURN_NONE;
6535}
6536
Benjamin Peterson2740af82011-08-02 17:41:34 -05006537#ifdef HAVE_SCHED_SETAFFINITY
Antoine Pitrou84869872012-08-04 16:16:35 +02006538/* The minimum number of CPUs allocated in a cpu_set_t */
6539static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006540
Larry Hastings2f936352014-08-05 14:04:04 +10006541/*[clinic input]
6542os.sched_setaffinity
6543 pid: pid_t
6544 mask : object
6545 /
6546
6547Set the CPU affinity of the process identified by pid to mask.
6548
6549mask should be an iterable of integers identifying CPUs.
6550[clinic start generated code]*/
6551
Larry Hastings2f936352014-08-05 14:04:04 +10006552static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006553os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
6554/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006555{
Antoine Pitrou84869872012-08-04 16:16:35 +02006556 int ncpus;
6557 size_t setsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006558 cpu_set_t *cpu_set = NULL;
6559 PyObject *iterator = NULL, *item;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006560
Larry Hastings2f936352014-08-05 14:04:04 +10006561 iterator = PyObject_GetIter(mask);
Antoine Pitrou84869872012-08-04 16:16:35 +02006562 if (iterator == NULL)
6563 return NULL;
6564
6565 ncpus = NCPUS_START;
6566 setsize = CPU_ALLOC_SIZE(ncpus);
Larry Hastings2f936352014-08-05 14:04:04 +10006567 cpu_set = CPU_ALLOC(ncpus);
6568 if (cpu_set == NULL) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006569 PyErr_NoMemory();
6570 goto error;
6571 }
Larry Hastings2f936352014-08-05 14:04:04 +10006572 CPU_ZERO_S(setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006573
6574 while ((item = PyIter_Next(iterator))) {
6575 long cpu;
6576 if (!PyLong_Check(item)) {
6577 PyErr_Format(PyExc_TypeError,
6578 "expected an iterator of ints, "
6579 "but iterator yielded %R",
6580 Py_TYPE(item));
6581 Py_DECREF(item);
6582 goto error;
6583 }
6584 cpu = PyLong_AsLong(item);
6585 Py_DECREF(item);
6586 if (cpu < 0) {
6587 if (!PyErr_Occurred())
6588 PyErr_SetString(PyExc_ValueError, "negative CPU number");
6589 goto error;
6590 }
6591 if (cpu > INT_MAX - 1) {
6592 PyErr_SetString(PyExc_OverflowError, "CPU number too large");
6593 goto error;
6594 }
6595 if (cpu >= ncpus) {
6596 /* Grow CPU mask to fit the CPU number */
6597 int newncpus = ncpus;
6598 cpu_set_t *newmask;
6599 size_t newsetsize;
6600 while (newncpus <= cpu) {
6601 if (newncpus > INT_MAX / 2)
6602 newncpus = cpu + 1;
6603 else
6604 newncpus = newncpus * 2;
6605 }
6606 newmask = CPU_ALLOC(newncpus);
6607 if (newmask == NULL) {
6608 PyErr_NoMemory();
6609 goto error;
6610 }
6611 newsetsize = CPU_ALLOC_SIZE(newncpus);
6612 CPU_ZERO_S(newsetsize, newmask);
Larry Hastings2f936352014-08-05 14:04:04 +10006613 memcpy(newmask, cpu_set, setsize);
6614 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006615 setsize = newsetsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006616 cpu_set = newmask;
Antoine Pitrou84869872012-08-04 16:16:35 +02006617 ncpus = newncpus;
6618 }
Larry Hastings2f936352014-08-05 14:04:04 +10006619 CPU_SET_S(cpu, setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006620 }
Brandt Bucher45a30af2019-06-27 09:10:57 -07006621 if (PyErr_Occurred()) {
6622 goto error;
6623 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006624 Py_CLEAR(iterator);
6625
Larry Hastings2f936352014-08-05 14:04:04 +10006626 if (sched_setaffinity(pid, setsize, cpu_set)) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006627 posix_error();
6628 goto error;
6629 }
Larry Hastings2f936352014-08-05 14:04:04 +10006630 CPU_FREE(cpu_set);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006631 Py_RETURN_NONE;
Antoine Pitrou84869872012-08-04 16:16:35 +02006632
6633error:
Larry Hastings2f936352014-08-05 14:04:04 +10006634 if (cpu_set)
6635 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006636 Py_XDECREF(iterator);
6637 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006638}
6639
Larry Hastings2f936352014-08-05 14:04:04 +10006640
6641/*[clinic input]
6642os.sched_getaffinity
6643 pid: pid_t
6644 /
6645
Charles-François Natalidc87e4b2015-07-13 21:01:39 +01006646Return the affinity of the process identified by pid (or the current process if zero).
Larry Hastings2f936352014-08-05 14:04:04 +10006647
6648The affinity is returned as a set of CPU identifiers.
6649[clinic start generated code]*/
6650
Larry Hastings2f936352014-08-05 14:04:04 +10006651static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006652os_sched_getaffinity_impl(PyObject *module, pid_t pid)
Serhiy Storchaka2954f832016-07-07 18:20:03 +03006653/*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006654{
Antoine Pitrou84869872012-08-04 16:16:35 +02006655 int cpu, ncpus, count;
6656 size_t setsize;
6657 cpu_set_t *mask = NULL;
6658 PyObject *res = NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006659
Antoine Pitrou84869872012-08-04 16:16:35 +02006660 ncpus = NCPUS_START;
6661 while (1) {
6662 setsize = CPU_ALLOC_SIZE(ncpus);
6663 mask = CPU_ALLOC(ncpus);
6664 if (mask == NULL)
6665 return PyErr_NoMemory();
6666 if (sched_getaffinity(pid, setsize, mask) == 0)
6667 break;
6668 CPU_FREE(mask);
6669 if (errno != EINVAL)
6670 return posix_error();
6671 if (ncpus > INT_MAX / 2) {
6672 PyErr_SetString(PyExc_OverflowError, "could not allocate "
6673 "a large enough CPU set");
6674 return NULL;
6675 }
6676 ncpus = ncpus * 2;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006677 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006678
6679 res = PySet_New(NULL);
6680 if (res == NULL)
6681 goto error;
6682 for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
6683 if (CPU_ISSET_S(cpu, setsize, mask)) {
6684 PyObject *cpu_num = PyLong_FromLong(cpu);
6685 --count;
6686 if (cpu_num == NULL)
6687 goto error;
6688 if (PySet_Add(res, cpu_num)) {
6689 Py_DECREF(cpu_num);
6690 goto error;
6691 }
6692 Py_DECREF(cpu_num);
6693 }
6694 }
6695 CPU_FREE(mask);
6696 return res;
6697
6698error:
6699 if (mask)
6700 CPU_FREE(mask);
6701 Py_XDECREF(res);
6702 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006703}
6704
Benjamin Peterson2740af82011-08-02 17:41:34 -05006705#endif /* HAVE_SCHED_SETAFFINITY */
6706
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006707#endif /* HAVE_SCHED_H */
6708
Larry Hastings2f936352014-08-05 14:04:04 +10006709
Neal Norwitzb59798b2003-03-21 01:43:31 +00006710/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
Neal Norwitz2deaddb2003-03-21 03:08:31 +00006711/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
6712#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
Neal Norwitzb59798b2003-03-21 01:43:31 +00006713#define DEV_PTY_FILE "/dev/ptc"
6714#define HAVE_DEV_PTMX
6715#else
6716#define DEV_PTY_FILE "/dev/ptmx"
6717#endif
6718
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006719#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
Fred Drake8cef4cf2000-06-28 16:40:38 +00006720#ifdef HAVE_PTY_H
6721#include <pty.h>
6722#else
6723#ifdef HAVE_LIBUTIL_H
6724#include <libutil.h>
Ronald Oussoren755740f2010-02-07 19:56:39 +00006725#else
6726#ifdef HAVE_UTIL_H
6727#include <util.h>
6728#endif /* HAVE_UTIL_H */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006729#endif /* HAVE_LIBUTIL_H */
6730#endif /* HAVE_PTY_H */
Martin v. Löwis14e73b12003-01-01 09:51:12 +00006731#ifdef HAVE_STROPTS_H
6732#include <stropts.h>
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006733#endif
ngie-eign7745ec42018-02-14 11:54:28 -08006734#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006735
Larry Hastings2f936352014-08-05 14:04:04 +10006736
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006737#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
Larry Hastings2f936352014-08-05 14:04:04 +10006738/*[clinic input]
6739os.openpty
6740
6741Open a pseudo-terminal.
6742
6743Return a tuple of (master_fd, slave_fd) containing open file descriptors
6744for both the master and slave ends.
6745[clinic start generated code]*/
6746
Larry Hastings2f936352014-08-05 14:04:04 +10006747static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006748os_openpty_impl(PyObject *module)
6749/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006750{
Victor Stinnerdaf45552013-08-28 00:53:59 +02006751 int master_fd = -1, slave_fd = -1;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006752#ifndef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006753 char * slave_name;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006754#endif
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006755#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006756 PyOS_sighandler_t sig_saved;
Jakub Kulík6f9bc722018-12-31 03:16:40 +01006757#if defined(__sun) && defined(__SVR4)
Victor Stinner8c62be82010-05-06 00:08:46 +00006758 extern char *ptsname(int fildes);
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006759#endif
6760#endif
Thomas Wouters70c21a12000-07-14 14:28:33 +00006761
Thomas Wouters70c21a12000-07-14 14:28:33 +00006762#ifdef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006763 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006764 goto posix_error;
6765
6766 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6767 goto error;
6768 if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
6769 goto error;
6770
Neal Norwitzb59798b2003-03-21 01:43:31 +00006771#elif defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006772 slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
6773 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006774 goto posix_error;
6775 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6776 goto error;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006777
Victor Stinnerdaf45552013-08-28 00:53:59 +02006778 slave_fd = _Py_open(slave_name, O_RDWR);
Victor Stinner8c62be82010-05-06 00:08:46 +00006779 if (slave_fd < 0)
Victor Stinnera555cfc2015-03-18 00:22:14 +01006780 goto error;
Victor Stinnerdaf45552013-08-28 00:53:59 +02006781
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006782#else
Victor Stinner000de532013-11-25 23:19:58 +01006783 master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
Victor Stinner8c62be82010-05-06 00:08:46 +00006784 if (master_fd < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006785 goto posix_error;
6786
Victor Stinner8c62be82010-05-06 00:08:46 +00006787 sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006788
Victor Stinner8c62be82010-05-06 00:08:46 +00006789 /* change permission of slave */
6790 if (grantpt(master_fd) < 0) {
6791 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006792 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006793 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006794
Victor Stinner8c62be82010-05-06 00:08:46 +00006795 /* unlock slave */
6796 if (unlockpt(master_fd) < 0) {
6797 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006798 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006799 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006800
Victor Stinner8c62be82010-05-06 00:08:46 +00006801 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006802
Victor Stinner8c62be82010-05-06 00:08:46 +00006803 slave_name = ptsname(master_fd); /* get name of slave */
6804 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006805 goto posix_error;
6806
6807 slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
Victor Stinnera555cfc2015-03-18 00:22:14 +01006808 if (slave_fd == -1)
6809 goto error;
Victor Stinner000de532013-11-25 23:19:58 +01006810
6811 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6812 goto posix_error;
6813
Stefan Krahfb7c8ae2016-04-26 17:04:18 +02006814#if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
Victor Stinner8c62be82010-05-06 00:08:46 +00006815 ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
6816 ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
Neal Norwitz6700e472002-12-31 16:16:07 +00006817#ifndef __hpux
Victor Stinner8c62be82010-05-06 00:08:46 +00006818 ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
Neal Norwitz6700e472002-12-31 16:16:07 +00006819#endif /* __hpux */
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006820#endif /* HAVE_CYGWIN */
Thomas Wouters1e0c2f42000-07-24 16:06:23 +00006821#endif /* HAVE_OPENPTY */
Thomas Wouters70c21a12000-07-14 14:28:33 +00006822
Victor Stinner8c62be82010-05-06 00:08:46 +00006823 return Py_BuildValue("(ii)", master_fd, slave_fd);
Thomas Wouters70c21a12000-07-14 14:28:33 +00006824
Victor Stinnerdaf45552013-08-28 00:53:59 +02006825posix_error:
6826 posix_error();
6827error:
6828 if (master_fd != -1)
6829 close(master_fd);
6830 if (slave_fd != -1)
6831 close(slave_fd);
6832 return NULL;
Fred Drake8cef4cf2000-06-28 16:40:38 +00006833}
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006834#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006835
Larry Hastings2f936352014-08-05 14:04:04 +10006836
Fred Drake8cef4cf2000-06-28 16:40:38 +00006837#ifdef HAVE_FORKPTY
Larry Hastings2f936352014-08-05 14:04:04 +10006838/*[clinic input]
6839os.forkpty
6840
6841Fork a new process with a new pseudo-terminal as controlling tty.
6842
6843Returns a tuple of (pid, master_fd).
6844Like fork(), return pid of 0 to the child process,
6845and pid of child to the parent process.
6846To both, return fd of newly opened pseudo-terminal.
6847[clinic start generated code]*/
6848
Larry Hastings2f936352014-08-05 14:04:04 +10006849static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006850os_forkpty_impl(PyObject *module)
6851/*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006852{
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006853 int master_fd = -1;
Victor Stinner8c62be82010-05-06 00:08:46 +00006854 pid_t pid;
Tim Peters5aa91602002-01-30 05:46:57 +00006855
Victor Stinner81a7be32020-04-14 15:14:01 +02006856 if (_PyInterpreterState_GET() != PyInterpreterState_Main()) {
Eric Snow59032962018-09-14 14:17:20 -07006857 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6858 return NULL;
6859 }
Saiyang Gou7514f4f2020-02-12 23:47:42 -08006860 if (PySys_Audit("os.forkpty", NULL) < 0) {
6861 return NULL;
6862 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006863 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006864 pid = forkpty(&master_fd, NULL, NULL, NULL);
6865 if (pid == 0) {
6866 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006867 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006868 } else {
6869 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006870 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006871 }
6872 if (pid == -1)
6873 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006874 return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
Fred Drake8cef4cf2000-06-28 16:40:38 +00006875}
Larry Hastings2f936352014-08-05 14:04:04 +10006876#endif /* HAVE_FORKPTY */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006877
Ross Lagerwall7807c352011-03-17 20:20:30 +02006878
Guido van Rossumad0ee831995-03-01 10:34:45 +00006879#ifdef HAVE_GETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10006880/*[clinic input]
6881os.getegid
6882
6883Return the current process's effective group id.
6884[clinic start generated code]*/
6885
Larry Hastings2f936352014-08-05 14:04:04 +10006886static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006887os_getegid_impl(PyObject *module)
6888/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006889{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006890 return _PyLong_FromGid(getegid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006891}
Larry Hastings2f936352014-08-05 14:04:04 +10006892#endif /* HAVE_GETEGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006893
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006894
Guido van Rossumad0ee831995-03-01 10:34:45 +00006895#ifdef HAVE_GETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10006896/*[clinic input]
6897os.geteuid
6898
6899Return the current process's effective user id.
6900[clinic start generated code]*/
6901
Larry Hastings2f936352014-08-05 14:04:04 +10006902static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006903os_geteuid_impl(PyObject *module)
6904/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006905{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006906 return _PyLong_FromUid(geteuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006907}
Larry Hastings2f936352014-08-05 14:04:04 +10006908#endif /* HAVE_GETEUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006909
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006910
Guido van Rossumad0ee831995-03-01 10:34:45 +00006911#ifdef HAVE_GETGID
Larry Hastings2f936352014-08-05 14:04:04 +10006912/*[clinic input]
6913os.getgid
6914
6915Return the current process's group id.
6916[clinic start generated code]*/
6917
Larry Hastings2f936352014-08-05 14:04:04 +10006918static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006919os_getgid_impl(PyObject *module)
6920/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006921{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006922 return _PyLong_FromGid(getgid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006923}
Larry Hastings2f936352014-08-05 14:04:04 +10006924#endif /* HAVE_GETGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006925
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006926
Berker Peksag39404992016-09-15 20:45:16 +03006927#ifdef HAVE_GETPID
Larry Hastings2f936352014-08-05 14:04:04 +10006928/*[clinic input]
6929os.getpid
6930
6931Return the current process id.
6932[clinic start generated code]*/
6933
Larry Hastings2f936352014-08-05 14:04:04 +10006934static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006935os_getpid_impl(PyObject *module)
6936/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006937{
Victor Stinner8c62be82010-05-06 00:08:46 +00006938 return PyLong_FromPid(getpid());
Guido van Rossum85e3b011991-06-03 12:42:10 +00006939}
Berker Peksag39404992016-09-15 20:45:16 +03006940#endif /* HAVE_GETPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00006941
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07006942#ifdef NGROUPS_MAX
6943#define MAX_GROUPS NGROUPS_MAX
6944#else
6945 /* defined to be 16 on Solaris7, so this should be a small number */
6946#define MAX_GROUPS 64
6947#endif
6948
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006949#ifdef HAVE_GETGROUPLIST
Larry Hastings2f936352014-08-05 14:04:04 +10006950
Serhiy Storchaka2b560312020-04-18 19:14:10 +03006951#ifdef __APPLE__
6952/*[clinic input]
6953os.getgrouplist
6954
6955 user: str
6956 username to lookup
6957 group as basegid: int
6958 base group id of the user
6959 /
6960
6961Returns a list of groups to which a user belongs.
6962[clinic start generated code]*/
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006963
6964static PyObject *
Serhiy Storchaka2b560312020-04-18 19:14:10 +03006965os_getgrouplist_impl(PyObject *module, const char *user, int basegid)
6966/*[clinic end generated code: output=6e734697b8c26de0 input=f8d870374b09a490]*/
6967#else
6968/*[clinic input]
6969os.getgrouplist
6970
6971 user: str
6972 username to lookup
6973 group as basegid: gid_t
6974 base group id of the user
6975 /
6976
6977Returns a list of groups to which a user belongs.
6978[clinic start generated code]*/
6979
6980static PyObject *
6981os_getgrouplist_impl(PyObject *module, const char *user, gid_t basegid)
6982/*[clinic end generated code: output=0ebd7fb70115575b input=cc61d5c20b08958d]*/
6983#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006984{
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006985 int i, ngroups;
6986 PyObject *list;
6987#ifdef __APPLE__
Serhiy Storchaka2b560312020-04-18 19:14:10 +03006988 int *groups;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006989#else
Serhiy Storchaka2b560312020-04-18 19:14:10 +03006990 gid_t *groups;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006991#endif
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07006992
6993 /*
6994 * NGROUPS_MAX is defined by POSIX.1 as the maximum
6995 * number of supplimental groups a users can belong to.
6996 * We have to increment it by one because
6997 * getgrouplist() returns both the supplemental groups
6998 * and the primary group, i.e. all of the groups the
6999 * user belongs to.
7000 */
7001 ngroups = 1 + MAX_GROUPS;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007002
Victor Stinnerf5c7cab2020-03-24 18:22:10 +01007003 while (1) {
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007004#ifdef __APPLE__
Victor Stinner8ec73702020-03-23 20:00:57 +01007005 groups = PyMem_New(int, ngroups);
Victor Stinnerf5c7cab2020-03-24 18:22:10 +01007006#else
7007 groups = PyMem_New(gid_t, ngroups);
7008#endif
Victor Stinner8ec73702020-03-23 20:00:57 +01007009 if (groups == NULL) {
7010 return PyErr_NoMemory();
7011 }
Victor Stinnerf5c7cab2020-03-24 18:22:10 +01007012
7013 int old_ngroups = ngroups;
7014 if (getgrouplist(user, basegid, groups, &ngroups) != -1) {
7015 /* Success */
7016 break;
7017 }
7018
7019 /* getgrouplist() fails if the group list is too small */
7020 PyMem_Free(groups);
7021
7022 if (ngroups > old_ngroups) {
7023 /* If the group list is too small, the glibc implementation of
7024 getgrouplist() sets ngroups to the total number of groups and
7025 returns -1. */
7026 }
7027 else {
7028 /* Double the group list size */
7029 if (ngroups > INT_MAX / 2) {
7030 return PyErr_NoMemory();
7031 }
7032 ngroups *= 2;
7033 }
7034
7035 /* Retry getgrouplist() with a larger group list */
Victor Stinner8ec73702020-03-23 20:00:57 +01007036 }
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007037
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08007038#ifdef _Py_MEMORY_SANITIZER
7039 /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
7040 __msan_unpoison(&ngroups, sizeof(ngroups));
7041 __msan_unpoison(groups, ngroups*sizeof(*groups));
7042#endif
7043
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007044 list = PyList_New(ngroups);
7045 if (list == NULL) {
7046 PyMem_Del(groups);
7047 return NULL;
7048 }
7049
7050 for (i = 0; i < ngroups; i++) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007051#ifdef __APPLE__
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007052 PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007053#else
7054 PyObject *o = _PyLong_FromGid(groups[i]);
7055#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007056 if (o == NULL) {
7057 Py_DECREF(list);
7058 PyMem_Del(groups);
7059 return NULL;
7060 }
7061 PyList_SET_ITEM(list, i, o);
7062 }
7063
7064 PyMem_Del(groups);
7065
7066 return list;
7067}
Larry Hastings2f936352014-08-05 14:04:04 +10007068#endif /* HAVE_GETGROUPLIST */
7069
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007070
Fred Drakec9680921999-12-13 16:37:25 +00007071#ifdef HAVE_GETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007072/*[clinic input]
7073os.getgroups
7074
7075Return list of supplemental group IDs for the process.
7076[clinic start generated code]*/
7077
Larry Hastings2f936352014-08-05 14:04:04 +10007078static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007079os_getgroups_impl(PyObject *module)
7080/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
Fred Drakec9680921999-12-13 16:37:25 +00007081{
7082 PyObject *result = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00007083 gid_t grouplist[MAX_GROUPS];
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007084
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007085 /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007086 * This is a helper variable to store the intermediate result when
7087 * that happens.
7088 *
7089 * To keep the code readable the OSX behaviour is unconditional,
7090 * according to the POSIX spec this should be safe on all unix-y
7091 * systems.
7092 */
7093 gid_t* alt_grouplist = grouplist;
Victor Stinner8c62be82010-05-06 00:08:46 +00007094 int n;
Fred Drakec9680921999-12-13 16:37:25 +00007095
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007096#ifdef __APPLE__
7097 /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
7098 * there are more groups than can fit in grouplist. Therefore, on OS X
7099 * always first call getgroups with length 0 to get the actual number
7100 * of groups.
7101 */
7102 n = getgroups(0, NULL);
7103 if (n < 0) {
7104 return posix_error();
7105 } else if (n <= MAX_GROUPS) {
7106 /* groups will fit in existing array */
7107 alt_grouplist = grouplist;
7108 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02007109 alt_grouplist = PyMem_New(gid_t, n);
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007110 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07007111 return PyErr_NoMemory();
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007112 }
7113 }
7114
7115 n = getgroups(n, alt_grouplist);
7116 if (n == -1) {
7117 if (alt_grouplist != grouplist) {
7118 PyMem_Free(alt_grouplist);
7119 }
7120 return posix_error();
7121 }
7122#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007123 n = getgroups(MAX_GROUPS, grouplist);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007124 if (n < 0) {
7125 if (errno == EINVAL) {
7126 n = getgroups(0, NULL);
7127 if (n == -1) {
7128 return posix_error();
7129 }
7130 if (n == 0) {
7131 /* Avoid malloc(0) */
7132 alt_grouplist = grouplist;
7133 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02007134 alt_grouplist = PyMem_New(gid_t, n);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007135 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07007136 return PyErr_NoMemory();
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007137 }
7138 n = getgroups(n, alt_grouplist);
7139 if (n == -1) {
7140 PyMem_Free(alt_grouplist);
7141 return posix_error();
7142 }
7143 }
7144 } else {
7145 return posix_error();
7146 }
7147 }
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007148#endif
7149
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007150 result = PyList_New(n);
7151 if (result != NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007152 int i;
7153 for (i = 0; i < n; ++i) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007154 PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
Victor Stinner8c62be82010-05-06 00:08:46 +00007155 if (o == NULL) {
Stefan Krah0e803b32010-11-26 16:16:47 +00007156 Py_DECREF(result);
7157 result = NULL;
7158 break;
Fred Drakec9680921999-12-13 16:37:25 +00007159 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007160 PyList_SET_ITEM(result, i, o);
Fred Drakec9680921999-12-13 16:37:25 +00007161 }
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007162 }
7163
7164 if (alt_grouplist != grouplist) {
7165 PyMem_Free(alt_grouplist);
Victor Stinner8c62be82010-05-06 00:08:46 +00007166 }
Neal Norwitze241ce82003-02-17 18:17:05 +00007167
Fred Drakec9680921999-12-13 16:37:25 +00007168 return result;
7169}
Larry Hastings2f936352014-08-05 14:04:04 +10007170#endif /* HAVE_GETGROUPS */
Fred Drakec9680921999-12-13 16:37:25 +00007171
Antoine Pitroub7572f02009-12-02 20:46:48 +00007172#ifdef HAVE_INITGROUPS
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007173#ifdef __APPLE__
7174/*[clinic input]
7175os.initgroups
Antoine Pitroub7572f02009-12-02 20:46:48 +00007176
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007177 username as oname: FSConverter
7178 gid: int
7179 /
7180
7181Initialize the group access list.
7182
7183Call the system initgroups() to initialize the group access list with all of
7184the groups of which the specified username is a member, plus the specified
7185group id.
7186[clinic start generated code]*/
7187
Antoine Pitroub7572f02009-12-02 20:46:48 +00007188static PyObject *
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007189os_initgroups_impl(PyObject *module, PyObject *oname, int gid)
7190/*[clinic end generated code: output=7f074d30a425fd3a input=df3d54331b0af204]*/
7191#else
7192/*[clinic input]
7193os.initgroups
7194
7195 username as oname: FSConverter
7196 gid: gid_t
7197 /
7198
7199Initialize the group access list.
7200
7201Call the system initgroups() to initialize the group access list with all of
7202the groups of which the specified username is a member, plus the specified
7203group id.
7204[clinic start generated code]*/
7205
7206static PyObject *
7207os_initgroups_impl(PyObject *module, PyObject *oname, gid_t gid)
7208/*[clinic end generated code: output=59341244521a9e3f input=0cb91bdc59a4c564]*/
7209#endif
Antoine Pitroub7572f02009-12-02 20:46:48 +00007210{
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007211 const char *username = PyBytes_AS_STRING(oname);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007212
Serhiy Storchaka2b560312020-04-18 19:14:10 +03007213 if (initgroups(username, gid) == -1)
Victor Stinner8c62be82010-05-06 00:08:46 +00007214 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007215
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007216 Py_RETURN_NONE;
Antoine Pitroub7572f02009-12-02 20:46:48 +00007217}
Larry Hastings2f936352014-08-05 14:04:04 +10007218#endif /* HAVE_INITGROUPS */
7219
Antoine Pitroub7572f02009-12-02 20:46:48 +00007220
Martin v. Löwis606edc12002-06-13 21:09:11 +00007221#ifdef HAVE_GETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10007222/*[clinic input]
7223os.getpgid
7224
7225 pid: pid_t
7226
7227Call the system call getpgid(), and return the result.
7228[clinic start generated code]*/
7229
Larry Hastings2f936352014-08-05 14:04:04 +10007230static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007231os_getpgid_impl(PyObject *module, pid_t pid)
7232/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007233{
7234 pid_t pgid = getpgid(pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007235 if (pgid < 0)
7236 return posix_error();
7237 return PyLong_FromPid(pgid);
Martin v. Löwis606edc12002-06-13 21:09:11 +00007238}
7239#endif /* HAVE_GETPGID */
7240
7241
Guido van Rossumb6775db1994-08-01 11:34:53 +00007242#ifdef HAVE_GETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007243/*[clinic input]
7244os.getpgrp
7245
7246Return the current process group id.
7247[clinic start generated code]*/
7248
Larry Hastings2f936352014-08-05 14:04:04 +10007249static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007250os_getpgrp_impl(PyObject *module)
7251/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
Guido van Rossum04814471991-06-04 20:23:49 +00007252{
Guido van Rossumb6775db1994-08-01 11:34:53 +00007253#ifdef GETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007254 return PyLong_FromPid(getpgrp(0));
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007255#else /* GETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007256 return PyLong_FromPid(getpgrp());
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007257#endif /* GETPGRP_HAVE_ARG */
Guido van Rossum04814471991-06-04 20:23:49 +00007258}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007259#endif /* HAVE_GETPGRP */
Guido van Rossum04814471991-06-04 20:23:49 +00007260
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007261
Guido van Rossumb6775db1994-08-01 11:34:53 +00007262#ifdef HAVE_SETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007263/*[clinic input]
7264os.setpgrp
7265
7266Make the current process the leader of its process group.
7267[clinic start generated code]*/
7268
Larry Hastings2f936352014-08-05 14:04:04 +10007269static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007270os_setpgrp_impl(PyObject *module)
7271/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00007272{
Guido van Rossum64933891994-10-20 21:56:42 +00007273#ifdef SETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007274 if (setpgrp(0, 0) < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007275#else /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007276 if (setpgrp() < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007277#endif /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007278 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007279 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00007280}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007281#endif /* HAVE_SETPGRP */
7282
Guido van Rossumad0ee831995-03-01 10:34:45 +00007283#ifdef HAVE_GETPPID
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007284
7285#ifdef MS_WINDOWS
7286#include <tlhelp32.h>
7287
7288static PyObject*
7289win32_getppid()
7290{
7291 HANDLE snapshot;
7292 pid_t mypid;
7293 PyObject* result = NULL;
7294 BOOL have_record;
7295 PROCESSENTRY32 pe;
7296
7297 mypid = getpid(); /* This function never fails */
7298
7299 snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
7300 if (snapshot == INVALID_HANDLE_VALUE)
7301 return PyErr_SetFromWindowsErr(GetLastError());
7302
7303 pe.dwSize = sizeof(pe);
7304 have_record = Process32First(snapshot, &pe);
7305 while (have_record) {
7306 if (mypid == (pid_t)pe.th32ProcessID) {
7307 /* We could cache the ulong value in a static variable. */
7308 result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
7309 break;
7310 }
7311
7312 have_record = Process32Next(snapshot, &pe);
7313 }
7314
7315 /* If our loop exits and our pid was not found (result will be NULL)
7316 * then GetLastError will return ERROR_NO_MORE_FILES. This is an
7317 * error anyway, so let's raise it. */
7318 if (!result)
7319 result = PyErr_SetFromWindowsErr(GetLastError());
7320
7321 CloseHandle(snapshot);
7322
7323 return result;
7324}
7325#endif /*MS_WINDOWS*/
7326
Larry Hastings2f936352014-08-05 14:04:04 +10007327
7328/*[clinic input]
7329os.getppid
7330
7331Return the parent's process id.
7332
7333If the parent process has already exited, Windows machines will still
7334return its id; others systems will return the id of the 'init' process (1).
7335[clinic start generated code]*/
7336
Larry Hastings2f936352014-08-05 14:04:04 +10007337static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007338os_getppid_impl(PyObject *module)
7339/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00007340{
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007341#ifdef MS_WINDOWS
7342 return win32_getppid();
7343#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007344 return PyLong_FromPid(getppid());
Guido van Rossumad0ee831995-03-01 10:34:45 +00007345#endif
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007346}
7347#endif /* HAVE_GETPPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007348
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007349
Fred Drake12c6e2d1999-12-14 21:25:03 +00007350#ifdef HAVE_GETLOGIN
Larry Hastings2f936352014-08-05 14:04:04 +10007351/*[clinic input]
7352os.getlogin
7353
7354Return the actual login name.
7355[clinic start generated code]*/
7356
Larry Hastings2f936352014-08-05 14:04:04 +10007357static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007358os_getlogin_impl(PyObject *module)
7359/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
Fred Drake12c6e2d1999-12-14 21:25:03 +00007360{
Victor Stinner8c62be82010-05-06 00:08:46 +00007361 PyObject *result = NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007362#ifdef MS_WINDOWS
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007363 wchar_t user_name[UNLEN + 1];
Victor Stinner63941882011-09-29 00:42:28 +02007364 DWORD num_chars = Py_ARRAY_LENGTH(user_name);
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007365
7366 if (GetUserNameW(user_name, &num_chars)) {
7367 /* num_chars is the number of unicode chars plus null terminator */
7368 result = PyUnicode_FromWideChar(user_name, num_chars - 1);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007369 }
7370 else
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007371 result = PyErr_SetFromWindowsErr(GetLastError());
7372#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007373 char *name;
7374 int old_errno = errno;
Fred Drake12c6e2d1999-12-14 21:25:03 +00007375
Victor Stinner8c62be82010-05-06 00:08:46 +00007376 errno = 0;
7377 name = getlogin();
7378 if (name == NULL) {
7379 if (errno)
Victor Stinnere039ffe2010-08-15 09:33:08 +00007380 posix_error();
Fred Drake12c6e2d1999-12-14 21:25:03 +00007381 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007382 PyErr_SetString(PyExc_OSError, "unable to determine login name");
Victor Stinner8c62be82010-05-06 00:08:46 +00007383 }
7384 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007385 result = PyUnicode_DecodeFSDefault(name);
Victor Stinner8c62be82010-05-06 00:08:46 +00007386 errno = old_errno;
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007387#endif
Fred Drake12c6e2d1999-12-14 21:25:03 +00007388 return result;
7389}
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007390#endif /* HAVE_GETLOGIN */
Fred Drake12c6e2d1999-12-14 21:25:03 +00007391
Larry Hastings2f936352014-08-05 14:04:04 +10007392
Guido van Rossumad0ee831995-03-01 10:34:45 +00007393#ifdef HAVE_GETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007394/*[clinic input]
7395os.getuid
7396
7397Return the current process's user id.
7398[clinic start generated code]*/
7399
Larry Hastings2f936352014-08-05 14:04:04 +10007400static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007401os_getuid_impl(PyObject *module)
7402/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00007403{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007404 return _PyLong_FromUid(getuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00007405}
Larry Hastings2f936352014-08-05 14:04:04 +10007406#endif /* HAVE_GETUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00007407
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007408
Brian Curtineb24d742010-04-12 17:16:38 +00007409#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007410#define HAVE_KILL
7411#endif /* MS_WINDOWS */
7412
7413#ifdef HAVE_KILL
7414/*[clinic input]
7415os.kill
7416
7417 pid: pid_t
7418 signal: Py_ssize_t
7419 /
7420
7421Kill a process with a signal.
7422[clinic start generated code]*/
7423
Larry Hastings2f936352014-08-05 14:04:04 +10007424static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007425os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
7426/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007427{
Saiyang Gou7514f4f2020-02-12 23:47:42 -08007428 if (PySys_Audit("os.kill", "in", pid, signal) < 0) {
7429 return NULL;
7430 }
7431#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007432 if (kill(pid, (int)signal) == -1)
7433 return posix_error();
7434 Py_RETURN_NONE;
Larry Hastings2f936352014-08-05 14:04:04 +10007435#else /* !MS_WINDOWS */
Amaury Forgeot d'Arc0a589c92010-05-15 20:35:12 +00007436 PyObject *result;
Larry Hastings2f936352014-08-05 14:04:04 +10007437 DWORD sig = (DWORD)signal;
7438 DWORD err;
Victor Stinner8c62be82010-05-06 00:08:46 +00007439 HANDLE handle;
Brian Curtineb24d742010-04-12 17:16:38 +00007440
Victor Stinner8c62be82010-05-06 00:08:46 +00007441 /* Console processes which share a common console can be sent CTRL+C or
7442 CTRL+BREAK events, provided they handle said events. */
7443 if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007444 if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007445 err = GetLastError();
7446 PyErr_SetFromWindowsErr(err);
7447 }
7448 else
7449 Py_RETURN_NONE;
7450 }
Brian Curtineb24d742010-04-12 17:16:38 +00007451
Victor Stinner8c62be82010-05-06 00:08:46 +00007452 /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
7453 attempt to open and terminate the process. */
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007454 handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007455 if (handle == NULL) {
7456 err = GetLastError();
7457 return PyErr_SetFromWindowsErr(err);
7458 }
Brian Curtineb24d742010-04-12 17:16:38 +00007459
Victor Stinner8c62be82010-05-06 00:08:46 +00007460 if (TerminateProcess(handle, sig) == 0) {
7461 err = GetLastError();
7462 result = PyErr_SetFromWindowsErr(err);
7463 } else {
7464 Py_INCREF(Py_None);
7465 result = Py_None;
7466 }
Brian Curtineb24d742010-04-12 17:16:38 +00007467
Victor Stinner8c62be82010-05-06 00:08:46 +00007468 CloseHandle(handle);
7469 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10007470#endif /* !MS_WINDOWS */
Saiyang Gou7514f4f2020-02-12 23:47:42 -08007471}
Larry Hastings2f936352014-08-05 14:04:04 +10007472#endif /* HAVE_KILL */
7473
7474
7475#ifdef HAVE_KILLPG
7476/*[clinic input]
7477os.killpg
7478
7479 pgid: pid_t
7480 signal: int
7481 /
7482
7483Kill a process group with a signal.
7484[clinic start generated code]*/
7485
Larry Hastings2f936352014-08-05 14:04:04 +10007486static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007487os_killpg_impl(PyObject *module, pid_t pgid, int signal)
7488/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007489{
Saiyang Gou7514f4f2020-02-12 23:47:42 -08007490 if (PySys_Audit("os.killpg", "ii", pgid, signal) < 0) {
7491 return NULL;
7492 }
Larry Hastings2f936352014-08-05 14:04:04 +10007493 /* XXX some man pages make the `pgid` parameter an int, others
7494 a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
7495 take the same type. Moreover, pid_t is always at least as wide as
7496 int (else compilation of this module fails), which is safe. */
7497 if (killpg(pgid, signal) == -1)
7498 return posix_error();
7499 Py_RETURN_NONE;
7500}
7501#endif /* HAVE_KILLPG */
7502
Brian Curtineb24d742010-04-12 17:16:38 +00007503
Guido van Rossumc0125471996-06-28 18:55:32 +00007504#ifdef HAVE_PLOCK
Guido van Rossumc0125471996-06-28 18:55:32 +00007505#ifdef HAVE_SYS_LOCK_H
7506#include <sys/lock.h>
7507#endif
7508
Larry Hastings2f936352014-08-05 14:04:04 +10007509/*[clinic input]
7510os.plock
7511 op: int
7512 /
7513
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007514Lock program segments into memory.");
Larry Hastings2f936352014-08-05 14:04:04 +10007515[clinic start generated code]*/
7516
Larry Hastings2f936352014-08-05 14:04:04 +10007517static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007518os_plock_impl(PyObject *module, int op)
7519/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007520{
Victor Stinner8c62be82010-05-06 00:08:46 +00007521 if (plock(op) == -1)
7522 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007523 Py_RETURN_NONE;
Guido van Rossumc0125471996-06-28 18:55:32 +00007524}
Larry Hastings2f936352014-08-05 14:04:04 +10007525#endif /* HAVE_PLOCK */
7526
Guido van Rossumc0125471996-06-28 18:55:32 +00007527
Guido van Rossumb6775db1994-08-01 11:34:53 +00007528#ifdef HAVE_SETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007529/*[clinic input]
7530os.setuid
7531
7532 uid: uid_t
7533 /
7534
7535Set the current process's user id.
7536[clinic start generated code]*/
7537
Larry Hastings2f936352014-08-05 14:04:04 +10007538static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007539os_setuid_impl(PyObject *module, uid_t uid)
7540/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007541{
Victor Stinner8c62be82010-05-06 00:08:46 +00007542 if (setuid(uid) < 0)
7543 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007544 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007545}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007546#endif /* HAVE_SETUID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007547
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007548
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007549#ifdef HAVE_SETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10007550/*[clinic input]
7551os.seteuid
7552
7553 euid: uid_t
7554 /
7555
7556Set the current process's effective user id.
7557[clinic start generated code]*/
7558
Larry Hastings2f936352014-08-05 14:04:04 +10007559static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007560os_seteuid_impl(PyObject *module, uid_t euid)
7561/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007562{
7563 if (seteuid(euid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007564 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007565 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007566}
7567#endif /* HAVE_SETEUID */
7568
Larry Hastings2f936352014-08-05 14:04:04 +10007569
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007570#ifdef HAVE_SETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10007571/*[clinic input]
7572os.setegid
7573
7574 egid: gid_t
7575 /
7576
7577Set the current process's effective group id.
7578[clinic start generated code]*/
7579
Larry Hastings2f936352014-08-05 14:04:04 +10007580static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007581os_setegid_impl(PyObject *module, gid_t egid)
7582/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007583{
7584 if (setegid(egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007585 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007586 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007587}
7588#endif /* HAVE_SETEGID */
7589
Larry Hastings2f936352014-08-05 14:04:04 +10007590
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007591#ifdef HAVE_SETREUID
Larry Hastings2f936352014-08-05 14:04:04 +10007592/*[clinic input]
7593os.setreuid
7594
7595 ruid: uid_t
7596 euid: uid_t
7597 /
7598
7599Set the current process's real and effective user ids.
7600[clinic start generated code]*/
7601
Larry Hastings2f936352014-08-05 14:04:04 +10007602static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007603os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
7604/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007605{
Victor Stinner8c62be82010-05-06 00:08:46 +00007606 if (setreuid(ruid, euid) < 0) {
7607 return posix_error();
7608 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007609 Py_RETURN_NONE;
Victor Stinner8c62be82010-05-06 00:08:46 +00007610 }
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007611}
7612#endif /* HAVE_SETREUID */
7613
Larry Hastings2f936352014-08-05 14:04:04 +10007614
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007615#ifdef HAVE_SETREGID
Larry Hastings2f936352014-08-05 14:04:04 +10007616/*[clinic input]
7617os.setregid
7618
7619 rgid: gid_t
7620 egid: gid_t
7621 /
7622
7623Set the current process's real and effective group ids.
7624[clinic start generated code]*/
7625
Larry Hastings2f936352014-08-05 14:04:04 +10007626static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007627os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
7628/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007629{
7630 if (setregid(rgid, egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007631 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007632 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007633}
7634#endif /* HAVE_SETREGID */
7635
Larry Hastings2f936352014-08-05 14:04:04 +10007636
Guido van Rossumb6775db1994-08-01 11:34:53 +00007637#ifdef HAVE_SETGID
Larry Hastings2f936352014-08-05 14:04:04 +10007638/*[clinic input]
7639os.setgid
7640 gid: gid_t
7641 /
7642
7643Set the current process's group id.
7644[clinic start generated code]*/
7645
Larry Hastings2f936352014-08-05 14:04:04 +10007646static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007647os_setgid_impl(PyObject *module, gid_t gid)
7648/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007649{
Victor Stinner8c62be82010-05-06 00:08:46 +00007650 if (setgid(gid) < 0)
7651 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007652 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007653}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007654#endif /* HAVE_SETGID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007655
Larry Hastings2f936352014-08-05 14:04:04 +10007656
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007657#ifdef HAVE_SETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007658/*[clinic input]
7659os.setgroups
7660
7661 groups: object
7662 /
7663
7664Set the groups of the current process to list.
7665[clinic start generated code]*/
7666
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007667static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007668os_setgroups(PyObject *module, PyObject *groups)
7669/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007670{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007671 Py_ssize_t i, len;
Victor Stinner8c62be82010-05-06 00:08:46 +00007672 gid_t grouplist[MAX_GROUPS];
Tim Peters5aa91602002-01-30 05:46:57 +00007673
Victor Stinner8c62be82010-05-06 00:08:46 +00007674 if (!PySequence_Check(groups)) {
7675 PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
7676 return NULL;
7677 }
7678 len = PySequence_Size(groups);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007679 if (len < 0) {
7680 return NULL;
7681 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007682 if (len > MAX_GROUPS) {
7683 PyErr_SetString(PyExc_ValueError, "too many groups");
7684 return NULL;
7685 }
7686 for(i = 0; i < len; i++) {
7687 PyObject *elem;
7688 elem = PySequence_GetItem(groups, i);
7689 if (!elem)
7690 return NULL;
7691 if (!PyLong_Check(elem)) {
7692 PyErr_SetString(PyExc_TypeError,
7693 "groups must be integers");
7694 Py_DECREF(elem);
7695 return NULL;
7696 } else {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007697 if (!_Py_Gid_Converter(elem, &grouplist[i])) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007698 Py_DECREF(elem);
7699 return NULL;
7700 }
7701 }
7702 Py_DECREF(elem);
7703 }
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007704
Victor Stinner8c62be82010-05-06 00:08:46 +00007705 if (setgroups(len, grouplist) < 0)
7706 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007707 Py_RETURN_NONE;
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007708}
7709#endif /* HAVE_SETGROUPS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007710
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007711#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
7712static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +01007713wait_helper(pid_t pid, int status, struct rusage *ru)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007714{
Victor Stinner8c62be82010-05-06 00:08:46 +00007715 PyObject *result;
Eddie Elizondob3966632019-11-05 07:16:14 -08007716 PyObject *struct_rusage;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007717
Victor Stinner8c62be82010-05-06 00:08:46 +00007718 if (pid == -1)
7719 return posix_error();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007720
Zackery Spytz682107c2019-09-09 09:48:32 -06007721 // If wait succeeded but no child was ready to report status, ru will not
7722 // have been populated.
7723 if (pid == 0) {
7724 memset(ru, 0, sizeof(*ru));
7725 }
7726
Eddie Elizondob3966632019-11-05 07:16:14 -08007727 PyObject *m = PyImport_ImportModuleNoBlock("resource");
7728 if (m == NULL)
7729 return NULL;
7730 struct_rusage = PyObject_GetAttr(m, _posixstate_global->struct_rusage);
7731 Py_DECREF(m);
7732 if (struct_rusage == NULL)
7733 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007734
Victor Stinner8c62be82010-05-06 00:08:46 +00007735 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
7736 result = PyStructSequence_New((PyTypeObject*) struct_rusage);
Eddie Elizondoe4db1f02019-11-25 19:07:37 -08007737 Py_DECREF(struct_rusage);
Victor Stinner8c62be82010-05-06 00:08:46 +00007738 if (!result)
7739 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007740
7741#ifndef doubletime
7742#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
7743#endif
7744
Victor Stinner8c62be82010-05-06 00:08:46 +00007745 PyStructSequence_SET_ITEM(result, 0,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007746 PyFloat_FromDouble(doubletime(ru->ru_utime)));
Victor Stinner8c62be82010-05-06 00:08:46 +00007747 PyStructSequence_SET_ITEM(result, 1,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007748 PyFloat_FromDouble(doubletime(ru->ru_stime)));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007749#define SET_INT(result, index, value)\
Victor Stinner8c62be82010-05-06 00:08:46 +00007750 PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
7751 SET_INT(result, 2, ru->ru_maxrss);
7752 SET_INT(result, 3, ru->ru_ixrss);
7753 SET_INT(result, 4, ru->ru_idrss);
7754 SET_INT(result, 5, ru->ru_isrss);
7755 SET_INT(result, 6, ru->ru_minflt);
7756 SET_INT(result, 7, ru->ru_majflt);
7757 SET_INT(result, 8, ru->ru_nswap);
7758 SET_INT(result, 9, ru->ru_inblock);
7759 SET_INT(result, 10, ru->ru_oublock);
7760 SET_INT(result, 11, ru->ru_msgsnd);
7761 SET_INT(result, 12, ru->ru_msgrcv);
7762 SET_INT(result, 13, ru->ru_nsignals);
7763 SET_INT(result, 14, ru->ru_nvcsw);
7764 SET_INT(result, 15, ru->ru_nivcsw);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007765#undef SET_INT
7766
Victor Stinner8c62be82010-05-06 00:08:46 +00007767 if (PyErr_Occurred()) {
7768 Py_DECREF(result);
7769 return NULL;
7770 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007771
Victor Stinner8c62be82010-05-06 00:08:46 +00007772 return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007773}
7774#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
7775
Larry Hastings2f936352014-08-05 14:04:04 +10007776
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007777#ifdef HAVE_WAIT3
Larry Hastings2f936352014-08-05 14:04:04 +10007778/*[clinic input]
7779os.wait3
7780
7781 options: int
7782Wait for completion of a child process.
7783
7784Returns a tuple of information about the child process:
7785 (pid, status, rusage)
7786[clinic start generated code]*/
7787
Larry Hastings2f936352014-08-05 14:04:04 +10007788static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007789os_wait3_impl(PyObject *module, int options)
7790/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007791{
Victor Stinner8c62be82010-05-06 00:08:46 +00007792 pid_t pid;
Victor Stinner8c62be82010-05-06 00:08:46 +00007793 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007794 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007795 WAIT_TYPE status;
7796 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007797
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007798 do {
7799 Py_BEGIN_ALLOW_THREADS
7800 pid = wait3(&status, options, &ru);
7801 Py_END_ALLOW_THREADS
7802 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7803 if (pid < 0)
7804 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007805
Victor Stinner4195b5c2012-02-08 23:03:19 +01007806 return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007807}
7808#endif /* HAVE_WAIT3 */
7809
Larry Hastings2f936352014-08-05 14:04:04 +10007810
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007811#ifdef HAVE_WAIT4
Larry Hastings2f936352014-08-05 14:04:04 +10007812/*[clinic input]
7813
7814os.wait4
7815
7816 pid: pid_t
7817 options: int
7818
7819Wait for completion of a specific child process.
7820
7821Returns a tuple of information about the child process:
7822 (pid, status, rusage)
7823[clinic start generated code]*/
7824
Larry Hastings2f936352014-08-05 14:04:04 +10007825static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007826os_wait4_impl(PyObject *module, pid_t pid, int options)
7827/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007828{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007829 pid_t res;
Victor Stinner8c62be82010-05-06 00:08:46 +00007830 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007831 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007832 WAIT_TYPE status;
7833 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007834
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007835 do {
7836 Py_BEGIN_ALLOW_THREADS
7837 res = wait4(pid, &status, options, &ru);
7838 Py_END_ALLOW_THREADS
7839 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7840 if (res < 0)
7841 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007842
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007843 return wait_helper(res, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007844}
7845#endif /* HAVE_WAIT4 */
7846
Larry Hastings2f936352014-08-05 14:04:04 +10007847
Ross Lagerwall7807c352011-03-17 20:20:30 +02007848#if defined(HAVE_WAITID) && !defined(__APPLE__)
Larry Hastings2f936352014-08-05 14:04:04 +10007849/*[clinic input]
7850os.waitid
7851
7852 idtype: idtype_t
7853 Must be one of be P_PID, P_PGID or P_ALL.
7854 id: id_t
7855 The id to wait on.
7856 options: int
7857 Constructed from the ORing of one or more of WEXITED, WSTOPPED
7858 or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
7859 /
7860
7861Returns the result of waiting for a process or processes.
7862
7863Returns either waitid_result or None if WNOHANG is specified and there are
7864no children in a waitable state.
7865[clinic start generated code]*/
7866
Larry Hastings2f936352014-08-05 14:04:04 +10007867static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007868os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
7869/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007870{
7871 PyObject *result;
7872 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007873 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007874 siginfo_t si;
7875 si.si_pid = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007876
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007877 do {
7878 Py_BEGIN_ALLOW_THREADS
7879 res = waitid(idtype, id, &si, options);
7880 Py_END_ALLOW_THREADS
7881 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7882 if (res < 0)
7883 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007884
7885 if (si.si_pid == 0)
7886 Py_RETURN_NONE;
7887
Hai Shif707d942020-03-16 21:15:01 +08007888 PyObject *WaitidResultType = get_posix_state(module)->WaitidResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -08007889 result = PyStructSequence_New((PyTypeObject *)WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +02007890 if (!result)
7891 return NULL;
7892
7893 PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007894 PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
Ross Lagerwall7807c352011-03-17 20:20:30 +02007895 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
7896 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
7897 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
7898 if (PyErr_Occurred()) {
7899 Py_DECREF(result);
7900 return NULL;
7901 }
7902
7903 return result;
7904}
Larry Hastings2f936352014-08-05 14:04:04 +10007905#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
Ross Lagerwall7807c352011-03-17 20:20:30 +02007906
Larry Hastings2f936352014-08-05 14:04:04 +10007907
7908#if defined(HAVE_WAITPID)
7909/*[clinic input]
7910os.waitpid
7911 pid: pid_t
7912 options: int
7913 /
7914
7915Wait for completion of a given child process.
7916
7917Returns a tuple of information regarding the child process:
7918 (pid, status)
7919
7920The options argument is ignored on Windows.
7921[clinic start generated code]*/
7922
Larry Hastings2f936352014-08-05 14:04:04 +10007923static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007924os_waitpid_impl(PyObject *module, pid_t pid, int options)
7925/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007926{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007927 pid_t res;
7928 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007929 WAIT_TYPE status;
7930 WAIT_STATUS_INT(status) = 0;
Guido van Rossum54ecc3d1999-01-27 17:53:11 +00007931
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007932 do {
7933 Py_BEGIN_ALLOW_THREADS
7934 res = waitpid(pid, &status, options);
7935 Py_END_ALLOW_THREADS
7936 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7937 if (res < 0)
7938 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007939
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007940 return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
Guido van Rossum21803b81992-08-09 12:55:27 +00007941}
Tim Petersab034fa2002-02-01 11:27:43 +00007942#elif defined(HAVE_CWAIT)
Tim Petersab034fa2002-02-01 11:27:43 +00007943/* MS C has a variant of waitpid() that's usable for most purposes. */
Larry Hastings2f936352014-08-05 14:04:04 +10007944/*[clinic input]
7945os.waitpid
Benjamin Petersonca470632016-09-06 13:47:26 -07007946 pid: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +10007947 options: int
7948 /
7949
7950Wait for completion of a given process.
7951
7952Returns a tuple of information regarding the process:
7953 (pid, status << 8)
7954
7955The options argument is ignored on Windows.
7956[clinic start generated code]*/
7957
Larry Hastings2f936352014-08-05 14:04:04 +10007958static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -07007959os_waitpid_impl(PyObject *module, intptr_t pid, int options)
Victor Stinner581139c2016-09-06 15:54:20 -07007960/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007961{
7962 int status;
Benjamin Petersonca470632016-09-06 13:47:26 -07007963 intptr_t res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007964 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007965
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007966 do {
7967 Py_BEGIN_ALLOW_THREADS
Steve Dower11f43262016-11-19 18:33:39 -08007968 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007969 res = _cwait(&status, pid, options);
Steve Dower11f43262016-11-19 18:33:39 -08007970 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007971 Py_END_ALLOW_THREADS
7972 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinnerd3ffd322015-09-15 10:11:03 +02007973 if (res < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007974 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007975
Victor Stinner9bee32b2020-04-22 16:30:35 +02007976 unsigned long long ustatus = (unsigned int)status;
7977
Victor Stinner8c62be82010-05-06 00:08:46 +00007978 /* shift the status left a byte so this is more like the POSIX waitpid */
Victor Stinner9bee32b2020-04-22 16:30:35 +02007979 return Py_BuildValue(_Py_PARSE_INTPTR "K", res, ustatus << 8);
Tim Petersab034fa2002-02-01 11:27:43 +00007980}
Larry Hastings2f936352014-08-05 14:04:04 +10007981#endif
7982
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007983
Guido van Rossumad0ee831995-03-01 10:34:45 +00007984#ifdef HAVE_WAIT
Larry Hastings2f936352014-08-05 14:04:04 +10007985/*[clinic input]
7986os.wait
7987
7988Wait for completion of a child process.
7989
7990Returns a tuple of information about the child process:
7991 (pid, status)
7992[clinic start generated code]*/
7993
Larry Hastings2f936352014-08-05 14:04:04 +10007994static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007995os_wait_impl(PyObject *module)
7996/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
Guido van Rossum21803b81992-08-09 12:55:27 +00007997{
Victor Stinner8c62be82010-05-06 00:08:46 +00007998 pid_t pid;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007999 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00008000 WAIT_TYPE status;
8001 WAIT_STATUS_INT(status) = 0;
Neal Norwitze241ce82003-02-17 18:17:05 +00008002
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008003 do {
8004 Py_BEGIN_ALLOW_THREADS
8005 pid = wait(&status);
8006 Py_END_ALLOW_THREADS
8007 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8008 if (pid < 0)
8009 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008010
Victor Stinner8c62be82010-05-06 00:08:46 +00008011 return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
Guido van Rossum85e3b011991-06-03 12:42:10 +00008012}
Larry Hastings2f936352014-08-05 14:04:04 +10008013#endif /* HAVE_WAIT */
Guido van Rossum85e3b011991-06-03 12:42:10 +00008014
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -08008015#if defined(__linux__) && defined(__NR_pidfd_open)
8016/*[clinic input]
8017os.pidfd_open
8018 pid: pid_t
8019 flags: unsigned_int = 0
8020
8021Return a file descriptor referring to the process *pid*.
8022
8023The descriptor can be used to perform process management without races and
8024signals.
8025[clinic start generated code]*/
8026
8027static PyObject *
8028os_pidfd_open_impl(PyObject *module, pid_t pid, unsigned int flags)
8029/*[clinic end generated code: output=5c7252698947dc41 input=c3fd99ce947ccfef]*/
8030{
8031 int fd = syscall(__NR_pidfd_open, pid, flags);
8032 if (fd < 0) {
8033 return posix_error();
8034 }
8035 return PyLong_FromLong(fd);
8036}
8037#endif
8038
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008039
Larry Hastings9cf065c2012-06-22 16:30:09 -07008040#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008041/*[clinic input]
8042os.readlink
8043
8044 path: path_t
8045 *
8046 dir_fd: dir_fd(requires='readlinkat') = None
8047
8048Return a string representing the path to which the symbolic link points.
8049
8050If dir_fd is not None, it should be a file descriptor open to a directory,
8051and path should be relative; path will then be relative to that directory.
8052
8053dir_fd may not be implemented on your platform. If it is unavailable,
8054using it will raise a NotImplementedError.
8055[clinic start generated code]*/
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008056
Barry Warsaw53699e91996-12-10 23:23:01 +00008057static PyObject *
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008058os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
8059/*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008060{
Berker Peksage0b5b202018-08-15 13:03:41 +03008061#if defined(HAVE_READLINK)
Christian Heimes3cb091e2016-09-23 20:24:28 +02008062 char buffer[MAXPATHLEN+1];
Larry Hastings9cf065c2012-06-22 16:30:09 -07008063 ssize_t length;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008064
8065 Py_BEGIN_ALLOW_THREADS
8066#ifdef HAVE_READLINKAT
8067 if (dir_fd != DEFAULT_DIR_FD)
8068 length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
8069 else
8070#endif
8071 length = readlink(path->narrow, buffer, MAXPATHLEN);
8072 Py_END_ALLOW_THREADS
8073
8074 if (length < 0) {
8075 return path_error(path);
8076 }
8077 buffer[length] = '\0';
8078
8079 if (PyUnicode_Check(path->object))
8080 return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
8081 else
8082 return PyBytes_FromStringAndSize(buffer, length);
Berker Peksage0b5b202018-08-15 13:03:41 +03008083#elif defined(MS_WINDOWS)
8084 DWORD n_bytes_returned;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008085 DWORD io_result = 0;
Berker Peksage0b5b202018-08-15 13:03:41 +03008086 HANDLE reparse_point_handle;
Berker Peksage0b5b202018-08-15 13:03:41 +03008087 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
8088 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Steve Dower993ac922019-09-03 12:50:51 -07008089 PyObject *result = NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00008090
Larry Hastings2f936352014-08-05 14:04:04 +10008091 /* First get a handle to the reparse point */
8092 Py_BEGIN_ALLOW_THREADS
8093 reparse_point_handle = CreateFileW(
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008094 path->wide,
Larry Hastings2f936352014-08-05 14:04:04 +10008095 0,
8096 0,
8097 0,
8098 OPEN_EXISTING,
8099 FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
8100 0);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008101 if (reparse_point_handle != INVALID_HANDLE_VALUE) {
8102 /* New call DeviceIoControl to read the reparse point */
8103 io_result = DeviceIoControl(
8104 reparse_point_handle,
8105 FSCTL_GET_REPARSE_POINT,
8106 0, 0, /* in buffer */
8107 target_buffer, sizeof(target_buffer),
8108 &n_bytes_returned,
8109 0 /* we're not using OVERLAPPED_IO */
8110 );
8111 CloseHandle(reparse_point_handle);
Berker Peksage0b5b202018-08-15 13:03:41 +03008112 }
Larry Hastings2f936352014-08-05 14:04:04 +10008113 Py_END_ALLOW_THREADS
8114
Berker Peksage0b5b202018-08-15 13:03:41 +03008115 if (io_result == 0) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008116 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03008117 }
Larry Hastings2f936352014-08-05 14:04:04 +10008118
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008119 wchar_t *name = NULL;
8120 Py_ssize_t nameLen = 0;
8121 if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
Larry Hastings2f936352014-08-05 14:04:04 +10008122 {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008123 name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
8124 rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
8125 nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
Larry Hastings2f936352014-08-05 14:04:04 +10008126 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008127 else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
8128 {
8129 name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
8130 rdb->MountPointReparseBuffer.SubstituteNameOffset);
8131 nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
8132 }
8133 else
8134 {
8135 PyErr_SetString(PyExc_ValueError, "not a symbolic link");
8136 }
8137 if (name) {
8138 if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
8139 /* Our buffer is mutable, so this is okay */
8140 name[1] = L'\\';
8141 }
8142 result = PyUnicode_FromWideChar(name, nameLen);
Steve Dower993ac922019-09-03 12:50:51 -07008143 if (result && path->narrow) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008144 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
8145 }
Berker Peksage0b5b202018-08-15 13:03:41 +03008146 }
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008147 return result;
Berker Peksage0b5b202018-08-15 13:03:41 +03008148#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008149}
Berker Peksage0b5b202018-08-15 13:03:41 +03008150#endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008151
Larry Hastings9cf065c2012-06-22 16:30:09 -07008152#ifdef HAVE_SYMLINK
Larry Hastings9cf065c2012-06-22 16:30:09 -07008153
8154#if defined(MS_WINDOWS)
8155
Steve Dower6921e732018-03-05 14:26:08 -08008156/* Remove the last portion of the path - return 0 on success */
8157static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008158_dirnameW(WCHAR *path)
8159{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008160 WCHAR *ptr;
Steve Dower6921e732018-03-05 14:26:08 -08008161 size_t length = wcsnlen_s(path, MAX_PATH);
8162 if (length == MAX_PATH) {
8163 return -1;
8164 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008165
8166 /* walk the path from the end until a backslash is encountered */
Steve Dower6921e732018-03-05 14:26:08 -08008167 for(ptr = path + length; ptr != path; ptr--) {
8168 if (*ptr == L'\\' || *ptr == L'/') {
Jason R. Coombs3a092862013-05-27 23:21:28 -04008169 break;
Steve Dower6921e732018-03-05 14:26:08 -08008170 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008171 }
8172 *ptr = 0;
Steve Dower6921e732018-03-05 14:26:08 -08008173 return 0;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008174}
8175
Victor Stinner31b3b922013-06-05 01:49:17 +02008176/* Is this path absolute? */
8177static int
8178_is_absW(const WCHAR *path)
8179{
Steve Dower6921e732018-03-05 14:26:08 -08008180 return path[0] == L'\\' || path[0] == L'/' ||
8181 (path[0] && path[1] == L':');
Jason R. Coombs3a092862013-05-27 23:21:28 -04008182}
8183
Steve Dower6921e732018-03-05 14:26:08 -08008184/* join root and rest with a backslash - return 0 on success */
8185static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008186_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
8187{
Victor Stinner31b3b922013-06-05 01:49:17 +02008188 if (_is_absW(rest)) {
Steve Dower6921e732018-03-05 14:26:08 -08008189 return wcscpy_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008190 }
8191
Steve Dower6921e732018-03-05 14:26:08 -08008192 if (wcscpy_s(dest_path, MAX_PATH, root)) {
8193 return -1;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008194 }
Steve Dower6921e732018-03-05 14:26:08 -08008195
8196 if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
8197 return -1;
8198 }
8199
8200 return wcscat_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008201}
8202
Victor Stinner31b3b922013-06-05 01:49:17 +02008203/* Return True if the path at src relative to dest is a directory */
8204static int
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03008205_check_dirW(LPCWSTR src, LPCWSTR dest)
Jason R. Coombs3a092862013-05-27 23:21:28 -04008206{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008207 WIN32_FILE_ATTRIBUTE_DATA src_info;
8208 WCHAR dest_parent[MAX_PATH];
8209 WCHAR src_resolved[MAX_PATH] = L"";
8210
8211 /* dest_parent = os.path.dirname(dest) */
Steve Dower6921e732018-03-05 14:26:08 -08008212 if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
8213 _dirnameW(dest_parent)) {
8214 return 0;
8215 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008216 /* src_resolved = os.path.join(dest_parent, src) */
Steve Dower6921e732018-03-05 14:26:08 -08008217 if (_joinW(src_resolved, dest_parent, src)) {
8218 return 0;
8219 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008220 return (
8221 GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
8222 && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
8223 );
8224}
Larry Hastings9cf065c2012-06-22 16:30:09 -07008225#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008226
Larry Hastings2f936352014-08-05 14:04:04 +10008227
8228/*[clinic input]
8229os.symlink
8230 src: path_t
8231 dst: path_t
8232 target_is_directory: bool = False
8233 *
8234 dir_fd: dir_fd(requires='symlinkat')=None
8235
8236# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
8237
8238Create a symbolic link pointing to src named dst.
8239
8240target_is_directory is required on Windows if the target is to be
8241 interpreted as a directory. (On Windows, symlink requires
8242 Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
8243 target_is_directory is ignored on non-Windows platforms.
8244
8245If dir_fd is not None, it should be a file descriptor open to a directory,
8246 and path should be relative; path will then be relative to that directory.
8247dir_fd may not be implemented on your platform.
8248 If it is unavailable, using it will raise a NotImplementedError.
8249
8250[clinic start generated code]*/
8251
Larry Hastings2f936352014-08-05 14:04:04 +10008252static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008253os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
Larry Hastings89964c42015-04-14 18:07:59 -04008254 int target_is_directory, int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008255/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008256{
Larry Hastings9cf065c2012-06-22 16:30:09 -07008257#ifdef MS_WINDOWS
8258 DWORD result;
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008259 DWORD flags = 0;
8260
8261 /* Assumed true, set to false if detected to not be available. */
8262 static int windows_has_symlink_unprivileged_flag = TRUE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008263#else
8264 int result;
8265#endif
8266
Saiyang Gou7514f4f2020-02-12 23:47:42 -08008267 if (PySys_Audit("os.symlink", "OOi", src->object, dst->object,
8268 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
8269 return NULL;
8270 }
8271
Larry Hastings9cf065c2012-06-22 16:30:09 -07008272#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008273
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008274 if (windows_has_symlink_unprivileged_flag) {
8275 /* Allow non-admin symlinks if system allows it. */
8276 flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
8277 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008278
Larry Hastings9cf065c2012-06-22 16:30:09 -07008279 Py_BEGIN_ALLOW_THREADS
Steve Dower6921e732018-03-05 14:26:08 -08008280 _Py_BEGIN_SUPPRESS_IPH
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008281 /* if src is a directory, ensure flags==1 (target_is_directory bit) */
8282 if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
8283 flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
8284 }
8285
8286 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
Steve Dower6921e732018-03-05 14:26:08 -08008287 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07008288 Py_END_ALLOW_THREADS
8289
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008290 if (windows_has_symlink_unprivileged_flag && !result &&
8291 ERROR_INVALID_PARAMETER == GetLastError()) {
8292
8293 Py_BEGIN_ALLOW_THREADS
8294 _Py_BEGIN_SUPPRESS_IPH
8295 /* This error might be caused by
8296 SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
8297 Try again, and update windows_has_symlink_unprivileged_flag if we
8298 are successful this time.
8299
8300 NOTE: There is a risk of a race condition here if there are other
8301 conditions than the flag causing ERROR_INVALID_PARAMETER, and
8302 another process (or thread) changes that condition in between our
8303 calls to CreateSymbolicLink.
8304 */
8305 flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
8306 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
8307 _Py_END_SUPPRESS_IPH
8308 Py_END_ALLOW_THREADS
8309
8310 if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
8311 windows_has_symlink_unprivileged_flag = FALSE;
8312 }
8313 }
8314
Larry Hastings2f936352014-08-05 14:04:04 +10008315 if (!result)
8316 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008317
8318#else
8319
Steve Dower6921e732018-03-05 14:26:08 -08008320 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
8321 PyErr_SetString(PyExc_ValueError,
8322 "symlink: src and dst must be the same type");
8323 return NULL;
8324 }
8325
Larry Hastings9cf065c2012-06-22 16:30:09 -07008326 Py_BEGIN_ALLOW_THREADS
8327#if HAVE_SYMLINKAT
8328 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10008329 result = symlinkat(src->narrow, dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008330 else
8331#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008332 result = symlink(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008333 Py_END_ALLOW_THREADS
8334
Larry Hastings2f936352014-08-05 14:04:04 +10008335 if (result)
8336 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008337#endif
8338
Larry Hastings2f936352014-08-05 14:04:04 +10008339 Py_RETURN_NONE;
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008340}
8341#endif /* HAVE_SYMLINK */
8342
Larry Hastings9cf065c2012-06-22 16:30:09 -07008343
Brian Curtind40e6f72010-07-08 21:39:08 +00008344
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008345
Larry Hastings605a62d2012-06-24 04:33:36 -07008346static PyStructSequence_Field times_result_fields[] = {
8347 {"user", "user time"},
8348 {"system", "system time"},
8349 {"children_user", "user time of children"},
8350 {"children_system", "system time of children"},
8351 {"elapsed", "elapsed time since an arbitrary point in the past"},
8352 {NULL}
8353};
8354
8355PyDoc_STRVAR(times_result__doc__,
8356"times_result: Result from os.times().\n\n\
8357This object may be accessed either as a tuple of\n\
8358 (user, system, children_user, children_system, elapsed),\n\
8359or via the attributes user, system, children_user, children_system,\n\
8360and elapsed.\n\
8361\n\
8362See os.times for more information.");
8363
8364static PyStructSequence_Desc times_result_desc = {
8365 "times_result", /* name */
8366 times_result__doc__, /* doc */
8367 times_result_fields,
8368 5
8369};
8370
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008371#ifdef MS_WINDOWS
8372#define HAVE_TIMES /* mandatory, for the method table */
8373#endif
Larry Hastings605a62d2012-06-24 04:33:36 -07008374
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008375#ifdef HAVE_TIMES
Larry Hastings605a62d2012-06-24 04:33:36 -07008376
8377static PyObject *
8378build_times_result(double user, double system,
8379 double children_user, double children_system,
8380 double elapsed)
8381{
Eddie Elizondob3966632019-11-05 07:16:14 -08008382 PyObject *TimesResultType = _posixstate_global->TimesResultType;
8383 PyObject *value = PyStructSequence_New((PyTypeObject *)TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07008384 if (value == NULL)
8385 return NULL;
8386
8387#define SET(i, field) \
8388 { \
8389 PyObject *o = PyFloat_FromDouble(field); \
8390 if (!o) { \
8391 Py_DECREF(value); \
8392 return NULL; \
8393 } \
8394 PyStructSequence_SET_ITEM(value, i, o); \
8395 } \
8396
8397 SET(0, user);
8398 SET(1, system);
8399 SET(2, children_user);
8400 SET(3, children_system);
8401 SET(4, elapsed);
8402
8403#undef SET
8404
8405 return value;
8406}
8407
Larry Hastings605a62d2012-06-24 04:33:36 -07008408
Larry Hastings2f936352014-08-05 14:04:04 +10008409#ifndef MS_WINDOWS
8410#define NEED_TICKS_PER_SECOND
8411static long ticks_per_second = -1;
8412#endif /* MS_WINDOWS */
8413
8414/*[clinic input]
8415os.times
8416
8417Return a collection containing process timing information.
8418
8419The object returned behaves like a named tuple with these fields:
8420 (utime, stime, cutime, cstime, elapsed_time)
8421All fields are floating point numbers.
8422[clinic start generated code]*/
8423
Larry Hastings2f936352014-08-05 14:04:04 +10008424static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008425os_times_impl(PyObject *module)
8426/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008427#ifdef MS_WINDOWS
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008428{
Victor Stinner8c62be82010-05-06 00:08:46 +00008429 FILETIME create, exit, kernel, user;
8430 HANDLE hProc;
8431 hProc = GetCurrentProcess();
8432 GetProcessTimes(hProc, &create, &exit, &kernel, &user);
8433 /* The fields of a FILETIME structure are the hi and lo part
8434 of a 64-bit value expressed in 100 nanosecond units.
8435 1e7 is one second in such units; 1e-7 the inverse.
8436 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
8437 */
Larry Hastings605a62d2012-06-24 04:33:36 -07008438 return build_times_result(
Victor Stinner8c62be82010-05-06 00:08:46 +00008439 (double)(user.dwHighDateTime*429.4967296 +
8440 user.dwLowDateTime*1e-7),
8441 (double)(kernel.dwHighDateTime*429.4967296 +
8442 kernel.dwLowDateTime*1e-7),
8443 (double)0,
8444 (double)0,
8445 (double)0);
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008446}
Larry Hastings2f936352014-08-05 14:04:04 +10008447#else /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008448{
Larry Hastings2f936352014-08-05 14:04:04 +10008449
8450
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008451 struct tms t;
8452 clock_t c;
8453 errno = 0;
8454 c = times(&t);
8455 if (c == (clock_t) -1)
8456 return posix_error();
8457 return build_times_result(
8458 (double)t.tms_utime / ticks_per_second,
8459 (double)t.tms_stime / ticks_per_second,
8460 (double)t.tms_cutime / ticks_per_second,
8461 (double)t.tms_cstime / ticks_per_second,
8462 (double)c / ticks_per_second);
8463}
Larry Hastings2f936352014-08-05 14:04:04 +10008464#endif /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008465#endif /* HAVE_TIMES */
8466
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008467
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008468#ifdef HAVE_GETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008469/*[clinic input]
8470os.getsid
8471
8472 pid: pid_t
8473 /
8474
8475Call the system call getsid(pid) and return the result.
8476[clinic start generated code]*/
8477
Larry Hastings2f936352014-08-05 14:04:04 +10008478static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008479os_getsid_impl(PyObject *module, pid_t pid)
8480/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008481{
Victor Stinner8c62be82010-05-06 00:08:46 +00008482 int sid;
Victor Stinner8c62be82010-05-06 00:08:46 +00008483 sid = getsid(pid);
8484 if (sid < 0)
8485 return posix_error();
8486 return PyLong_FromLong((long)sid);
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008487}
8488#endif /* HAVE_GETSID */
8489
8490
Guido van Rossumb6775db1994-08-01 11:34:53 +00008491#ifdef HAVE_SETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008492/*[clinic input]
8493os.setsid
8494
8495Call the system call setsid().
8496[clinic start generated code]*/
8497
Larry Hastings2f936352014-08-05 14:04:04 +10008498static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008499os_setsid_impl(PyObject *module)
8500/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00008501{
Victor Stinner8c62be82010-05-06 00:08:46 +00008502 if (setsid() < 0)
8503 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008504 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008505}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008506#endif /* HAVE_SETSID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008507
Larry Hastings2f936352014-08-05 14:04:04 +10008508
Guido van Rossumb6775db1994-08-01 11:34:53 +00008509#ifdef HAVE_SETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10008510/*[clinic input]
8511os.setpgid
8512
8513 pid: pid_t
8514 pgrp: pid_t
8515 /
8516
8517Call the system call setpgid(pid, pgrp).
8518[clinic start generated code]*/
8519
Larry Hastings2f936352014-08-05 14:04:04 +10008520static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008521os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
8522/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008523{
Victor Stinner8c62be82010-05-06 00:08:46 +00008524 if (setpgid(pid, pgrp) < 0)
8525 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008526 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008527}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008528#endif /* HAVE_SETPGID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008529
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008530
Guido van Rossumb6775db1994-08-01 11:34:53 +00008531#ifdef HAVE_TCGETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008532/*[clinic input]
8533os.tcgetpgrp
8534
8535 fd: int
8536 /
8537
8538Return the process group associated with the terminal specified by fd.
8539[clinic start generated code]*/
8540
Larry Hastings2f936352014-08-05 14:04:04 +10008541static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008542os_tcgetpgrp_impl(PyObject *module, int fd)
8543/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008544{
8545 pid_t pgid = tcgetpgrp(fd);
Victor Stinner8c62be82010-05-06 00:08:46 +00008546 if (pgid < 0)
8547 return posix_error();
8548 return PyLong_FromPid(pgid);
Guido van Rossum7066dd71992-09-17 17:54:56 +00008549}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008550#endif /* HAVE_TCGETPGRP */
Guido van Rossum7066dd71992-09-17 17:54:56 +00008551
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008552
Guido van Rossumb6775db1994-08-01 11:34:53 +00008553#ifdef HAVE_TCSETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008554/*[clinic input]
8555os.tcsetpgrp
8556
8557 fd: int
8558 pgid: pid_t
8559 /
8560
8561Set the process group associated with the terminal specified by fd.
8562[clinic start generated code]*/
8563
Larry Hastings2f936352014-08-05 14:04:04 +10008564static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008565os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
8566/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008567{
Victor Stinner8c62be82010-05-06 00:08:46 +00008568 if (tcsetpgrp(fd, pgid) < 0)
8569 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008570 Py_RETURN_NONE;
Guido van Rossum7066dd71992-09-17 17:54:56 +00008571}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008572#endif /* HAVE_TCSETPGRP */
Guido van Rossum22db57e1992-04-05 14:25:30 +00008573
Guido van Rossum687dd131993-05-17 08:34:16 +00008574/* Functions acting on file descriptors */
8575
Victor Stinnerdaf45552013-08-28 00:53:59 +02008576#ifdef O_CLOEXEC
8577extern int _Py_open_cloexec_works;
8578#endif
8579
Larry Hastings2f936352014-08-05 14:04:04 +10008580
8581/*[clinic input]
8582os.open -> int
8583 path: path_t
8584 flags: int
8585 mode: int = 0o777
8586 *
8587 dir_fd: dir_fd(requires='openat') = None
8588
8589# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
8590
8591Open a file for low level IO. Returns a file descriptor (integer).
8592
8593If dir_fd is not None, it should be a file descriptor open to a directory,
8594 and path should be relative; path will then be relative to that directory.
8595dir_fd may not be implemented on your platform.
8596 If it is unavailable, using it will raise a NotImplementedError.
8597[clinic start generated code]*/
8598
Larry Hastings2f936352014-08-05 14:04:04 +10008599static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008600os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
8601/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008602{
8603 int fd;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008604 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008605
Victor Stinnerdaf45552013-08-28 00:53:59 +02008606#ifdef O_CLOEXEC
8607 int *atomic_flag_works = &_Py_open_cloexec_works;
8608#elif !defined(MS_WINDOWS)
8609 int *atomic_flag_works = NULL;
8610#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +00008611
Victor Stinnerdaf45552013-08-28 00:53:59 +02008612#ifdef MS_WINDOWS
8613 flags |= O_NOINHERIT;
8614#elif defined(O_CLOEXEC)
8615 flags |= O_CLOEXEC;
8616#endif
8617
Steve Dowerb82e17e2019-05-23 08:45:22 -07008618 if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
8619 return -1;
8620 }
8621
Steve Dower8fc89802015-04-12 00:26:27 -04008622 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008623 do {
8624 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008625#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07008626 fd = _wopen(path->wide, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008627#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07008628#ifdef HAVE_OPENAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008629 if (dir_fd != DEFAULT_DIR_FD)
8630 fd = openat(dir_fd, path->narrow, flags, mode);
8631 else
Steve Dower6230aaf2016-09-09 09:03:15 -07008632#endif /* HAVE_OPENAT */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008633 fd = open(path->narrow, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008634#endif /* !MS_WINDOWS */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008635 Py_END_ALLOW_THREADS
8636 } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04008637 _Py_END_SUPPRESS_IPH
Guido van Rossum687dd131993-05-17 08:34:16 +00008638
Victor Stinnerd3ffd322015-09-15 10:11:03 +02008639 if (fd < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008640 if (!async_err)
8641 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Larry Hastings2f936352014-08-05 14:04:04 +10008642 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008643 }
8644
Victor Stinnerdaf45552013-08-28 00:53:59 +02008645#ifndef MS_WINDOWS
8646 if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
8647 close(fd);
Larry Hastings2f936352014-08-05 14:04:04 +10008648 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008649 }
8650#endif
8651
Larry Hastings2f936352014-08-05 14:04:04 +10008652 return fd;
8653}
8654
8655
8656/*[clinic input]
8657os.close
8658
8659 fd: int
8660
8661Close a file descriptor.
8662[clinic start generated code]*/
8663
Barry Warsaw53699e91996-12-10 23:23:01 +00008664static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008665os_close_impl(PyObject *module, int fd)
8666/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00008667{
Larry Hastings2f936352014-08-05 14:04:04 +10008668 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008669 /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
8670 * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
8671 * for more details.
8672 */
Victor Stinner8c62be82010-05-06 00:08:46 +00008673 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008674 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008675 res = close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04008676 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008677 Py_END_ALLOW_THREADS
8678 if (res < 0)
8679 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008680 Py_RETURN_NONE;
Guido van Rossum687dd131993-05-17 08:34:16 +00008681}
8682
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008683
Jakub Kulíke20134f2019-09-11 17:11:57 +02008684#ifdef HAVE_FDWALK
8685static int
8686_fdwalk_close_func(void *lohi, int fd)
8687{
8688 int lo = ((int *)lohi)[0];
8689 int hi = ((int *)lohi)[1];
8690
Victor Stinner162c5672020-04-24 12:00:51 +02008691 if (fd >= hi) {
Jakub Kulíke20134f2019-09-11 17:11:57 +02008692 return 1;
Victor Stinner162c5672020-04-24 12:00:51 +02008693 }
8694 else if (fd >= lo) {
8695 /* Ignore errors */
8696 (void)close(fd);
8697 }
Jakub Kulíke20134f2019-09-11 17:11:57 +02008698 return 0;
8699}
8700#endif /* HAVE_FDWALK */
8701
Larry Hastings2f936352014-08-05 14:04:04 +10008702/*[clinic input]
8703os.closerange
8704
8705 fd_low: int
8706 fd_high: int
8707 /
8708
8709Closes all file descriptors in [fd_low, fd_high), ignoring errors.
8710[clinic start generated code]*/
8711
Larry Hastings2f936352014-08-05 14:04:04 +10008712static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008713os_closerange_impl(PyObject *module, int fd_low, int fd_high)
8714/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008715{
Jakub Kulíke20134f2019-09-11 17:11:57 +02008716#ifdef HAVE_FDWALK
8717 int lohi[2];
Jakub Kulíke20134f2019-09-11 17:11:57 +02008718#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00008719 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008720 _Py_BEGIN_SUPPRESS_IPH
Jakub Kulíke20134f2019-09-11 17:11:57 +02008721#ifdef HAVE_FDWALK
8722 lohi[0] = Py_MAX(fd_low, 0);
8723 lohi[1] = fd_high;
8724 fdwalk(_fdwalk_close_func, lohi);
8725#else
Victor Stinner162c5672020-04-24 12:00:51 +02008726 fd_low = Py_MAX(fd_low, 0);
8727#ifdef __FreeBSD__
8728 if (fd_high >= sysconf(_SC_OPEN_MAX)) {
8729 /* Any errors encountered while closing file descriptors are ignored */
8730 closefrom(fd_low);
8731 }
8732 else
8733#endif
8734 {
8735 for (int i = fd_low; i < fd_high; i++) {
8736 /* Ignore errors */
8737 (void)close(i);
8738 }
8739 }
Jakub Kulíke20134f2019-09-11 17:11:57 +02008740#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008741 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008742 Py_END_ALLOW_THREADS
8743 Py_RETURN_NONE;
Christian Heimesfdab48e2008-01-20 09:06:41 +00008744}
8745
8746
Larry Hastings2f936352014-08-05 14:04:04 +10008747/*[clinic input]
8748os.dup -> int
8749
8750 fd: int
8751 /
8752
8753Return a duplicate of a file descriptor.
8754[clinic start generated code]*/
8755
Larry Hastings2f936352014-08-05 14:04:04 +10008756static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008757os_dup_impl(PyObject *module, int fd)
8758/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008759{
8760 return _Py_dup(fd);
Guido van Rossum687dd131993-05-17 08:34:16 +00008761}
8762
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008763
Larry Hastings2f936352014-08-05 14:04:04 +10008764/*[clinic input]
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008765os.dup2 -> int
Larry Hastings2f936352014-08-05 14:04:04 +10008766 fd: int
8767 fd2: int
8768 inheritable: bool=True
8769
8770Duplicate file descriptor.
8771[clinic start generated code]*/
8772
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008773static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008774os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008775/*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008776{
Stéphane Wirtel3d86e482018-01-30 07:04:36 +01008777 int res = 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008778#if defined(HAVE_DUP3) && \
8779 !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
8780 /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
Alexey Izbyshevb3caf382018-02-20 10:25:46 +03008781 static int dup3_works = -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008782#endif
8783
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008784 if (fd < 0 || fd2 < 0) {
8785 posix_error();
8786 return -1;
8787 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008788
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008789 /* dup2() can fail with EINTR if the target FD is already open, because it
8790 * then has to be closed. See os_close_impl() for why we don't handle EINTR
8791 * upon close(), and therefore below.
8792 */
Victor Stinnerdaf45552013-08-28 00:53:59 +02008793#ifdef MS_WINDOWS
8794 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008795 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008796 res = dup2(fd, fd2);
Steve Dower8fc89802015-04-12 00:26:27 -04008797 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02008798 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008799 if (res < 0) {
8800 posix_error();
8801 return -1;
8802 }
8803 res = fd2; // msvcrt dup2 returns 0 on success.
Victor Stinnerdaf45552013-08-28 00:53:59 +02008804
8805 /* Character files like console cannot be make non-inheritable */
8806 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8807 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008808 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008809 }
8810
8811#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
8812 Py_BEGIN_ALLOW_THREADS
8813 if (!inheritable)
8814 res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
8815 else
8816 res = dup2(fd, fd2);
8817 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008818 if (res < 0) {
8819 posix_error();
8820 return -1;
8821 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008822
8823#else
8824
8825#ifdef HAVE_DUP3
8826 if (!inheritable && dup3_works != 0) {
8827 Py_BEGIN_ALLOW_THREADS
8828 res = dup3(fd, fd2, O_CLOEXEC);
8829 Py_END_ALLOW_THREADS
8830 if (res < 0) {
8831 if (dup3_works == -1)
8832 dup3_works = (errno != ENOSYS);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008833 if (dup3_works) {
8834 posix_error();
8835 return -1;
8836 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008837 }
8838 }
8839
8840 if (inheritable || dup3_works == 0)
8841 {
8842#endif
8843 Py_BEGIN_ALLOW_THREADS
8844 res = dup2(fd, fd2);
8845 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008846 if (res < 0) {
8847 posix_error();
8848 return -1;
8849 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008850
8851 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8852 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008853 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008854 }
8855#ifdef HAVE_DUP3
8856 }
8857#endif
8858
8859#endif
8860
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008861 return res;
Guido van Rossum687dd131993-05-17 08:34:16 +00008862}
8863
Larry Hastings2f936352014-08-05 14:04:04 +10008864
Ross Lagerwall7807c352011-03-17 20:20:30 +02008865#ifdef HAVE_LOCKF
Larry Hastings2f936352014-08-05 14:04:04 +10008866/*[clinic input]
8867os.lockf
8868
8869 fd: int
8870 An open file descriptor.
8871 command: int
8872 One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
8873 length: Py_off_t
8874 The number of bytes to lock, starting at the current position.
8875 /
8876
8877Apply, test or remove a POSIX lock on an open file descriptor.
8878
8879[clinic start generated code]*/
8880
Larry Hastings2f936352014-08-05 14:04:04 +10008881static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008882os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
8883/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008884{
8885 int res;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008886
Saiyang Gou7514f4f2020-02-12 23:47:42 -08008887 if (PySys_Audit("os.lockf", "iiL", fd, command, length) < 0) {
8888 return NULL;
8889 }
8890
Ross Lagerwall7807c352011-03-17 20:20:30 +02008891 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008892 res = lockf(fd, command, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008893 Py_END_ALLOW_THREADS
8894
8895 if (res < 0)
8896 return posix_error();
8897
8898 Py_RETURN_NONE;
8899}
Larry Hastings2f936352014-08-05 14:04:04 +10008900#endif /* HAVE_LOCKF */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008901
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008902
Larry Hastings2f936352014-08-05 14:04:04 +10008903/*[clinic input]
8904os.lseek -> Py_off_t
8905
8906 fd: int
8907 position: Py_off_t
8908 how: int
8909 /
8910
8911Set the position of a file descriptor. Return the new position.
8912
8913Return the new cursor position in number of bytes
8914relative to the beginning of the file.
8915[clinic start generated code]*/
8916
Larry Hastings2f936352014-08-05 14:04:04 +10008917static Py_off_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008918os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
8919/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008920{
8921 Py_off_t result;
8922
Guido van Rossum687dd131993-05-17 08:34:16 +00008923#ifdef SEEK_SET
Victor Stinner8c62be82010-05-06 00:08:46 +00008924 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
8925 switch (how) {
Larry Hastings2f936352014-08-05 14:04:04 +10008926 case 0: how = SEEK_SET; break;
8927 case 1: how = SEEK_CUR; break;
8928 case 2: how = SEEK_END; break;
Victor Stinner8c62be82010-05-06 00:08:46 +00008929 }
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00008930#endif /* SEEK_END */
Guido van Rossum94f6f721999-01-06 18:42:14 +00008931
Victor Stinner8c62be82010-05-06 00:08:46 +00008932 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008933 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner14b9b112013-06-25 00:37:25 +02008934#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10008935 result = _lseeki64(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008936#else
Larry Hastings2f936352014-08-05 14:04:04 +10008937 result = lseek(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008938#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008939 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008940 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008941 if (result < 0)
8942 posix_error();
Guido van Rossum94f6f721999-01-06 18:42:14 +00008943
Larry Hastings2f936352014-08-05 14:04:04 +10008944 return result;
Guido van Rossum687dd131993-05-17 08:34:16 +00008945}
8946
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008947
Larry Hastings2f936352014-08-05 14:04:04 +10008948/*[clinic input]
8949os.read
8950 fd: int
8951 length: Py_ssize_t
8952 /
8953
8954Read from a file descriptor. Returns a bytes object.
8955[clinic start generated code]*/
8956
Larry Hastings2f936352014-08-05 14:04:04 +10008957static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008958os_read_impl(PyObject *module, int fd, Py_ssize_t length)
8959/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008960{
Victor Stinner8c62be82010-05-06 00:08:46 +00008961 Py_ssize_t n;
8962 PyObject *buffer;
Larry Hastings2f936352014-08-05 14:04:04 +10008963
8964 if (length < 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008965 errno = EINVAL;
8966 return posix_error();
8967 }
Larry Hastings2f936352014-08-05 14:04:04 +10008968
Victor Stinner9a0d7a72018-11-22 15:03:40 +01008969 length = Py_MIN(length, _PY_READ_MAX);
Larry Hastings2f936352014-08-05 14:04:04 +10008970
8971 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Victor Stinner8c62be82010-05-06 00:08:46 +00008972 if (buffer == NULL)
8973 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008974
Victor Stinner66aab0c2015-03-19 22:53:20 +01008975 n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
8976 if (n == -1) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008977 Py_DECREF(buffer);
Victor Stinner66aab0c2015-03-19 22:53:20 +01008978 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00008979 }
Larry Hastings2f936352014-08-05 14:04:04 +10008980
8981 if (n != length)
Victor Stinner8c62be82010-05-06 00:08:46 +00008982 _PyBytes_Resize(&buffer, n);
Larry Hastings2f936352014-08-05 14:04:04 +10008983
Victor Stinner8c62be82010-05-06 00:08:46 +00008984 return buffer;
Guido van Rossum687dd131993-05-17 08:34:16 +00008985}
8986
Ross Lagerwall7807c352011-03-17 20:20:30 +02008987#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008988 || defined(__APPLE__))) \
8989 || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
8990 || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
8991static int
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008992iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008993{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008994 Py_ssize_t i, j;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008995
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008996 *iov = PyMem_New(struct iovec, cnt);
8997 if (*iov == NULL) {
8998 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008999 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009000 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009001
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009002 *buf = PyMem_New(Py_buffer, cnt);
9003 if (*buf == NULL) {
9004 PyMem_Del(*iov);
9005 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01009006 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009007 }
9008
9009 for (i = 0; i < cnt; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02009010 PyObject *item = PySequence_GetItem(seq, i);
9011 if (item == NULL)
9012 goto fail;
9013 if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
9014 Py_DECREF(item);
9015 goto fail;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009016 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02009017 Py_DECREF(item);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009018 (*iov)[i].iov_base = (*buf)[i].buf;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009019 (*iov)[i].iov_len = (*buf)[i].len;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009020 }
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009021 return 0;
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02009022
9023fail:
9024 PyMem_Del(*iov);
9025 for (j = 0; j < i; j++) {
9026 PyBuffer_Release(&(*buf)[j]);
9027 }
9028 PyMem_Del(*buf);
Victor Stinner57ddf782014-01-08 15:21:28 +01009029 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009030}
9031
9032static void
9033iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
9034{
9035 int i;
9036 PyMem_Del(iov);
9037 for (i = 0; i < cnt; i++) {
9038 PyBuffer_Release(&buf[i]);
9039 }
9040 PyMem_Del(buf);
9041}
9042#endif
9043
Larry Hastings2f936352014-08-05 14:04:04 +10009044
Ross Lagerwall7807c352011-03-17 20:20:30 +02009045#ifdef HAVE_READV
Larry Hastings2f936352014-08-05 14:04:04 +10009046/*[clinic input]
9047os.readv -> Py_ssize_t
9048
9049 fd: int
9050 buffers: object
9051 /
9052
9053Read from a file descriptor fd into an iterable of buffers.
9054
9055The buffers should be mutable buffers accepting bytes.
9056readv will transfer data into each buffer until it is full
9057and then move on to the next buffer in the sequence to hold
9058the rest of the data.
9059
9060readv returns the total number of bytes read,
9061which may be less than the total capacity of all the buffers.
9062[clinic start generated code]*/
9063
Larry Hastings2f936352014-08-05 14:04:04 +10009064static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009065os_readv_impl(PyObject *module, int fd, PyObject *buffers)
9066/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009067{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009068 Py_ssize_t cnt, n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009069 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009070 struct iovec *iov;
9071 Py_buffer *buf;
9072
Larry Hastings2f936352014-08-05 14:04:04 +10009073 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009074 PyErr_SetString(PyExc_TypeError,
9075 "readv() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009076 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009077 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02009078
Larry Hastings2f936352014-08-05 14:04:04 +10009079 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009080 if (cnt < 0)
9081 return -1;
Larry Hastings2f936352014-08-05 14:04:04 +10009082
9083 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
9084 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009085
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009086 do {
9087 Py_BEGIN_ALLOW_THREADS
9088 n = readv(fd, iov, cnt);
9089 Py_END_ALLOW_THREADS
9090 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009091
9092 iov_cleanup(iov, buf, cnt);
Larry Hastings2f936352014-08-05 14:04:04 +10009093 if (n < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009094 if (!async_err)
9095 posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10009096 return -1;
9097 }
Victor Stinner57ddf782014-01-08 15:21:28 +01009098
Larry Hastings2f936352014-08-05 14:04:04 +10009099 return n;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009100}
Larry Hastings2f936352014-08-05 14:04:04 +10009101#endif /* HAVE_READV */
9102
Ross Lagerwall7807c352011-03-17 20:20:30 +02009103
9104#ifdef HAVE_PREAD
Larry Hastings2f936352014-08-05 14:04:04 +10009105/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10009106os.pread
9107
9108 fd: int
Dong-hee Naad7736f2019-09-25 14:47:04 +09009109 length: Py_ssize_t
Larry Hastings2f936352014-08-05 14:04:04 +10009110 offset: Py_off_t
9111 /
9112
9113Read a number of bytes from a file descriptor starting at a particular offset.
9114
9115Read length bytes from file descriptor fd, starting at offset bytes from
9116the beginning of the file. The file offset remains unchanged.
9117[clinic start generated code]*/
9118
Larry Hastings2f936352014-08-05 14:04:04 +10009119static PyObject *
Dong-hee Naad7736f2019-09-25 14:47:04 +09009120os_pread_impl(PyObject *module, int fd, Py_ssize_t length, Py_off_t offset)
9121/*[clinic end generated code: output=3f875c1eef82e32f input=85cb4a5589627144]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009122{
Ross Lagerwall7807c352011-03-17 20:20:30 +02009123 Py_ssize_t n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009124 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009125 PyObject *buffer;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009126
Larry Hastings2f936352014-08-05 14:04:04 +10009127 if (length < 0) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009128 errno = EINVAL;
9129 return posix_error();
9130 }
Larry Hastings2f936352014-08-05 14:04:04 +10009131 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02009132 if (buffer == NULL)
9133 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009134
9135 do {
9136 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009137 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009138 n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009139 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009140 Py_END_ALLOW_THREADS
9141 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9142
Ross Lagerwall7807c352011-03-17 20:20:30 +02009143 if (n < 0) {
9144 Py_DECREF(buffer);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009145 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009146 }
Larry Hastings2f936352014-08-05 14:04:04 +10009147 if (n != length)
Ross Lagerwall7807c352011-03-17 20:20:30 +02009148 _PyBytes_Resize(&buffer, n);
9149 return buffer;
9150}
Larry Hastings2f936352014-08-05 14:04:04 +10009151#endif /* HAVE_PREAD */
Ross Lagerwall7807c352011-03-17 20:20:30 +02009152
Pablo Galindo4defba32018-01-27 16:16:37 +00009153#if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
9154/*[clinic input]
9155os.preadv -> Py_ssize_t
9156
9157 fd: int
9158 buffers: object
9159 offset: Py_off_t
9160 flags: int = 0
9161 /
9162
9163Reads from a file descriptor into a number of mutable bytes-like objects.
9164
9165Combines the functionality of readv() and pread(). As readv(), it will
9166transfer data into each buffer until it is full and then move on to the next
9167buffer in the sequence to hold the rest of the data. Its fourth argument,
9168specifies the file offset at which the input operation is to be performed. It
9169will return the total number of bytes read (which can be less than the total
9170capacity of all the objects).
9171
9172The flags argument contains a bitwise OR of zero or more of the following flags:
9173
9174- RWF_HIPRI
9175- RWF_NOWAIT
9176
9177Using non-zero flags requires Linux 4.6 or newer.
9178[clinic start generated code]*/
9179
9180static Py_ssize_t
9181os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9182 int flags)
9183/*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
9184{
9185 Py_ssize_t cnt, n;
9186 int async_err = 0;
9187 struct iovec *iov;
9188 Py_buffer *buf;
9189
9190 if (!PySequence_Check(buffers)) {
9191 PyErr_SetString(PyExc_TypeError,
9192 "preadv2() arg 2 must be a sequence");
9193 return -1;
9194 }
9195
9196 cnt = PySequence_Size(buffers);
9197 if (cnt < 0) {
9198 return -1;
9199 }
9200
9201#ifndef HAVE_PREADV2
9202 if(flags != 0) {
9203 argument_unavailable_error("preadv2", "flags");
9204 return -1;
9205 }
9206#endif
9207
9208 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
9209 return -1;
9210 }
9211#ifdef HAVE_PREADV2
9212 do {
9213 Py_BEGIN_ALLOW_THREADS
9214 _Py_BEGIN_SUPPRESS_IPH
9215 n = preadv2(fd, iov, cnt, offset, flags);
9216 _Py_END_SUPPRESS_IPH
9217 Py_END_ALLOW_THREADS
9218 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9219#else
9220 do {
9221 Py_BEGIN_ALLOW_THREADS
9222 _Py_BEGIN_SUPPRESS_IPH
9223 n = preadv(fd, iov, cnt, offset);
9224 _Py_END_SUPPRESS_IPH
9225 Py_END_ALLOW_THREADS
9226 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9227#endif
9228
9229 iov_cleanup(iov, buf, cnt);
9230 if (n < 0) {
9231 if (!async_err) {
9232 posix_error();
9233 }
9234 return -1;
9235 }
9236
9237 return n;
9238}
9239#endif /* HAVE_PREADV */
9240
Larry Hastings2f936352014-08-05 14:04:04 +10009241
9242/*[clinic input]
9243os.write -> Py_ssize_t
9244
9245 fd: int
9246 data: Py_buffer
9247 /
9248
9249Write a bytes object to a file descriptor.
9250[clinic start generated code]*/
9251
Larry Hastings2f936352014-08-05 14:04:04 +10009252static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009253os_write_impl(PyObject *module, int fd, Py_buffer *data)
9254/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009255{
Victor Stinner66aab0c2015-03-19 22:53:20 +01009256 return _Py_write(fd, data->buf, data->len);
Ross Lagerwall7807c352011-03-17 20:20:30 +02009257}
9258
9259#ifdef HAVE_SENDFILE
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009260#ifdef __APPLE__
9261/*[clinic input]
9262os.sendfile
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009263
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009264 out_fd: int
9265 in_fd: int
9266 offset: Py_off_t
9267 count as sbytes: Py_off_t
9268 headers: object(c_default="NULL") = ()
9269 trailers: object(c_default="NULL") = ()
9270 flags: int = 0
9271
9272Copy count bytes from file descriptor in_fd to file descriptor out_fd.
9273[clinic start generated code]*/
9274
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009275static PyObject *
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009276os_sendfile_impl(PyObject *module, int out_fd, int in_fd, Py_off_t offset,
9277 Py_off_t sbytes, PyObject *headers, PyObject *trailers,
9278 int flags)
9279/*[clinic end generated code: output=81c4bcd143f5c82b input=b0d72579d4c69afa]*/
9280#elif defined(__FreeBSD__) || defined(__DragonFly__)
9281/*[clinic input]
9282os.sendfile
9283
9284 out_fd: int
9285 in_fd: int
9286 offset: Py_off_t
9287 count: Py_ssize_t
9288 headers: object(c_default="NULL") = ()
9289 trailers: object(c_default="NULL") = ()
9290 flags: int = 0
9291
9292Copy count bytes from file descriptor in_fd to file descriptor out_fd.
9293[clinic start generated code]*/
9294
9295static PyObject *
9296os_sendfile_impl(PyObject *module, int out_fd, int in_fd, Py_off_t offset,
9297 Py_ssize_t count, PyObject *headers, PyObject *trailers,
9298 int flags)
9299/*[clinic end generated code: output=329ea009bdd55afc input=338adb8ff84ae8cd]*/
9300#else
9301/*[clinic input]
9302os.sendfile
9303
9304 out_fd: int
9305 in_fd: int
9306 offset as offobj: object
9307 count: Py_ssize_t
9308
9309Copy count bytes from file descriptor in_fd to file descriptor out_fd.
9310[clinic start generated code]*/
9311
9312static PyObject *
9313os_sendfile_impl(PyObject *module, int out_fd, int in_fd, PyObject *offobj,
9314 Py_ssize_t count)
9315/*[clinic end generated code: output=ae81216e40f167d8 input=76d64058c74477ba]*/
9316#endif
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009317{
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009318 Py_ssize_t ret;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009319 int async_err = 0;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009320
9321#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
9322#ifndef __APPLE__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009323 off_t sbytes;
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009324#endif
9325 Py_buffer *hbuf, *tbuf;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009326 struct sf_hdtr sf;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009327
Victor Stinner6ce0dbf2013-07-07 16:32:36 +02009328 sf.headers = NULL;
9329 sf.trailers = NULL;
9330
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009331 if (headers != NULL) {
9332 if (!PySequence_Check(headers)) {
9333 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009334 "sendfile() headers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009335 return NULL;
9336 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009337 Py_ssize_t i = PySequence_Size(headers);
9338 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009339 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009340 if (i > INT_MAX) {
9341 PyErr_SetString(PyExc_OverflowError,
9342 "sendfile() header is too large");
9343 return NULL;
9344 }
9345 if (i > 0) {
9346 sf.hdr_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009347 if (iov_setup(&(sf.headers), &hbuf,
9348 headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009349 return NULL;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009350#ifdef __APPLE__
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009351 for (i = 0; i < sf.hdr_cnt; i++) {
9352 Py_ssize_t blen = sf.headers[i].iov_len;
9353# define OFF_T_MAX 0x7fffffffffffffff
9354 if (sbytes >= OFF_T_MAX - blen) {
9355 PyErr_SetString(PyExc_OverflowError,
9356 "sendfile() header is too large");
9357 return NULL;
9358 }
9359 sbytes += blen;
9360 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009361#endif
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009362 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009363 }
9364 }
9365 if (trailers != NULL) {
9366 if (!PySequence_Check(trailers)) {
9367 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009368 "sendfile() trailers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009369 return NULL;
9370 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009371 Py_ssize_t i = PySequence_Size(trailers);
9372 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009373 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009374 if (i > INT_MAX) {
9375 PyErr_SetString(PyExc_OverflowError,
9376 "sendfile() trailer is too large");
9377 return NULL;
9378 }
9379 if (i > 0) {
9380 sf.trl_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009381 if (iov_setup(&(sf.trailers), &tbuf,
9382 trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009383 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009384 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009385 }
9386 }
9387
Steve Dower8fc89802015-04-12 00:26:27 -04009388 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009389 do {
9390 Py_BEGIN_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009391#ifdef __APPLE__
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009392 ret = sendfile(in_fd, out_fd, offset, &sbytes, &sf, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009393#else
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009394 ret = sendfile(in_fd, out_fd, offset, count, &sf, &sbytes, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009395#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009396 Py_END_ALLOW_THREADS
9397 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04009398 _Py_END_SUPPRESS_IPH
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009399
9400 if (sf.headers != NULL)
9401 iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
9402 if (sf.trailers != NULL)
9403 iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
9404
9405 if (ret < 0) {
9406 if ((errno == EAGAIN) || (errno == EBUSY)) {
9407 if (sbytes != 0) {
9408 // some data has been sent
9409 goto done;
9410 }
9411 else {
9412 // no data has been sent; upper application is supposed
9413 // to retry on EAGAIN or EBUSY
9414 return posix_error();
9415 }
9416 }
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009417 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009418 }
9419 goto done;
9420
9421done:
9422 #if !defined(HAVE_LARGEFILE_SUPPORT)
9423 return Py_BuildValue("l", sbytes);
9424 #else
9425 return Py_BuildValue("L", sbytes);
9426 #endif
9427
9428#else
Benjamin Peterson840ef8f2016-09-07 14:45:10 -07009429#ifdef __linux__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009430 if (offobj == Py_None) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009431 do {
9432 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009433 ret = sendfile(out_fd, in_fd, NULL, count);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009434 Py_END_ALLOW_THREADS
9435 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009436 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009437 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodola'ff1a7352011-04-19 09:47:16 +02009438 return Py_BuildValue("n", ret);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009439 }
9440#endif
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009441 off_t offset;
Larry Hastings2f936352014-08-05 14:04:04 +10009442 if (!Py_off_t_converter(offobj, &offset))
Antoine Pitroudcc20b82011-02-26 13:38:35 +00009443 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009444
9445 do {
9446 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka2b560312020-04-18 19:14:10 +03009447 ret = sendfile(out_fd, in_fd, &offset, count);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009448 Py_END_ALLOW_THREADS
9449 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009450 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009451 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009452 return Py_BuildValue("n", ret);
9453#endif
9454}
Larry Hastings2f936352014-08-05 14:04:04 +10009455#endif /* HAVE_SENDFILE */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009456
Larry Hastings2f936352014-08-05 14:04:04 +10009457
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009458#if defined(__APPLE__)
9459/*[clinic input]
9460os._fcopyfile
9461
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009462 in_fd: int
9463 out_fd: int
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009464 flags: int
9465 /
9466
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009467Efficiently copy content or metadata of 2 regular file descriptors (macOS).
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009468[clinic start generated code]*/
9469
9470static PyObject *
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009471os__fcopyfile_impl(PyObject *module, int in_fd, int out_fd, int flags)
9472/*[clinic end generated code: output=c9d1a35a992e401b input=1e34638a86948795]*/
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009473{
9474 int ret;
9475
9476 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009477 ret = fcopyfile(in_fd, out_fd, NULL, flags);
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009478 Py_END_ALLOW_THREADS
9479 if (ret < 0)
9480 return posix_error();
9481 Py_RETURN_NONE;
9482}
9483#endif
9484
9485
Larry Hastings2f936352014-08-05 14:04:04 +10009486/*[clinic input]
9487os.fstat
9488
9489 fd : int
9490
9491Perform a stat system call on the given file descriptor.
9492
9493Like stat(), but for an open file descriptor.
9494Equivalent to os.stat(fd).
9495[clinic start generated code]*/
9496
Larry Hastings2f936352014-08-05 14:04:04 +10009497static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009498os_fstat_impl(PyObject *module, int fd)
9499/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009500{
Victor Stinner8c62be82010-05-06 00:08:46 +00009501 STRUCT_STAT st;
9502 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009503 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009504
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009505 do {
9506 Py_BEGIN_ALLOW_THREADS
9507 res = FSTAT(fd, &st);
9508 Py_END_ALLOW_THREADS
9509 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner8c62be82010-05-06 00:08:46 +00009510 if (res != 0) {
Martin v. Löwis14694662006-02-03 12:54:16 +00009511#ifdef MS_WINDOWS
Victor Stinnerb024e842012-10-31 22:24:06 +01009512 return PyErr_SetFromWindowsErr(0);
Martin v. Löwis14694662006-02-03 12:54:16 +00009513#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009514 return (!async_err) ? posix_error() : NULL;
Martin v. Löwis14694662006-02-03 12:54:16 +00009515#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00009516 }
Tim Peters5aa91602002-01-30 05:46:57 +00009517
Victor Stinner4195b5c2012-02-08 23:03:19 +01009518 return _pystat_fromstructstat(&st);
Guido van Rossum687dd131993-05-17 08:34:16 +00009519}
9520
Larry Hastings2f936352014-08-05 14:04:04 +10009521
9522/*[clinic input]
9523os.isatty -> bool
9524 fd: int
9525 /
9526
9527Return True if the fd is connected to a terminal.
9528
9529Return True if the file descriptor is an open file descriptor
9530connected to the slave end of a terminal.
9531[clinic start generated code]*/
9532
Larry Hastings2f936352014-08-05 14:04:04 +10009533static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009534os_isatty_impl(PyObject *module, int fd)
9535/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009536{
Steve Dower8fc89802015-04-12 00:26:27 -04009537 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -04009538 _Py_BEGIN_SUPPRESS_IPH
9539 return_value = isatty(fd);
9540 _Py_END_SUPPRESS_IPH
9541 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +10009542}
9543
9544
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009545#ifdef HAVE_PIPE
Larry Hastings2f936352014-08-05 14:04:04 +10009546/*[clinic input]
9547os.pipe
9548
9549Create a pipe.
9550
9551Returns a tuple of two file descriptors:
9552 (read_fd, write_fd)
9553[clinic start generated code]*/
9554
Larry Hastings2f936352014-08-05 14:04:04 +10009555static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009556os_pipe_impl(PyObject *module)
9557/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00009558{
Victor Stinner8c62be82010-05-06 00:08:46 +00009559 int fds[2];
Victor Stinnerdaf45552013-08-28 00:53:59 +02009560#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00009561 HANDLE read, write;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009562 SECURITY_ATTRIBUTES attr;
Victor Stinner8c62be82010-05-06 00:08:46 +00009563 BOOL ok;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009564#else
9565 int res;
9566#endif
9567
9568#ifdef MS_WINDOWS
9569 attr.nLength = sizeof(attr);
9570 attr.lpSecurityDescriptor = NULL;
9571 attr.bInheritHandle = FALSE;
9572
9573 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08009574 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009575 ok = CreatePipe(&read, &write, &attr, 0);
9576 if (ok) {
Benjamin Petersonca470632016-09-06 13:47:26 -07009577 fds[0] = _open_osfhandle((intptr_t)read, _O_RDONLY);
9578 fds[1] = _open_osfhandle((intptr_t)write, _O_WRONLY);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009579 if (fds[0] == -1 || fds[1] == -1) {
9580 CloseHandle(read);
9581 CloseHandle(write);
9582 ok = 0;
9583 }
9584 }
Steve Dowerc3630612016-11-19 18:41:16 -08009585 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009586 Py_END_ALLOW_THREADS
9587
Victor Stinner8c62be82010-05-06 00:08:46 +00009588 if (!ok)
Victor Stinnerb024e842012-10-31 22:24:06 +01009589 return PyErr_SetFromWindowsErr(0);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009590#else
9591
9592#ifdef HAVE_PIPE2
9593 Py_BEGIN_ALLOW_THREADS
9594 res = pipe2(fds, O_CLOEXEC);
9595 Py_END_ALLOW_THREADS
9596
9597 if (res != 0 && errno == ENOSYS)
9598 {
9599#endif
9600 Py_BEGIN_ALLOW_THREADS
9601 res = pipe(fds);
9602 Py_END_ALLOW_THREADS
9603
9604 if (res == 0) {
9605 if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
9606 close(fds[0]);
9607 close(fds[1]);
9608 return NULL;
9609 }
9610 if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
9611 close(fds[0]);
9612 close(fds[1]);
9613 return NULL;
9614 }
9615 }
9616#ifdef HAVE_PIPE2
9617 }
9618#endif
9619
9620 if (res != 0)
9621 return PyErr_SetFromErrno(PyExc_OSError);
9622#endif /* !MS_WINDOWS */
9623 return Py_BuildValue("(ii)", fds[0], fds[1]);
Guido van Rossum687dd131993-05-17 08:34:16 +00009624}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009625#endif /* HAVE_PIPE */
9626
Larry Hastings2f936352014-08-05 14:04:04 +10009627
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009628#ifdef HAVE_PIPE2
Larry Hastings2f936352014-08-05 14:04:04 +10009629/*[clinic input]
9630os.pipe2
9631
9632 flags: int
9633 /
9634
9635Create a pipe with flags set atomically.
9636
9637Returns a tuple of two file descriptors:
9638 (read_fd, write_fd)
9639
9640flags can be constructed by ORing together one or more of these values:
9641O_NONBLOCK, O_CLOEXEC.
9642[clinic start generated code]*/
9643
Larry Hastings2f936352014-08-05 14:04:04 +10009644static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009645os_pipe2_impl(PyObject *module, int flags)
9646/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009647{
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009648 int fds[2];
9649 int res;
9650
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009651 res = pipe2(fds, flags);
9652 if (res != 0)
9653 return posix_error();
9654 return Py_BuildValue("(ii)", fds[0], fds[1]);
9655}
9656#endif /* HAVE_PIPE2 */
9657
Larry Hastings2f936352014-08-05 14:04:04 +10009658
Ross Lagerwall7807c352011-03-17 20:20:30 +02009659#ifdef HAVE_WRITEV
Larry Hastings2f936352014-08-05 14:04:04 +10009660/*[clinic input]
9661os.writev -> Py_ssize_t
9662 fd: int
9663 buffers: object
9664 /
9665
9666Iterate over buffers, and write the contents of each to a file descriptor.
9667
9668Returns the total number of bytes written.
9669buffers must be a sequence of bytes-like objects.
9670[clinic start generated code]*/
9671
Larry Hastings2f936352014-08-05 14:04:04 +10009672static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009673os_writev_impl(PyObject *module, int fd, PyObject *buffers)
9674/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009675{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009676 Py_ssize_t cnt;
Larry Hastings2f936352014-08-05 14:04:04 +10009677 Py_ssize_t result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009678 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009679 struct iovec *iov;
9680 Py_buffer *buf;
Larry Hastings2f936352014-08-05 14:04:04 +10009681
9682 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009683 PyErr_SetString(PyExc_TypeError,
9684 "writev() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009685 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009686 }
Larry Hastings2f936352014-08-05 14:04:04 +10009687 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009688 if (cnt < 0)
9689 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009690
Larry Hastings2f936352014-08-05 14:04:04 +10009691 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9692 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009693 }
9694
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009695 do {
9696 Py_BEGIN_ALLOW_THREADS
9697 result = writev(fd, iov, cnt);
9698 Py_END_ALLOW_THREADS
9699 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009700
9701 iov_cleanup(iov, buf, cnt);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009702 if (result < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009703 posix_error();
Victor Stinner57ddf782014-01-08 15:21:28 +01009704
Georg Brandl306336b2012-06-24 12:55:33 +02009705 return result;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009706}
Larry Hastings2f936352014-08-05 14:04:04 +10009707#endif /* HAVE_WRITEV */
9708
9709
9710#ifdef HAVE_PWRITE
9711/*[clinic input]
9712os.pwrite -> Py_ssize_t
9713
9714 fd: int
9715 buffer: Py_buffer
9716 offset: Py_off_t
9717 /
9718
9719Write bytes to a file descriptor starting at a particular offset.
9720
9721Write buffer to fd, starting at offset bytes from the beginning of
9722the file. Returns the number of bytes writte. Does not change the
9723current file offset.
9724[clinic start generated code]*/
9725
Larry Hastings2f936352014-08-05 14:04:04 +10009726static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009727os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
9728/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009729{
9730 Py_ssize_t size;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009731 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009732
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009733 do {
9734 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009735 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009736 size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009737 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009738 Py_END_ALLOW_THREADS
9739 } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +10009740
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009741 if (size < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009742 posix_error();
9743 return size;
9744}
9745#endif /* HAVE_PWRITE */
9746
Pablo Galindo4defba32018-01-27 16:16:37 +00009747#if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
9748/*[clinic input]
9749os.pwritev -> Py_ssize_t
9750
9751 fd: int
9752 buffers: object
9753 offset: Py_off_t
9754 flags: int = 0
9755 /
9756
9757Writes the contents of bytes-like objects to a file descriptor at a given offset.
9758
9759Combines the functionality of writev() and pwrite(). All buffers must be a sequence
9760of bytes-like objects. Buffers are processed in array order. Entire contents of first
9761buffer is written before proceeding to second, and so on. The operating system may
9762set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
9763This function writes the contents of each object to the file descriptor and returns
9764the total number of bytes written.
9765
9766The flags argument contains a bitwise OR of zero or more of the following flags:
9767
9768- RWF_DSYNC
9769- RWF_SYNC
9770
9771Using non-zero flags requires Linux 4.7 or newer.
9772[clinic start generated code]*/
9773
9774static Py_ssize_t
9775os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9776 int flags)
9777/*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=803dc5ddbf0cfd3b]*/
9778{
9779 Py_ssize_t cnt;
9780 Py_ssize_t result;
9781 int async_err = 0;
9782 struct iovec *iov;
9783 Py_buffer *buf;
9784
9785 if (!PySequence_Check(buffers)) {
9786 PyErr_SetString(PyExc_TypeError,
9787 "pwritev() arg 2 must be a sequence");
9788 return -1;
9789 }
9790
9791 cnt = PySequence_Size(buffers);
9792 if (cnt < 0) {
9793 return -1;
9794 }
9795
9796#ifndef HAVE_PWRITEV2
9797 if(flags != 0) {
9798 argument_unavailable_error("pwritev2", "flags");
9799 return -1;
9800 }
9801#endif
9802
9803 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9804 return -1;
9805 }
9806#ifdef HAVE_PWRITEV2
9807 do {
9808 Py_BEGIN_ALLOW_THREADS
9809 _Py_BEGIN_SUPPRESS_IPH
9810 result = pwritev2(fd, iov, cnt, offset, flags);
9811 _Py_END_SUPPRESS_IPH
9812 Py_END_ALLOW_THREADS
9813 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9814#else
9815 do {
9816 Py_BEGIN_ALLOW_THREADS
9817 _Py_BEGIN_SUPPRESS_IPH
9818 result = pwritev(fd, iov, cnt, offset);
9819 _Py_END_SUPPRESS_IPH
9820 Py_END_ALLOW_THREADS
9821 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9822#endif
9823
9824 iov_cleanup(iov, buf, cnt);
9825 if (result < 0) {
9826 if (!async_err) {
9827 posix_error();
9828 }
9829 return -1;
9830 }
9831
9832 return result;
9833}
9834#endif /* HAVE_PWRITEV */
9835
Pablo Galindoaac4d032019-05-31 19:39:47 +01009836#ifdef HAVE_COPY_FILE_RANGE
9837/*[clinic input]
9838
9839os.copy_file_range
9840 src: int
9841 Source file descriptor.
9842 dst: int
9843 Destination file descriptor.
9844 count: Py_ssize_t
9845 Number of bytes to copy.
9846 offset_src: object = None
9847 Starting offset in src.
9848 offset_dst: object = None
9849 Starting offset in dst.
9850
9851Copy count bytes from one file descriptor to another.
9852
9853If offset_src is None, then src is read from the current position;
9854respectively for offset_dst.
9855[clinic start generated code]*/
9856
9857static PyObject *
9858os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
9859 PyObject *offset_src, PyObject *offset_dst)
9860/*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
9861{
9862 off_t offset_src_val, offset_dst_val;
9863 off_t *p_offset_src = NULL;
9864 off_t *p_offset_dst = NULL;
9865 Py_ssize_t ret;
9866 int async_err = 0;
9867 /* The flags argument is provided to allow
9868 * for future extensions and currently must be to 0. */
9869 int flags = 0;
Pablo Galindo4defba32018-01-27 16:16:37 +00009870
9871
Pablo Galindoaac4d032019-05-31 19:39:47 +01009872 if (count < 0) {
9873 PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
9874 return NULL;
9875 }
9876
9877 if (offset_src != Py_None) {
9878 if (!Py_off_t_converter(offset_src, &offset_src_val)) {
9879 return NULL;
9880 }
9881 p_offset_src = &offset_src_val;
9882 }
9883
9884 if (offset_dst != Py_None) {
9885 if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
9886 return NULL;
9887 }
9888 p_offset_dst = &offset_dst_val;
9889 }
9890
9891 do {
9892 Py_BEGIN_ALLOW_THREADS
9893 ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
9894 Py_END_ALLOW_THREADS
9895 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9896
9897 if (ret < 0) {
9898 return (!async_err) ? posix_error() : NULL;
9899 }
9900
9901 return PyLong_FromSsize_t(ret);
9902}
9903#endif /* HAVE_COPY_FILE_RANGE*/
Larry Hastings2f936352014-08-05 14:04:04 +10009904
9905#ifdef HAVE_MKFIFO
9906/*[clinic input]
9907os.mkfifo
9908
9909 path: path_t
9910 mode: int=0o666
9911 *
9912 dir_fd: dir_fd(requires='mkfifoat')=None
9913
9914Create a "fifo" (a POSIX named pipe).
9915
9916If dir_fd is not None, it should be a file descriptor open to a directory,
9917 and path should be relative; path will then be relative to that directory.
9918dir_fd may not be implemented on your platform.
9919 If it is unavailable, using it will raise a NotImplementedError.
9920[clinic start generated code]*/
9921
Larry Hastings2f936352014-08-05 14:04:04 +10009922static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009923os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
9924/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009925{
9926 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009927 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009928
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009929 do {
9930 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009931#ifdef HAVE_MKFIFOAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009932 if (dir_fd != DEFAULT_DIR_FD)
9933 result = mkfifoat(dir_fd, path->narrow, mode);
9934 else
Ross Lagerwall7807c352011-03-17 20:20:30 +02009935#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009936 result = mkfifo(path->narrow, mode);
9937 Py_END_ALLOW_THREADS
9938 } while (result != 0 && errno == EINTR &&
9939 !(async_err = PyErr_CheckSignals()));
9940 if (result != 0)
9941 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009942
9943 Py_RETURN_NONE;
9944}
9945#endif /* HAVE_MKFIFO */
9946
9947
9948#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
9949/*[clinic input]
9950os.mknod
9951
9952 path: path_t
9953 mode: int=0o600
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009954 device: dev_t=0
Larry Hastings2f936352014-08-05 14:04:04 +10009955 *
9956 dir_fd: dir_fd(requires='mknodat')=None
9957
9958Create a node in the file system.
9959
9960Create a node in the file system (file, device special file or named pipe)
9961at path. mode specifies both the permissions to use and the
9962type of node to be created, being combined (bitwise OR) with one of
9963S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
9964device defines the newly created device special file (probably using
9965os.makedev()). Otherwise device is ignored.
9966
9967If dir_fd is not None, it should be a file descriptor open to a directory,
9968 and path should be relative; path will then be relative to that directory.
9969dir_fd may not be implemented on your platform.
9970 If it is unavailable, using it will raise a NotImplementedError.
9971[clinic start generated code]*/
9972
Larry Hastings2f936352014-08-05 14:04:04 +10009973static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009974os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
Larry Hastings89964c42015-04-14 18:07:59 -04009975 int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009976/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009977{
9978 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009979 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009980
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009981 do {
9982 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009983#ifdef HAVE_MKNODAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009984 if (dir_fd != DEFAULT_DIR_FD)
9985 result = mknodat(dir_fd, path->narrow, mode, device);
9986 else
Larry Hastings2f936352014-08-05 14:04:04 +10009987#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009988 result = mknod(path->narrow, mode, device);
9989 Py_END_ALLOW_THREADS
9990 } while (result != 0 && errno == EINTR &&
9991 !(async_err = PyErr_CheckSignals()));
9992 if (result != 0)
9993 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009994
9995 Py_RETURN_NONE;
9996}
9997#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
9998
9999
10000#ifdef HAVE_DEVICE_MACROS
10001/*[clinic input]
10002os.major -> unsigned_int
10003
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +020010004 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +100010005 /
10006
10007Extracts a device major number from a raw device number.
10008[clinic start generated code]*/
10009
Larry Hastings2f936352014-08-05 14:04:04 +100010010static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010011os_major_impl(PyObject *module, dev_t device)
10012/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010013{
10014 return major(device);
10015}
10016
10017
10018/*[clinic input]
10019os.minor -> unsigned_int
10020
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +020010021 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +100010022 /
10023
10024Extracts a device minor number from a raw device number.
10025[clinic start generated code]*/
10026
Larry Hastings2f936352014-08-05 14:04:04 +100010027static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010028os_minor_impl(PyObject *module, dev_t device)
10029/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010030{
10031 return minor(device);
10032}
10033
10034
10035/*[clinic input]
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +020010036os.makedev -> dev_t
Larry Hastings2f936352014-08-05 14:04:04 +100010037
10038 major: int
10039 minor: int
10040 /
10041
10042Composes a raw device number from the major and minor device numbers.
10043[clinic start generated code]*/
10044
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +020010045static dev_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010046os_makedev_impl(PyObject *module, int major, int minor)
10047/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010048{
10049 return makedev(major, minor);
10050}
10051#endif /* HAVE_DEVICE_MACROS */
10052
10053
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010054#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010055/*[clinic input]
10056os.ftruncate
10057
10058 fd: int
10059 length: Py_off_t
10060 /
10061
10062Truncate a file, specified by file descriptor, to a specific length.
10063[clinic start generated code]*/
10064
Larry Hastings2f936352014-08-05 14:04:04 +100010065static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010066os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
10067/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010068{
10069 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010070 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +100010071
Steve Dowerb82e17e2019-05-23 08:45:22 -070010072 if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
10073 return NULL;
10074 }
10075
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010076 do {
10077 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -040010078 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010079#ifdef MS_WINDOWS
10080 result = _chsize_s(fd, length);
10081#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010082 result = ftruncate(fd, length);
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010083#endif
Steve Dowera1c7e722015-04-12 00:26:43 -040010084 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010085 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 Py_RETURN_NONE;
10091}
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010092#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +100010093
10094
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010095#if defined HAVE_TRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010096/*[clinic input]
10097os.truncate
10098 path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
10099 length: Py_off_t
10100
10101Truncate a file, specified by path, to a specific length.
10102
10103On some platforms, path may also be specified as an open file descriptor.
10104 If this functionality is unavailable, using it raises an exception.
10105[clinic start generated code]*/
10106
Larry Hastings2f936352014-08-05 14:04:04 +100010107static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010108os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
10109/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010110{
10111 int result;
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010112#ifdef MS_WINDOWS
10113 int fd;
10114#endif
10115
10116 if (path->fd != -1)
10117 return os_ftruncate_impl(module, path->fd, length);
Larry Hastings2f936352014-08-05 14:04:04 +100010118
Steve Dowerb82e17e2019-05-23 08:45:22 -070010119 if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
10120 return NULL;
10121 }
10122
Larry Hastings2f936352014-08-05 14:04:04 +100010123 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -040010124 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010125#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -070010126 fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
Victor Stinnercc0bbbc2015-04-25 00:21:52 +020010127 if (fd < 0)
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010128 result = -1;
10129 else {
10130 result = _chsize_s(fd, length);
10131 close(fd);
10132 if (result < 0)
10133 errno = result;
10134 }
10135#else
10136 result = truncate(path->narrow, length);
Larry Hastings2f936352014-08-05 14:04:04 +100010137#endif
Steve Dowera1c7e722015-04-12 00:26:43 -040010138 _Py_END_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +100010139 Py_END_ALLOW_THREADS
10140 if (result < 0)
Alexey Izbyshev83460312018-10-20 03:28:22 +030010141 return posix_path_error(path);
Larry Hastings2f936352014-08-05 14:04:04 +100010142
10143 Py_RETURN_NONE;
10144}
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010145#endif /* HAVE_TRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +100010146
Ross Lagerwall7807c352011-03-17 20:20:30 +020010147
Victor Stinnerd6b17692014-09-30 12:20:05 +020010148/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
10149 and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
10150 defined, which is the case in Python on AIX. AIX bug report:
10151 http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
10152#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
10153# define POSIX_FADVISE_AIX_BUG
10154#endif
10155
Victor Stinnerec39e262014-09-30 12:35:58 +020010156
Victor Stinnerd6b17692014-09-30 12:20:05 +020010157#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +100010158/*[clinic input]
10159os.posix_fallocate
10160
10161 fd: int
10162 offset: Py_off_t
10163 length: Py_off_t
10164 /
10165
10166Ensure a file has allocated at least a particular number of bytes on disk.
10167
10168Ensure that the file specified by fd encompasses a range of bytes
10169starting at offset bytes from the beginning and continuing for length bytes.
10170[clinic start generated code]*/
10171
Larry Hastings2f936352014-08-05 14:04:04 +100010172static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010173os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -040010174 Py_off_t length)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010175/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010176{
10177 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010178 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010179
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010180 do {
10181 Py_BEGIN_ALLOW_THREADS
10182 result = posix_fallocate(fd, offset, length);
10183 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010184 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10185
10186 if (result == 0)
10187 Py_RETURN_NONE;
10188
10189 if (async_err)
10190 return NULL;
10191
10192 errno = result;
10193 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010194}
Victor Stinnerec39e262014-09-30 12:35:58 +020010195#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
Larry Hastings2f936352014-08-05 14:04:04 +100010196
Ross Lagerwall7807c352011-03-17 20:20:30 +020010197
Victor Stinnerd6b17692014-09-30 12:20:05 +020010198#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +100010199/*[clinic input]
10200os.posix_fadvise
10201
10202 fd: int
10203 offset: Py_off_t
10204 length: Py_off_t
10205 advice: int
10206 /
10207
10208Announce an intention to access data in a specific pattern.
10209
10210Announce an intention to access data in a specific pattern, thus allowing
10211the kernel to make optimizations.
10212The advice applies to the region of the file specified by fd starting at
10213offset and continuing for length bytes.
10214advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
10215POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
10216POSIX_FADV_DONTNEED.
10217[clinic start generated code]*/
10218
Larry Hastings2f936352014-08-05 14:04:04 +100010219static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010220os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -040010221 Py_off_t length, int advice)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010222/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010223{
10224 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010225 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010226
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010227 do {
10228 Py_BEGIN_ALLOW_THREADS
10229 result = posix_fadvise(fd, offset, length, advice);
10230 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010231 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10232
10233 if (result == 0)
10234 Py_RETURN_NONE;
10235
10236 if (async_err)
10237 return NULL;
10238
10239 errno = result;
10240 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010241}
Victor Stinnerec39e262014-09-30 12:35:58 +020010242#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
Ross Lagerwall7807c352011-03-17 20:20:30 +020010243
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000010244
Thomas Hellerf78f12a2007-11-08 19:33:05 +000010245#ifdef MS_WINDOWS
Victor Stinner161e7b32020-01-24 11:53:44 +010010246static PyObject*
10247win32_putenv(PyObject *name, PyObject *value)
10248{
10249 /* Search from index 1 because on Windows starting '=' is allowed for
10250 defining hidden environment variables. */
10251 if (PyUnicode_GET_LENGTH(name) == 0 ||
10252 PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
10253 {
10254 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10255 return NULL;
10256 }
10257 PyObject *unicode;
10258 if (value != NULL) {
10259 unicode = PyUnicode_FromFormat("%U=%U", name, value);
10260 }
10261 else {
10262 unicode = PyUnicode_FromFormat("%U=", name);
10263 }
10264 if (unicode == NULL) {
10265 return NULL;
10266 }
10267
10268 Py_ssize_t size;
10269 /* PyUnicode_AsWideCharString() rejects embedded null characters */
10270 wchar_t *env = PyUnicode_AsWideCharString(unicode, &size);
10271 Py_DECREF(unicode);
10272
10273 if (env == NULL) {
10274 return NULL;
10275 }
10276 if (size > _MAX_ENV) {
10277 PyErr_Format(PyExc_ValueError,
10278 "the environment variable is longer than %u characters",
10279 _MAX_ENV);
10280 PyMem_Free(env);
10281 return NULL;
10282 }
10283
10284 /* _wputenv() and SetEnvironmentVariableW() update the environment in the
10285 Process Environment Block (PEB). _wputenv() also updates CRT 'environ'
10286 and '_wenviron' variables, whereas SetEnvironmentVariableW() does not.
10287
10288 Prefer _wputenv() to be compatible with C libraries using CRT
10289 variables and CRT functions using these variables (ex: getenv()). */
10290 int err = _wputenv(env);
10291 PyMem_Free(env);
10292
10293 if (err) {
10294 posix_error();
10295 return NULL;
10296 }
10297
10298 Py_RETURN_NONE;
10299}
10300#endif
10301
10302
10303#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010304/*[clinic input]
10305os.putenv
10306
10307 name: unicode
10308 value: unicode
10309 /
10310
10311Change or add an environment variable.
10312[clinic start generated code]*/
10313
Larry Hastings2f936352014-08-05 14:04:04 +100010314static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010315os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10316/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010317{
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010318 if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
10319 return NULL;
10320 }
Victor Stinner161e7b32020-01-24 11:53:44 +010010321 return win32_putenv(name, value);
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010322}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010323#else
Larry Hastings2f936352014-08-05 14:04:04 +100010324/*[clinic input]
10325os.putenv
Guido van Rossumb6a47161997-09-15 22:54:34 +000010326
Larry Hastings2f936352014-08-05 14:04:04 +100010327 name: FSConverter
10328 value: FSConverter
10329 /
10330
10331Change or add an environment variable.
10332[clinic start generated code]*/
10333
Larry Hastings2f936352014-08-05 14:04:04 +100010334static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010335os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10336/*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010337{
Serhiy Storchaka77703942017-06-25 07:33:01 +030010338 const char *name_string = PyBytes_AS_STRING(name);
10339 const char *value_string = PyBytes_AS_STRING(value);
Larry Hastings2f936352014-08-05 14:04:04 +100010340
Serhiy Storchaka77703942017-06-25 07:33:01 +030010341 if (strchr(name_string, '=') != NULL) {
10342 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10343 return NULL;
10344 }
Victor Stinnerb477d192020-01-22 22:48:16 +010010345
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010346 if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
10347 return NULL;
10348 }
10349
Victor Stinnerb477d192020-01-22 22:48:16 +010010350 if (setenv(name_string, value_string, 1)) {
10351 return posix_error();
10352 }
Larry Hastings2f936352014-08-05 14:04:04 +100010353 Py_RETURN_NONE;
10354}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010355#endif /* !defined(MS_WINDOWS) */
Larry Hastings2f936352014-08-05 14:04:04 +100010356
10357
Victor Stinner161e7b32020-01-24 11:53:44 +010010358#ifdef MS_WINDOWS
10359/*[clinic input]
10360os.unsetenv
10361 name: unicode
10362 /
10363
10364Delete an environment variable.
10365[clinic start generated code]*/
10366
10367static PyObject *
10368os_unsetenv_impl(PyObject *module, PyObject *name)
10369/*[clinic end generated code: output=54c4137ab1834f02 input=4d6a1747cc526d2f]*/
10370{
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010371 if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
10372 return NULL;
10373 }
Victor Stinner161e7b32020-01-24 11:53:44 +010010374 return win32_putenv(name, NULL);
10375}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010376#else
Larry Hastings2f936352014-08-05 14:04:04 +100010377/*[clinic input]
10378os.unsetenv
10379 name: FSConverter
10380 /
10381
10382Delete an environment variable.
10383[clinic start generated code]*/
10384
Larry Hastings2f936352014-08-05 14:04:04 +100010385static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010386os_unsetenv_impl(PyObject *module, PyObject *name)
10387/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010388{
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010389 if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
10390 return NULL;
10391 }
Victor Stinner984890f2011-11-24 13:53:38 +010010392#ifdef HAVE_BROKEN_UNSETENV
10393 unsetenv(PyBytes_AS_STRING(name));
10394#else
Victor Stinner161e7b32020-01-24 11:53:44 +010010395 int err = unsetenv(PyBytes_AS_STRING(name));
10396 if (err) {
Victor Stinner60b385e2011-11-22 22:01:28 +010010397 return posix_error();
Victor Stinner161e7b32020-01-24 11:53:44 +010010398 }
Victor Stinner984890f2011-11-24 13:53:38 +010010399#endif
Guido van Rossumc524d952001-10-19 01:31:59 +000010400
Victor Stinner84ae1182010-05-06 22:05:07 +000010401 Py_RETURN_NONE;
Guido van Rossumc524d952001-10-19 01:31:59 +000010402}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010403#endif /* !MS_WINDOWS */
Guido van Rossumc524d952001-10-19 01:31:59 +000010404
Larry Hastings2f936352014-08-05 14:04:04 +100010405
10406/*[clinic input]
10407os.strerror
10408
10409 code: int
10410 /
10411
10412Translate an error code to a message string.
10413[clinic start generated code]*/
10414
Larry Hastings2f936352014-08-05 14:04:04 +100010415static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010416os_strerror_impl(PyObject *module, int code)
10417/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010418{
10419 char *message = strerror(code);
Victor Stinner8c62be82010-05-06 00:08:46 +000010420 if (message == NULL) {
10421 PyErr_SetString(PyExc_ValueError,
10422 "strerror() argument out of range");
10423 return NULL;
10424 }
Victor Stinner1b579672011-12-17 05:47:23 +010010425 return PyUnicode_DecodeLocale(message, "surrogateescape");
Guido van Rossumb6a47161997-09-15 22:54:34 +000010426}
Guido van Rossumb6a47161997-09-15 22:54:34 +000010427
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010428
Guido van Rossumc9641791998-08-04 15:26:23 +000010429#ifdef HAVE_SYS_WAIT_H
Fred Drake106c1a02002-04-23 15:58:02 +000010430#ifdef WCOREDUMP
Larry Hastings2f936352014-08-05 14:04:04 +100010431/*[clinic input]
10432os.WCOREDUMP -> bool
10433
10434 status: int
10435 /
10436
10437Return True if the process returning status was dumped to a core file.
10438[clinic start generated code]*/
10439
Larry Hastings2f936352014-08-05 14:04:04 +100010440static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010441os_WCOREDUMP_impl(PyObject *module, int status)
10442/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010443{
10444 WAIT_TYPE wait_status;
10445 WAIT_STATUS_INT(wait_status) = status;
10446 return WCOREDUMP(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010447}
10448#endif /* WCOREDUMP */
10449
Larry Hastings2f936352014-08-05 14:04:04 +100010450
Fred Drake106c1a02002-04-23 15:58:02 +000010451#ifdef WIFCONTINUED
Larry Hastings2f936352014-08-05 14:04:04 +100010452/*[clinic input]
10453os.WIFCONTINUED -> bool
10454
10455 status: int
10456
10457Return True if a particular process was continued from a job control stop.
10458
10459Return True if the process returning status was continued from a
10460job control stop.
10461[clinic start generated code]*/
10462
Larry Hastings2f936352014-08-05 14:04:04 +100010463static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010464os_WIFCONTINUED_impl(PyObject *module, int status)
10465/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010466{
10467 WAIT_TYPE wait_status;
10468 WAIT_STATUS_INT(wait_status) = status;
10469 return WIFCONTINUED(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010470}
10471#endif /* WIFCONTINUED */
10472
Larry Hastings2f936352014-08-05 14:04:04 +100010473
Guido van Rossumc9641791998-08-04 15:26:23 +000010474#ifdef WIFSTOPPED
Larry Hastings2f936352014-08-05 14:04:04 +100010475/*[clinic input]
10476os.WIFSTOPPED -> bool
10477
10478 status: int
10479
10480Return True if the process returning status was stopped.
10481[clinic start generated code]*/
10482
Larry Hastings2f936352014-08-05 14:04:04 +100010483static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010484os_WIFSTOPPED_impl(PyObject *module, int status)
10485/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010486{
10487 WAIT_TYPE wait_status;
10488 WAIT_STATUS_INT(wait_status) = status;
10489 return WIFSTOPPED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010490}
10491#endif /* WIFSTOPPED */
10492
Larry Hastings2f936352014-08-05 14:04:04 +100010493
Guido van Rossumc9641791998-08-04 15:26:23 +000010494#ifdef WIFSIGNALED
Larry Hastings2f936352014-08-05 14:04:04 +100010495/*[clinic input]
10496os.WIFSIGNALED -> bool
10497
10498 status: int
10499
10500Return True if the process returning status was terminated by a signal.
10501[clinic start generated code]*/
10502
Larry Hastings2f936352014-08-05 14:04:04 +100010503static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010504os_WIFSIGNALED_impl(PyObject *module, int status)
10505/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010506{
10507 WAIT_TYPE wait_status;
10508 WAIT_STATUS_INT(wait_status) = status;
10509 return WIFSIGNALED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010510}
10511#endif /* WIFSIGNALED */
10512
Larry Hastings2f936352014-08-05 14:04:04 +100010513
Guido van Rossumc9641791998-08-04 15:26:23 +000010514#ifdef WIFEXITED
Larry Hastings2f936352014-08-05 14:04:04 +100010515/*[clinic input]
10516os.WIFEXITED -> bool
10517
10518 status: int
10519
10520Return True if the process returning status exited via the exit() system call.
10521[clinic start generated code]*/
10522
Larry Hastings2f936352014-08-05 14:04:04 +100010523static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010524os_WIFEXITED_impl(PyObject *module, int status)
10525/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010526{
10527 WAIT_TYPE wait_status;
10528 WAIT_STATUS_INT(wait_status) = status;
10529 return WIFEXITED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010530}
10531#endif /* WIFEXITED */
10532
Larry Hastings2f936352014-08-05 14:04:04 +100010533
Guido van Rossum54ecc3d1999-01-27 17:53:11 +000010534#ifdef WEXITSTATUS
Larry Hastings2f936352014-08-05 14:04:04 +100010535/*[clinic input]
10536os.WEXITSTATUS -> int
10537
10538 status: int
10539
10540Return the process return code from status.
10541[clinic start generated code]*/
10542
Larry Hastings2f936352014-08-05 14:04:04 +100010543static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010544os_WEXITSTATUS_impl(PyObject *module, int status)
10545/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010546{
10547 WAIT_TYPE wait_status;
10548 WAIT_STATUS_INT(wait_status) = status;
10549 return WEXITSTATUS(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010550}
10551#endif /* WEXITSTATUS */
10552
Larry Hastings2f936352014-08-05 14:04:04 +100010553
Guido van Rossumc9641791998-08-04 15:26:23 +000010554#ifdef WTERMSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010555/*[clinic input]
10556os.WTERMSIG -> int
10557
10558 status: int
10559
10560Return the signal that terminated the process that provided the status value.
10561[clinic start generated code]*/
10562
Larry Hastings2f936352014-08-05 14:04:04 +100010563static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010564os_WTERMSIG_impl(PyObject *module, int status)
10565/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010566{
10567 WAIT_TYPE wait_status;
10568 WAIT_STATUS_INT(wait_status) = status;
10569 return WTERMSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010570}
10571#endif /* WTERMSIG */
10572
Larry Hastings2f936352014-08-05 14:04:04 +100010573
Guido van Rossumc9641791998-08-04 15:26:23 +000010574#ifdef WSTOPSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010575/*[clinic input]
10576os.WSTOPSIG -> int
10577
10578 status: int
10579
10580Return the signal that stopped the process that provided the status value.
10581[clinic start generated code]*/
10582
Larry Hastings2f936352014-08-05 14:04:04 +100010583static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010584os_WSTOPSIG_impl(PyObject *module, int status)
10585/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010586{
10587 WAIT_TYPE wait_status;
10588 WAIT_STATUS_INT(wait_status) = status;
10589 return WSTOPSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010590}
10591#endif /* WSTOPSIG */
Guido van Rossumc9641791998-08-04 15:26:23 +000010592#endif /* HAVE_SYS_WAIT_H */
10593
10594
Thomas Wouters477c8d52006-05-27 19:21:47 +000010595#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossumd5753e11999-10-19 13:29:23 +000010596#ifdef _SCO_DS
10597/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
10598 needed definitions in sys/statvfs.h */
10599#define _SVID3
10600#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000010601#include <sys/statvfs.h>
10602
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010603static PyObject*
10604_pystatvfs_fromstructstatvfs(struct statvfs st) {
Eddie Elizondob3966632019-11-05 07:16:14 -080010605 PyObject *StatVFSResultType = _posixstate_global->StatVFSResultType;
10606 PyObject *v = PyStructSequence_New((PyTypeObject *)StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000010607 if (v == NULL)
10608 return NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010609
10610#if !defined(HAVE_LARGEFILE_SUPPORT)
Victor Stinner8c62be82010-05-06 00:08:46 +000010611 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10612 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10613 PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
10614 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
10615 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
10616 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
10617 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
10618 PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
10619 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10620 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010621#else
Victor Stinner8c62be82010-05-06 00:08:46 +000010622 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10623 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10624 PyStructSequence_SET_ITEM(v, 2,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010625 PyLong_FromLongLong((long long) st.f_blocks));
Victor Stinner8c62be82010-05-06 00:08:46 +000010626 PyStructSequence_SET_ITEM(v, 3,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010627 PyLong_FromLongLong((long long) st.f_bfree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010628 PyStructSequence_SET_ITEM(v, 4,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010629 PyLong_FromLongLong((long long) st.f_bavail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010630 PyStructSequence_SET_ITEM(v, 5,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010631 PyLong_FromLongLong((long long) st.f_files));
Victor Stinner8c62be82010-05-06 00:08:46 +000010632 PyStructSequence_SET_ITEM(v, 6,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010633 PyLong_FromLongLong((long long) st.f_ffree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010634 PyStructSequence_SET_ITEM(v, 7,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010635 PyLong_FromLongLong((long long) st.f_favail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010636 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10637 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010638#endif
Michael Felt502d5512018-01-05 13:01:58 +010010639/* The _ALL_SOURCE feature test macro defines f_fsid as a structure
10640 * (issue #32390). */
10641#if defined(_AIX) && defined(_ALL_SOURCE)
10642 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
10643#else
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +010010644 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid));
Michael Felt502d5512018-01-05 13:01:58 +010010645#endif
Victor Stinnerf0a7bac2013-10-30 18:55:24 +010010646 if (PyErr_Occurred()) {
10647 Py_DECREF(v);
10648 return NULL;
10649 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010650
Victor Stinner8c62be82010-05-06 00:08:46 +000010651 return v;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010652}
10653
Larry Hastings2f936352014-08-05 14:04:04 +100010654
10655/*[clinic input]
10656os.fstatvfs
10657 fd: int
10658 /
10659
10660Perform an fstatvfs system call on the given fd.
10661
10662Equivalent to statvfs(fd).
10663[clinic start generated code]*/
10664
Larry Hastings2f936352014-08-05 14:04:04 +100010665static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010666os_fstatvfs_impl(PyObject *module, int fd)
10667/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010668{
10669 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010670 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010671 struct statvfs st;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010672
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010673 do {
10674 Py_BEGIN_ALLOW_THREADS
10675 result = fstatvfs(fd, &st);
10676 Py_END_ALLOW_THREADS
10677 } while (result != 0 && errno == EINTR &&
10678 !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +100010679 if (result != 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010680 return (!async_err) ? posix_error() : NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010681
Victor Stinner8c62be82010-05-06 00:08:46 +000010682 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010683}
Larry Hastings2f936352014-08-05 14:04:04 +100010684#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
Guido van Rossum94f6f721999-01-06 18:42:14 +000010685
10686
Thomas Wouters477c8d52006-05-27 19:21:47 +000010687#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossum94f6f721999-01-06 18:42:14 +000010688#include <sys/statvfs.h>
Larry Hastings2f936352014-08-05 14:04:04 +100010689/*[clinic input]
10690os.statvfs
Guido van Rossum94f6f721999-01-06 18:42:14 +000010691
Larry Hastings2f936352014-08-05 14:04:04 +100010692 path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
10693
10694Perform a statvfs system call on the given path.
10695
10696path may always be specified as a string.
10697On some platforms, path may also be specified as an open file descriptor.
10698 If this functionality is unavailable, using it raises an exception.
10699[clinic start generated code]*/
10700
Larry Hastings2f936352014-08-05 14:04:04 +100010701static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010702os_statvfs_impl(PyObject *module, path_t *path)
10703/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010704{
10705 int result;
10706 struct statvfs st;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010707
10708 Py_BEGIN_ALLOW_THREADS
10709#ifdef HAVE_FSTATVFS
Larry Hastings2f936352014-08-05 14:04:04 +100010710 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -070010711#ifdef __APPLE__
10712 /* handle weak-linking on Mac OS X 10.3 */
10713 if (fstatvfs == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010714 fd_specified("statvfs", path->fd);
10715 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010716 }
10717#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010718 result = fstatvfs(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010719 }
10720 else
10721#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010722 result = statvfs(path->narrow, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010723 Py_END_ALLOW_THREADS
10724
10725 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100010726 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010727 }
10728
Larry Hastings2f936352014-08-05 14:04:04 +100010729 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010730}
Larry Hastings2f936352014-08-05 14:04:04 +100010731#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
10732
Guido van Rossum94f6f721999-01-06 18:42:14 +000010733
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010734#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010735/*[clinic input]
10736os._getdiskusage
10737
Steve Dower23ad6d02018-02-22 10:39:10 -080010738 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +100010739
10740Return disk usage statistics about the given path as a (total, free) tuple.
10741[clinic start generated code]*/
10742
Larry Hastings2f936352014-08-05 14:04:04 +100010743static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -080010744os__getdiskusage_impl(PyObject *module, path_t *path)
10745/*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010746{
10747 BOOL retval;
10748 ULARGE_INTEGER _, total, free;
Joe Pamerc8c02492018-09-25 10:57:36 -040010749 DWORD err = 0;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010750
10751 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -080010752 retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010753 Py_END_ALLOW_THREADS
Joe Pamerc8c02492018-09-25 10:57:36 -040010754 if (retval == 0) {
10755 if (GetLastError() == ERROR_DIRECTORY) {
10756 wchar_t *dir_path = NULL;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010757
Joe Pamerc8c02492018-09-25 10:57:36 -040010758 dir_path = PyMem_New(wchar_t, path->length + 1);
10759 if (dir_path == NULL) {
10760 return PyErr_NoMemory();
10761 }
10762
10763 wcscpy_s(dir_path, path->length + 1, path->wide);
10764
10765 if (_dirnameW(dir_path) != -1) {
10766 Py_BEGIN_ALLOW_THREADS
10767 retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
10768 Py_END_ALLOW_THREADS
10769 }
10770 /* Record the last error in case it's modified by PyMem_Free. */
10771 err = GetLastError();
10772 PyMem_Free(dir_path);
10773 if (retval) {
10774 goto success;
10775 }
10776 }
10777 return PyErr_SetFromWindowsErr(err);
10778 }
10779
10780success:
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010781 return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
10782}
Larry Hastings2f936352014-08-05 14:04:04 +100010783#endif /* MS_WINDOWS */
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010784
10785
Fred Drakec9680921999-12-13 16:37:25 +000010786/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
10787 * It maps strings representing configuration variable names to
10788 * integer values, allowing those functions to be called with the
Thomas Wouters7e474022000-07-16 12:04:32 +000010789 * magic names instead of polluting the module's namespace with tons of
Fred Drake12c6e2d1999-12-14 21:25:03 +000010790 * rarely-used constants. There are three separate tables that use
10791 * these definitions.
Fred Drakebec628d1999-12-15 18:31:10 +000010792 *
10793 * This code is always included, even if none of the interfaces that
10794 * need it are included. The #if hackery needed to avoid it would be
10795 * sufficiently pervasive that it's not worth the loss of readability.
Fred Drakec9680921999-12-13 16:37:25 +000010796 */
10797struct constdef {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020010798 const char *name;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010799 int value;
Fred Drakec9680921999-12-13 16:37:25 +000010800};
10801
Fred Drake12c6e2d1999-12-14 21:25:03 +000010802static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010803conv_confname(PyObject *arg, int *valuep, struct constdef *table,
Guido van Rossum7d5baac2007-08-27 23:24:46 +000010804 size_t tablesize)
Fred Drake12c6e2d1999-12-14 21:25:03 +000010805{
Christian Heimes217cfd12007-12-02 14:31:20 +000010806 if (PyLong_Check(arg)) {
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010807 int value = _PyLong_AsInt(arg);
10808 if (value == -1 && PyErr_Occurred())
10809 return 0;
10810 *valuep = value;
Stefan Krah0e803b32010-11-26 16:16:47 +000010811 return 1;
Fred Drake12c6e2d1999-12-14 21:25:03 +000010812 }
Guido van Rossumbce56a62007-05-10 18:04:33 +000010813 else {
Stefan Krah0e803b32010-11-26 16:16:47 +000010814 /* look up the value in the table using a binary search */
10815 size_t lo = 0;
10816 size_t mid;
10817 size_t hi = tablesize;
10818 int cmp;
10819 const char *confname;
10820 if (!PyUnicode_Check(arg)) {
10821 PyErr_SetString(PyExc_TypeError,
10822 "configuration names must be strings or integers");
10823 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010824 }
Serhiy Storchaka06515832016-11-20 09:13:07 +020010825 confname = PyUnicode_AsUTF8(arg);
Stefan Krah0e803b32010-11-26 16:16:47 +000010826 if (confname == NULL)
10827 return 0;
10828 while (lo < hi) {
10829 mid = (lo + hi) / 2;
10830 cmp = strcmp(confname, table[mid].name);
10831 if (cmp < 0)
10832 hi = mid;
10833 else if (cmp > 0)
10834 lo = mid + 1;
10835 else {
10836 *valuep = table[mid].value;
10837 return 1;
10838 }
10839 }
10840 PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
10841 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010842 }
Fred Drake12c6e2d1999-12-14 21:25:03 +000010843}
10844
10845
10846#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
10847static struct constdef posix_constants_pathconf[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010848#ifdef _PC_ABI_AIO_XFER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010849 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000010850#endif
10851#ifdef _PC_ABI_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010852 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010853#endif
Fred Drakec9680921999-12-13 16:37:25 +000010854#ifdef _PC_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010855 {"PC_ASYNC_IO", _PC_ASYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010856#endif
10857#ifdef _PC_CHOWN_RESTRICTED
Victor Stinner8c62be82010-05-06 00:08:46 +000010858 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
Fred Drakec9680921999-12-13 16:37:25 +000010859#endif
10860#ifdef _PC_FILESIZEBITS
Victor Stinner8c62be82010-05-06 00:08:46 +000010861 {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
Fred Drakec9680921999-12-13 16:37:25 +000010862#endif
10863#ifdef _PC_LAST
Victor Stinner8c62be82010-05-06 00:08:46 +000010864 {"PC_LAST", _PC_LAST},
Fred Drakec9680921999-12-13 16:37:25 +000010865#endif
10866#ifdef _PC_LINK_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010867 {"PC_LINK_MAX", _PC_LINK_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010868#endif
10869#ifdef _PC_MAX_CANON
Victor Stinner8c62be82010-05-06 00:08:46 +000010870 {"PC_MAX_CANON", _PC_MAX_CANON},
Fred Drakec9680921999-12-13 16:37:25 +000010871#endif
10872#ifdef _PC_MAX_INPUT
Victor Stinner8c62be82010-05-06 00:08:46 +000010873 {"PC_MAX_INPUT", _PC_MAX_INPUT},
Fred Drakec9680921999-12-13 16:37:25 +000010874#endif
10875#ifdef _PC_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010876 {"PC_NAME_MAX", _PC_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010877#endif
10878#ifdef _PC_NO_TRUNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010879 {"PC_NO_TRUNC", _PC_NO_TRUNC},
Fred Drakec9680921999-12-13 16:37:25 +000010880#endif
10881#ifdef _PC_PATH_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010882 {"PC_PATH_MAX", _PC_PATH_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010883#endif
10884#ifdef _PC_PIPE_BUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010885 {"PC_PIPE_BUF", _PC_PIPE_BUF},
Fred Drakec9680921999-12-13 16:37:25 +000010886#endif
10887#ifdef _PC_PRIO_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010888 {"PC_PRIO_IO", _PC_PRIO_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010889#endif
10890#ifdef _PC_SOCK_MAXBUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010891 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
Fred Drakec9680921999-12-13 16:37:25 +000010892#endif
10893#ifdef _PC_SYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010894 {"PC_SYNC_IO", _PC_SYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010895#endif
10896#ifdef _PC_VDISABLE
Victor Stinner8c62be82010-05-06 00:08:46 +000010897 {"PC_VDISABLE", _PC_VDISABLE},
Fred Drakec9680921999-12-13 16:37:25 +000010898#endif
Jesus Cea7e9065c2010-10-25 13:02:04 +000010899#ifdef _PC_ACL_ENABLED
10900 {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
10901#endif
10902#ifdef _PC_MIN_HOLE_SIZE
10903 {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
10904#endif
10905#ifdef _PC_ALLOC_SIZE_MIN
10906 {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
10907#endif
10908#ifdef _PC_REC_INCR_XFER_SIZE
10909 {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
10910#endif
10911#ifdef _PC_REC_MAX_XFER_SIZE
10912 {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
10913#endif
10914#ifdef _PC_REC_MIN_XFER_SIZE
10915 {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
10916#endif
10917#ifdef _PC_REC_XFER_ALIGN
10918 {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
10919#endif
10920#ifdef _PC_SYMLINK_MAX
10921 {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
10922#endif
10923#ifdef _PC_XATTR_ENABLED
10924 {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
10925#endif
10926#ifdef _PC_XATTR_EXISTS
10927 {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
10928#endif
10929#ifdef _PC_TIMESTAMP_RESOLUTION
10930 {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
10931#endif
Fred Drakec9680921999-12-13 16:37:25 +000010932};
10933
Fred Drakec9680921999-12-13 16:37:25 +000010934static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010935conv_path_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010936{
10937 return conv_confname(arg, valuep, posix_constants_pathconf,
10938 sizeof(posix_constants_pathconf)
10939 / sizeof(struct constdef));
10940}
10941#endif
10942
Larry Hastings2f936352014-08-05 14:04:04 +100010943
Fred Drakec9680921999-12-13 16:37:25 +000010944#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010945/*[clinic input]
10946os.fpathconf -> long
10947
10948 fd: int
10949 name: path_confname
10950 /
10951
10952Return the configuration limit name for the file descriptor fd.
10953
10954If there is no limit, return -1.
10955[clinic start generated code]*/
10956
Larry Hastings2f936352014-08-05 14:04:04 +100010957static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010958os_fpathconf_impl(PyObject *module, int fd, int name)
10959/*[clinic end generated code: output=d5b7042425fc3e21 input=5942a024d3777810]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010960{
10961 long limit;
10962
10963 errno = 0;
10964 limit = fpathconf(fd, name);
10965 if (limit == -1 && errno != 0)
10966 posix_error();
10967
10968 return limit;
10969}
10970#endif /* HAVE_FPATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010971
10972
10973#ifdef HAVE_PATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010974/*[clinic input]
10975os.pathconf -> long
10976 path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
10977 name: path_confname
10978
10979Return the configuration limit name for the file or directory path.
10980
10981If there is no limit, return -1.
10982On some platforms, path may also be specified as an open file descriptor.
10983 If this functionality is unavailable, using it raises an exception.
10984[clinic start generated code]*/
10985
Larry Hastings2f936352014-08-05 14:04:04 +100010986static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010987os_pathconf_impl(PyObject *module, path_t *path, int name)
10988/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010989{
Victor Stinner8c62be82010-05-06 00:08:46 +000010990 long limit;
Fred Drakec9680921999-12-13 16:37:25 +000010991
Victor Stinner8c62be82010-05-06 00:08:46 +000010992 errno = 0;
Georg Brandl306336b2012-06-24 12:55:33 +020010993#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010994 if (path->fd != -1)
10995 limit = fpathconf(path->fd, name);
Georg Brandl306336b2012-06-24 12:55:33 +020010996 else
10997#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010998 limit = pathconf(path->narrow, name);
Victor Stinner8c62be82010-05-06 00:08:46 +000010999 if (limit == -1 && errno != 0) {
11000 if (errno == EINVAL)
Stefan Krah99439262010-11-26 12:58:05 +000011001 /* could be a path or name problem */
11002 posix_error();
Fred Drakec9680921999-12-13 16:37:25 +000011003 else
Larry Hastings2f936352014-08-05 14:04:04 +100011004 path_error(path);
Victor Stinner8c62be82010-05-06 00:08:46 +000011005 }
Larry Hastings2f936352014-08-05 14:04:04 +100011006
11007 return limit;
Fred Drakec9680921999-12-13 16:37:25 +000011008}
Larry Hastings2f936352014-08-05 14:04:04 +100011009#endif /* HAVE_PATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011010
11011#ifdef HAVE_CONFSTR
11012static struct constdef posix_constants_confstr[] = {
Fred Draked86ed291999-12-15 15:34:33 +000011013#ifdef _CS_ARCHITECTURE
Victor Stinner8c62be82010-05-06 00:08:46 +000011014 {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
Fred Draked86ed291999-12-15 15:34:33 +000011015#endif
Mark Dickinson876d7c82010-04-16 12:47:52 +000011016#ifdef _CS_GNU_LIBC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011017 {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000011018#endif
11019#ifdef _CS_GNU_LIBPTHREAD_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011020 {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000011021#endif
Fred Draked86ed291999-12-15 15:34:33 +000011022#ifdef _CS_HOSTNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011023 {"CS_HOSTNAME", _CS_HOSTNAME},
Fred Draked86ed291999-12-15 15:34:33 +000011024#endif
11025#ifdef _CS_HW_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000011026 {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000011027#endif
11028#ifdef _CS_HW_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000011029 {"CS_HW_SERIAL", _CS_HW_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000011030#endif
11031#ifdef _CS_INITTAB_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011032 {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000011033#endif
Fred Drakec9680921999-12-13 16:37:25 +000011034#ifdef _CS_LFS64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011035 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011036#endif
11037#ifdef _CS_LFS64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011038 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011039#endif
11040#ifdef _CS_LFS64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011041 {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011042#endif
11043#ifdef _CS_LFS64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011044 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011045#endif
11046#ifdef _CS_LFS_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011047 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011048#endif
11049#ifdef _CS_LFS_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011050 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011051#endif
11052#ifdef _CS_LFS_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011053 {"CS_LFS_LIBS", _CS_LFS_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011054#endif
11055#ifdef _CS_LFS_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011056 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011057#endif
Fred Draked86ed291999-12-15 15:34:33 +000011058#ifdef _CS_MACHINE
Victor Stinner8c62be82010-05-06 00:08:46 +000011059 {"CS_MACHINE", _CS_MACHINE},
Fred Draked86ed291999-12-15 15:34:33 +000011060#endif
Fred Drakec9680921999-12-13 16:37:25 +000011061#ifdef _CS_PATH
Victor Stinner8c62be82010-05-06 00:08:46 +000011062 {"CS_PATH", _CS_PATH},
Fred Drakec9680921999-12-13 16:37:25 +000011063#endif
Fred Draked86ed291999-12-15 15:34:33 +000011064#ifdef _CS_RELEASE
Victor Stinner8c62be82010-05-06 00:08:46 +000011065 {"CS_RELEASE", _CS_RELEASE},
Fred Draked86ed291999-12-15 15:34:33 +000011066#endif
11067#ifdef _CS_SRPC_DOMAIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011068 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
Fred Draked86ed291999-12-15 15:34:33 +000011069#endif
11070#ifdef _CS_SYSNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011071 {"CS_SYSNAME", _CS_SYSNAME},
Fred Draked86ed291999-12-15 15:34:33 +000011072#endif
11073#ifdef _CS_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011074 {"CS_VERSION", _CS_VERSION},
Fred Draked86ed291999-12-15 15:34:33 +000011075#endif
Fred Drakec9680921999-12-13 16:37:25 +000011076#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011077 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011078#endif
11079#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011080 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011081#endif
11082#ifdef _CS_XBS5_ILP32_OFF32_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011083 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011084#endif
11085#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011086 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011087#endif
11088#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011089 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011090#endif
11091#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011092 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011093#endif
11094#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011095 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011096#endif
11097#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011098 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011099#endif
11100#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011101 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011102#endif
11103#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011104 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011105#endif
11106#ifdef _CS_XBS5_LP64_OFF64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011107 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011108#endif
11109#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011110 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011111#endif
11112#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011113 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011114#endif
11115#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011116 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011117#endif
11118#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011119 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011120#endif
11121#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011122 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011123#endif
Fred Draked86ed291999-12-15 15:34:33 +000011124#ifdef _MIPS_CS_AVAIL_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000011125 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000011126#endif
11127#ifdef _MIPS_CS_BASE
Victor Stinner8c62be82010-05-06 00:08:46 +000011128 {"MIPS_CS_BASE", _MIPS_CS_BASE},
Fred Draked86ed291999-12-15 15:34:33 +000011129#endif
11130#ifdef _MIPS_CS_HOSTID
Victor Stinner8c62be82010-05-06 00:08:46 +000011131 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
Fred Draked86ed291999-12-15 15:34:33 +000011132#endif
11133#ifdef _MIPS_CS_HW_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011134 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000011135#endif
11136#ifdef _MIPS_CS_NUM_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000011137 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000011138#endif
11139#ifdef _MIPS_CS_OSREL_MAJ
Victor Stinner8c62be82010-05-06 00:08:46 +000011140 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
Fred Draked86ed291999-12-15 15:34:33 +000011141#endif
11142#ifdef _MIPS_CS_OSREL_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011143 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
Fred Draked86ed291999-12-15 15:34:33 +000011144#endif
11145#ifdef _MIPS_CS_OSREL_PATCH
Victor Stinner8c62be82010-05-06 00:08:46 +000011146 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
Fred Draked86ed291999-12-15 15:34:33 +000011147#endif
11148#ifdef _MIPS_CS_OS_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011149 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000011150#endif
11151#ifdef _MIPS_CS_OS_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000011152 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000011153#endif
11154#ifdef _MIPS_CS_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000011155 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000011156#endif
11157#ifdef _MIPS_CS_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000011158 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000011159#endif
11160#ifdef _MIPS_CS_VENDOR
Victor Stinner8c62be82010-05-06 00:08:46 +000011161 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
Fred Draked86ed291999-12-15 15:34:33 +000011162#endif
Fred Drakec9680921999-12-13 16:37:25 +000011163};
11164
11165static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011166conv_confstr_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011167{
11168 return conv_confname(arg, valuep, posix_constants_confstr,
11169 sizeof(posix_constants_confstr)
11170 / sizeof(struct constdef));
11171}
11172
Larry Hastings2f936352014-08-05 14:04:04 +100011173
11174/*[clinic input]
11175os.confstr
11176
11177 name: confstr_confname
11178 /
11179
11180Return a string-valued system configuration variable.
11181[clinic start generated code]*/
11182
Larry Hastings2f936352014-08-05 14:04:04 +100011183static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011184os_confstr_impl(PyObject *module, int name)
11185/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
Fred Drakec9680921999-12-13 16:37:25 +000011186{
11187 PyObject *result = NULL;
Victor Stinnercb043522010-09-10 23:49:04 +000011188 char buffer[255];
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011189 size_t len;
Fred Drakec9680921999-12-13 16:37:25 +000011190
Victor Stinnercb043522010-09-10 23:49:04 +000011191 errno = 0;
11192 len = confstr(name, buffer, sizeof(buffer));
11193 if (len == 0) {
11194 if (errno) {
11195 posix_error();
11196 return NULL;
Fred Drakec9680921999-12-13 16:37:25 +000011197 }
11198 else {
Victor Stinnercb043522010-09-10 23:49:04 +000011199 Py_RETURN_NONE;
Fred Drakec9680921999-12-13 16:37:25 +000011200 }
11201 }
Victor Stinnercb043522010-09-10 23:49:04 +000011202
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011203 if (len >= sizeof(buffer)) {
Victor Stinnercbc18f32014-12-05 22:51:51 +010011204 size_t len2;
Victor Stinnercb043522010-09-10 23:49:04 +000011205 char *buf = PyMem_Malloc(len);
11206 if (buf == NULL)
11207 return PyErr_NoMemory();
Victor Stinnercbc18f32014-12-05 22:51:51 +010011208 len2 = confstr(name, buf, len);
11209 assert(len == len2);
Christian Heimes8714cfd2015-04-21 10:57:41 +020011210 result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
Victor Stinnercb043522010-09-10 23:49:04 +000011211 PyMem_Free(buf);
11212 }
11213 else
11214 result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
Fred Drakec9680921999-12-13 16:37:25 +000011215 return result;
11216}
Larry Hastings2f936352014-08-05 14:04:04 +100011217#endif /* HAVE_CONFSTR */
Fred Drakec9680921999-12-13 16:37:25 +000011218
11219
11220#ifdef HAVE_SYSCONF
11221static struct constdef posix_constants_sysconf[] = {
11222#ifdef _SC_2_CHAR_TERM
Victor Stinner8c62be82010-05-06 00:08:46 +000011223 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
Fred Drakec9680921999-12-13 16:37:25 +000011224#endif
11225#ifdef _SC_2_C_BIND
Victor Stinner8c62be82010-05-06 00:08:46 +000011226 {"SC_2_C_BIND", _SC_2_C_BIND},
Fred Drakec9680921999-12-13 16:37:25 +000011227#endif
11228#ifdef _SC_2_C_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011229 {"SC_2_C_DEV", _SC_2_C_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011230#endif
11231#ifdef _SC_2_C_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011232 {"SC_2_C_VERSION", _SC_2_C_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011233#endif
11234#ifdef _SC_2_FORT_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011235 {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011236#endif
11237#ifdef _SC_2_FORT_RUN
Victor Stinner8c62be82010-05-06 00:08:46 +000011238 {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
Fred Drakec9680921999-12-13 16:37:25 +000011239#endif
11240#ifdef _SC_2_LOCALEDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000011241 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
Fred Drakec9680921999-12-13 16:37:25 +000011242#endif
11243#ifdef _SC_2_SW_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011244 {"SC_2_SW_DEV", _SC_2_SW_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011245#endif
11246#ifdef _SC_2_UPE
Victor Stinner8c62be82010-05-06 00:08:46 +000011247 {"SC_2_UPE", _SC_2_UPE},
Fred Drakec9680921999-12-13 16:37:25 +000011248#endif
11249#ifdef _SC_2_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011250 {"SC_2_VERSION", _SC_2_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011251#endif
Fred Draked86ed291999-12-15 15:34:33 +000011252#ifdef _SC_ABI_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011253 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
Fred Draked86ed291999-12-15 15:34:33 +000011254#endif
11255#ifdef _SC_ACL
Victor Stinner8c62be82010-05-06 00:08:46 +000011256 {"SC_ACL", _SC_ACL},
Fred Draked86ed291999-12-15 15:34:33 +000011257#endif
Fred Drakec9680921999-12-13 16:37:25 +000011258#ifdef _SC_AIO_LISTIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011259 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011260#endif
Fred Drakec9680921999-12-13 16:37:25 +000011261#ifdef _SC_AIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011262 {"SC_AIO_MAX", _SC_AIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011263#endif
11264#ifdef _SC_AIO_PRIO_DELTA_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011265 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011266#endif
11267#ifdef _SC_ARG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011268 {"SC_ARG_MAX", _SC_ARG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011269#endif
11270#ifdef _SC_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011271 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011272#endif
11273#ifdef _SC_ATEXIT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011274 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011275#endif
Fred Draked86ed291999-12-15 15:34:33 +000011276#ifdef _SC_AUDIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011277 {"SC_AUDIT", _SC_AUDIT},
Fred Draked86ed291999-12-15 15:34:33 +000011278#endif
Fred Drakec9680921999-12-13 16:37:25 +000011279#ifdef _SC_AVPHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011280 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011281#endif
11282#ifdef _SC_BC_BASE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011283 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011284#endif
11285#ifdef _SC_BC_DIM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011286 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011287#endif
11288#ifdef _SC_BC_SCALE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011289 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011290#endif
11291#ifdef _SC_BC_STRING_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011292 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011293#endif
Fred Draked86ed291999-12-15 15:34:33 +000011294#ifdef _SC_CAP
Victor Stinner8c62be82010-05-06 00:08:46 +000011295 {"SC_CAP", _SC_CAP},
Fred Draked86ed291999-12-15 15:34:33 +000011296#endif
Fred Drakec9680921999-12-13 16:37:25 +000011297#ifdef _SC_CHARCLASS_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011298 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011299#endif
11300#ifdef _SC_CHAR_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011301 {"SC_CHAR_BIT", _SC_CHAR_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011302#endif
11303#ifdef _SC_CHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011304 {"SC_CHAR_MAX", _SC_CHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011305#endif
11306#ifdef _SC_CHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011307 {"SC_CHAR_MIN", _SC_CHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011308#endif
11309#ifdef _SC_CHILD_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011310 {"SC_CHILD_MAX", _SC_CHILD_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011311#endif
11312#ifdef _SC_CLK_TCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011313 {"SC_CLK_TCK", _SC_CLK_TCK},
Fred Drakec9680921999-12-13 16:37:25 +000011314#endif
11315#ifdef _SC_COHER_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011316 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011317#endif
11318#ifdef _SC_COLL_WEIGHTS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011319 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011320#endif
11321#ifdef _SC_DCACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011322 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011323#endif
11324#ifdef _SC_DCACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011325 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011326#endif
11327#ifdef _SC_DCACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011328 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011329#endif
11330#ifdef _SC_DCACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011331 {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011332#endif
11333#ifdef _SC_DCACHE_TBLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011334 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011335#endif
11336#ifdef _SC_DELAYTIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011337 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011338#endif
11339#ifdef _SC_EQUIV_CLASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011340 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011341#endif
11342#ifdef _SC_EXPR_NEST_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011343 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011344#endif
11345#ifdef _SC_FSYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000011346 {"SC_FSYNC", _SC_FSYNC},
Fred Drakec9680921999-12-13 16:37:25 +000011347#endif
11348#ifdef _SC_GETGR_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011349 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011350#endif
11351#ifdef _SC_GETPW_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011352 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011353#endif
11354#ifdef _SC_ICACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011355 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011356#endif
11357#ifdef _SC_ICACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011358 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011359#endif
11360#ifdef _SC_ICACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011361 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011362#endif
11363#ifdef _SC_ICACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011364 {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011365#endif
Fred Draked86ed291999-12-15 15:34:33 +000011366#ifdef _SC_INF
Victor Stinner8c62be82010-05-06 00:08:46 +000011367 {"SC_INF", _SC_INF},
Fred Draked86ed291999-12-15 15:34:33 +000011368#endif
Fred Drakec9680921999-12-13 16:37:25 +000011369#ifdef _SC_INT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011370 {"SC_INT_MAX", _SC_INT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011371#endif
11372#ifdef _SC_INT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011373 {"SC_INT_MIN", _SC_INT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011374#endif
11375#ifdef _SC_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011376 {"SC_IOV_MAX", _SC_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011377#endif
Fred Draked86ed291999-12-15 15:34:33 +000011378#ifdef _SC_IP_SECOPTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011379 {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
Fred Draked86ed291999-12-15 15:34:33 +000011380#endif
Fred Drakec9680921999-12-13 16:37:25 +000011381#ifdef _SC_JOB_CONTROL
Victor Stinner8c62be82010-05-06 00:08:46 +000011382 {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
Fred Drakec9680921999-12-13 16:37:25 +000011383#endif
Fred Draked86ed291999-12-15 15:34:33 +000011384#ifdef _SC_KERN_POINTERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011385 {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
Fred Draked86ed291999-12-15 15:34:33 +000011386#endif
11387#ifdef _SC_KERN_SIM
Victor Stinner8c62be82010-05-06 00:08:46 +000011388 {"SC_KERN_SIM", _SC_KERN_SIM},
Fred Draked86ed291999-12-15 15:34:33 +000011389#endif
Fred Drakec9680921999-12-13 16:37:25 +000011390#ifdef _SC_LINE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011391 {"SC_LINE_MAX", _SC_LINE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011392#endif
11393#ifdef _SC_LOGIN_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011394 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011395#endif
11396#ifdef _SC_LOGNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011397 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011398#endif
11399#ifdef _SC_LONG_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011400 {"SC_LONG_BIT", _SC_LONG_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011401#endif
Fred Draked86ed291999-12-15 15:34:33 +000011402#ifdef _SC_MAC
Victor Stinner8c62be82010-05-06 00:08:46 +000011403 {"SC_MAC", _SC_MAC},
Fred Draked86ed291999-12-15 15:34:33 +000011404#endif
Fred Drakec9680921999-12-13 16:37:25 +000011405#ifdef _SC_MAPPED_FILES
Victor Stinner8c62be82010-05-06 00:08:46 +000011406 {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
Fred Drakec9680921999-12-13 16:37:25 +000011407#endif
11408#ifdef _SC_MAXPID
Victor Stinner8c62be82010-05-06 00:08:46 +000011409 {"SC_MAXPID", _SC_MAXPID},
Fred Drakec9680921999-12-13 16:37:25 +000011410#endif
11411#ifdef _SC_MB_LEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011412 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011413#endif
11414#ifdef _SC_MEMLOCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011415 {"SC_MEMLOCK", _SC_MEMLOCK},
Fred Drakec9680921999-12-13 16:37:25 +000011416#endif
11417#ifdef _SC_MEMLOCK_RANGE
Victor Stinner8c62be82010-05-06 00:08:46 +000011418 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
Fred Drakec9680921999-12-13 16:37:25 +000011419#endif
11420#ifdef _SC_MEMORY_PROTECTION
Victor Stinner8c62be82010-05-06 00:08:46 +000011421 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
Fred Drakec9680921999-12-13 16:37:25 +000011422#endif
11423#ifdef _SC_MESSAGE_PASSING
Victor Stinner8c62be82010-05-06 00:08:46 +000011424 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
Fred Drakec9680921999-12-13 16:37:25 +000011425#endif
Fred Draked86ed291999-12-15 15:34:33 +000011426#ifdef _SC_MMAP_FIXED_ALIGNMENT
Victor Stinner8c62be82010-05-06 00:08:46 +000011427 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
Fred Draked86ed291999-12-15 15:34:33 +000011428#endif
Fred Drakec9680921999-12-13 16:37:25 +000011429#ifdef _SC_MQ_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011430 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011431#endif
11432#ifdef _SC_MQ_PRIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011433 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011434#endif
Fred Draked86ed291999-12-15 15:34:33 +000011435#ifdef _SC_NACLS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011436 {"SC_NACLS_MAX", _SC_NACLS_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000011437#endif
Fred Drakec9680921999-12-13 16:37:25 +000011438#ifdef _SC_NGROUPS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011439 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011440#endif
11441#ifdef _SC_NL_ARGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011442 {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011443#endif
11444#ifdef _SC_NL_LANGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011445 {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011446#endif
11447#ifdef _SC_NL_MSGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011448 {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011449#endif
11450#ifdef _SC_NL_NMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011451 {"SC_NL_NMAX", _SC_NL_NMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011452#endif
11453#ifdef _SC_NL_SETMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011454 {"SC_NL_SETMAX", _SC_NL_SETMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011455#endif
11456#ifdef _SC_NL_TEXTMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011457 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011458#endif
11459#ifdef _SC_NPROCESSORS_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011460 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
Fred Drakec9680921999-12-13 16:37:25 +000011461#endif
11462#ifdef _SC_NPROCESSORS_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011463 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
Fred Drakec9680921999-12-13 16:37:25 +000011464#endif
Fred Draked86ed291999-12-15 15:34:33 +000011465#ifdef _SC_NPROC_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011466 {"SC_NPROC_CONF", _SC_NPROC_CONF},
Fred Draked86ed291999-12-15 15:34:33 +000011467#endif
11468#ifdef _SC_NPROC_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011469 {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
Fred Draked86ed291999-12-15 15:34:33 +000011470#endif
Fred Drakec9680921999-12-13 16:37:25 +000011471#ifdef _SC_NZERO
Victor Stinner8c62be82010-05-06 00:08:46 +000011472 {"SC_NZERO", _SC_NZERO},
Fred Drakec9680921999-12-13 16:37:25 +000011473#endif
11474#ifdef _SC_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011475 {"SC_OPEN_MAX", _SC_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011476#endif
11477#ifdef _SC_PAGESIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011478 {"SC_PAGESIZE", _SC_PAGESIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011479#endif
11480#ifdef _SC_PAGE_SIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011481 {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011482#endif
Batuhan Taşkaya909f4a32020-04-05 03:40:49 +030011483#ifdef _SC_AIX_REALMEM
11484 {"SC_AIX_REALMEM", _SC_AIX_REALMEM},
11485#endif
Fred Drakec9680921999-12-13 16:37:25 +000011486#ifdef _SC_PASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011487 {"SC_PASS_MAX", _SC_PASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011488#endif
11489#ifdef _SC_PHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011490 {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011491#endif
11492#ifdef _SC_PII
Victor Stinner8c62be82010-05-06 00:08:46 +000011493 {"SC_PII", _SC_PII},
Fred Drakec9680921999-12-13 16:37:25 +000011494#endif
11495#ifdef _SC_PII_INTERNET
Victor Stinner8c62be82010-05-06 00:08:46 +000011496 {"SC_PII_INTERNET", _SC_PII_INTERNET},
Fred Drakec9680921999-12-13 16:37:25 +000011497#endif
11498#ifdef _SC_PII_INTERNET_DGRAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011499 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
Fred Drakec9680921999-12-13 16:37:25 +000011500#endif
11501#ifdef _SC_PII_INTERNET_STREAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011502 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
Fred Drakec9680921999-12-13 16:37:25 +000011503#endif
11504#ifdef _SC_PII_OSI
Victor Stinner8c62be82010-05-06 00:08:46 +000011505 {"SC_PII_OSI", _SC_PII_OSI},
Fred Drakec9680921999-12-13 16:37:25 +000011506#endif
11507#ifdef _SC_PII_OSI_CLTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011508 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
Fred Drakec9680921999-12-13 16:37:25 +000011509#endif
11510#ifdef _SC_PII_OSI_COTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011511 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
Fred Drakec9680921999-12-13 16:37:25 +000011512#endif
11513#ifdef _SC_PII_OSI_M
Victor Stinner8c62be82010-05-06 00:08:46 +000011514 {"SC_PII_OSI_M", _SC_PII_OSI_M},
Fred Drakec9680921999-12-13 16:37:25 +000011515#endif
11516#ifdef _SC_PII_SOCKET
Victor Stinner8c62be82010-05-06 00:08:46 +000011517 {"SC_PII_SOCKET", _SC_PII_SOCKET},
Fred Drakec9680921999-12-13 16:37:25 +000011518#endif
11519#ifdef _SC_PII_XTI
Victor Stinner8c62be82010-05-06 00:08:46 +000011520 {"SC_PII_XTI", _SC_PII_XTI},
Fred Drakec9680921999-12-13 16:37:25 +000011521#endif
11522#ifdef _SC_POLL
Victor Stinner8c62be82010-05-06 00:08:46 +000011523 {"SC_POLL", _SC_POLL},
Fred Drakec9680921999-12-13 16:37:25 +000011524#endif
11525#ifdef _SC_PRIORITIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011526 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011527#endif
11528#ifdef _SC_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011529 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011530#endif
11531#ifdef _SC_REALTIME_SIGNALS
Victor Stinner8c62be82010-05-06 00:08:46 +000011532 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
Fred Drakec9680921999-12-13 16:37:25 +000011533#endif
11534#ifdef _SC_RE_DUP_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011535 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011536#endif
11537#ifdef _SC_RTSIG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011538 {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011539#endif
11540#ifdef _SC_SAVED_IDS
Victor Stinner8c62be82010-05-06 00:08:46 +000011541 {"SC_SAVED_IDS", _SC_SAVED_IDS},
Fred Drakec9680921999-12-13 16:37:25 +000011542#endif
11543#ifdef _SC_SCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011544 {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011545#endif
11546#ifdef _SC_SCHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011547 {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011548#endif
11549#ifdef _SC_SELECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011550 {"SC_SELECT", _SC_SELECT},
Fred Drakec9680921999-12-13 16:37:25 +000011551#endif
11552#ifdef _SC_SEMAPHORES
Victor Stinner8c62be82010-05-06 00:08:46 +000011553 {"SC_SEMAPHORES", _SC_SEMAPHORES},
Fred Drakec9680921999-12-13 16:37:25 +000011554#endif
11555#ifdef _SC_SEM_NSEMS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011556 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011557#endif
11558#ifdef _SC_SEM_VALUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011559 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011560#endif
11561#ifdef _SC_SHARED_MEMORY_OBJECTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011562 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
Fred Drakec9680921999-12-13 16:37:25 +000011563#endif
11564#ifdef _SC_SHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011565 {"SC_SHRT_MAX", _SC_SHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011566#endif
11567#ifdef _SC_SHRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011568 {"SC_SHRT_MIN", _SC_SHRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011569#endif
11570#ifdef _SC_SIGQUEUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011571 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011572#endif
11573#ifdef _SC_SIGRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011574 {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011575#endif
11576#ifdef _SC_SIGRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011577 {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011578#endif
Fred Draked86ed291999-12-15 15:34:33 +000011579#ifdef _SC_SOFTPOWER
Victor Stinner8c62be82010-05-06 00:08:46 +000011580 {"SC_SOFTPOWER", _SC_SOFTPOWER},
Fred Draked86ed291999-12-15 15:34:33 +000011581#endif
Fred Drakec9680921999-12-13 16:37:25 +000011582#ifdef _SC_SPLIT_CACHE
Victor Stinner8c62be82010-05-06 00:08:46 +000011583 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
Fred Drakec9680921999-12-13 16:37:25 +000011584#endif
11585#ifdef _SC_SSIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011586 {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011587#endif
11588#ifdef _SC_STACK_PROT
Victor Stinner8c62be82010-05-06 00:08:46 +000011589 {"SC_STACK_PROT", _SC_STACK_PROT},
Fred Drakec9680921999-12-13 16:37:25 +000011590#endif
11591#ifdef _SC_STREAM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011592 {"SC_STREAM_MAX", _SC_STREAM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011593#endif
11594#ifdef _SC_SYNCHRONIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011595 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011596#endif
11597#ifdef _SC_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011598 {"SC_THREADS", _SC_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011599#endif
11600#ifdef _SC_THREAD_ATTR_STACKADDR
Victor Stinner8c62be82010-05-06 00:08:46 +000011601 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
Fred Drakec9680921999-12-13 16:37:25 +000011602#endif
11603#ifdef _SC_THREAD_ATTR_STACKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011604 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011605#endif
11606#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011607 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011608#endif
11609#ifdef _SC_THREAD_KEYS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011610 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011611#endif
11612#ifdef _SC_THREAD_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011613 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011614#endif
11615#ifdef _SC_THREAD_PRIO_INHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011616 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
Fred Drakec9680921999-12-13 16:37:25 +000011617#endif
11618#ifdef _SC_THREAD_PRIO_PROTECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011619 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
Fred Drakec9680921999-12-13 16:37:25 +000011620#endif
11621#ifdef _SC_THREAD_PROCESS_SHARED
Victor Stinner8c62be82010-05-06 00:08:46 +000011622 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
Fred Drakec9680921999-12-13 16:37:25 +000011623#endif
11624#ifdef _SC_THREAD_SAFE_FUNCTIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011625 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011626#endif
11627#ifdef _SC_THREAD_STACK_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011628 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011629#endif
11630#ifdef _SC_THREAD_THREADS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011631 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011632#endif
11633#ifdef _SC_TIMERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011634 {"SC_TIMERS", _SC_TIMERS},
Fred Drakec9680921999-12-13 16:37:25 +000011635#endif
11636#ifdef _SC_TIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011637 {"SC_TIMER_MAX", _SC_TIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011638#endif
11639#ifdef _SC_TTY_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011640 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011641#endif
11642#ifdef _SC_TZNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011643 {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011644#endif
11645#ifdef _SC_T_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011646 {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011647#endif
11648#ifdef _SC_UCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011649 {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011650#endif
11651#ifdef _SC_UINT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011652 {"SC_UINT_MAX", _SC_UINT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011653#endif
11654#ifdef _SC_UIO_MAXIOV
Victor Stinner8c62be82010-05-06 00:08:46 +000011655 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
Fred Drakec9680921999-12-13 16:37:25 +000011656#endif
11657#ifdef _SC_ULONG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011658 {"SC_ULONG_MAX", _SC_ULONG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011659#endif
11660#ifdef _SC_USHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011661 {"SC_USHRT_MAX", _SC_USHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011662#endif
11663#ifdef _SC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011664 {"SC_VERSION", _SC_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011665#endif
11666#ifdef _SC_WORD_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011667 {"SC_WORD_BIT", _SC_WORD_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011668#endif
11669#ifdef _SC_XBS5_ILP32_OFF32
Victor Stinner8c62be82010-05-06 00:08:46 +000011670 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
Fred Drakec9680921999-12-13 16:37:25 +000011671#endif
11672#ifdef _SC_XBS5_ILP32_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011673 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011674#endif
11675#ifdef _SC_XBS5_LP64_OFF64
Victor Stinner8c62be82010-05-06 00:08:46 +000011676 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
Fred Drakec9680921999-12-13 16:37:25 +000011677#endif
11678#ifdef _SC_XBS5_LPBIG_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011679 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011680#endif
11681#ifdef _SC_XOPEN_CRYPT
Victor Stinner8c62be82010-05-06 00:08:46 +000011682 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
Fred Drakec9680921999-12-13 16:37:25 +000011683#endif
11684#ifdef _SC_XOPEN_ENH_I18N
Victor Stinner8c62be82010-05-06 00:08:46 +000011685 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
Fred Drakec9680921999-12-13 16:37:25 +000011686#endif
11687#ifdef _SC_XOPEN_LEGACY
Victor Stinner8c62be82010-05-06 00:08:46 +000011688 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
Fred Drakec9680921999-12-13 16:37:25 +000011689#endif
11690#ifdef _SC_XOPEN_REALTIME
Victor Stinner8c62be82010-05-06 00:08:46 +000011691 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
Fred Drakec9680921999-12-13 16:37:25 +000011692#endif
11693#ifdef _SC_XOPEN_REALTIME_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011694 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011695#endif
11696#ifdef _SC_XOPEN_SHM
Victor Stinner8c62be82010-05-06 00:08:46 +000011697 {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
Fred Drakec9680921999-12-13 16:37:25 +000011698#endif
11699#ifdef _SC_XOPEN_UNIX
Victor Stinner8c62be82010-05-06 00:08:46 +000011700 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
Fred Drakec9680921999-12-13 16:37:25 +000011701#endif
11702#ifdef _SC_XOPEN_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011703 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011704#endif
11705#ifdef _SC_XOPEN_XCU_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011706 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011707#endif
11708#ifdef _SC_XOPEN_XPG2
Victor Stinner8c62be82010-05-06 00:08:46 +000011709 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
Fred Drakec9680921999-12-13 16:37:25 +000011710#endif
11711#ifdef _SC_XOPEN_XPG3
Victor Stinner8c62be82010-05-06 00:08:46 +000011712 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
Fred Drakec9680921999-12-13 16:37:25 +000011713#endif
11714#ifdef _SC_XOPEN_XPG4
Victor Stinner8c62be82010-05-06 00:08:46 +000011715 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
Fred Drakec9680921999-12-13 16:37:25 +000011716#endif
11717};
11718
11719static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011720conv_sysconf_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011721{
11722 return conv_confname(arg, valuep, posix_constants_sysconf,
11723 sizeof(posix_constants_sysconf)
11724 / sizeof(struct constdef));
11725}
11726
Larry Hastings2f936352014-08-05 14:04:04 +100011727
11728/*[clinic input]
11729os.sysconf -> long
11730 name: sysconf_confname
11731 /
11732
11733Return an integer-valued system configuration variable.
11734[clinic start generated code]*/
11735
Larry Hastings2f936352014-08-05 14:04:04 +100011736static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011737os_sysconf_impl(PyObject *module, int name)
11738/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011739{
11740 long value;
11741
11742 errno = 0;
11743 value = sysconf(name);
11744 if (value == -1 && errno != 0)
11745 posix_error();
11746 return value;
11747}
11748#endif /* HAVE_SYSCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011749
11750
Fred Drakebec628d1999-12-15 18:31:10 +000011751/* This code is used to ensure that the tables of configuration value names
Serhiy Storchaka56a6d852014-12-01 18:28:43 +020011752 * are in sorted order as required by conv_confname(), and also to build
Fred Drakebec628d1999-12-15 18:31:10 +000011753 * the exported dictionaries that are used to publish information about the
11754 * names available on the host platform.
11755 *
11756 * Sorting the table at runtime ensures that the table is properly ordered
11757 * when used, even for platforms we're not able to test on. It also makes
11758 * it easier to add additional entries to the tables.
Fred Draked86ed291999-12-15 15:34:33 +000011759 */
Fred Drakebec628d1999-12-15 18:31:10 +000011760
11761static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011762cmp_constdefs(const void *v1, const void *v2)
Fred Drakebec628d1999-12-15 18:31:10 +000011763{
11764 const struct constdef *c1 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011765 (const struct constdef *) v1;
Fred Drakebec628d1999-12-15 18:31:10 +000011766 const struct constdef *c2 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011767 (const struct constdef *) v2;
Fred Drakebec628d1999-12-15 18:31:10 +000011768
11769 return strcmp(c1->name, c2->name);
11770}
11771
11772static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011773setup_confname_table(struct constdef *table, size_t tablesize,
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011774 const char *tablename, PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011775{
Fred Drakebec628d1999-12-15 18:31:10 +000011776 PyObject *d = NULL;
Barry Warsaw3155db32000-04-13 15:20:40 +000011777 size_t i;
Fred Drakebec628d1999-12-15 18:31:10 +000011778
11779 qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
11780 d = PyDict_New();
Barry Warsaw3155db32000-04-13 15:20:40 +000011781 if (d == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +000011782 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011783
Barry Warsaw3155db32000-04-13 15:20:40 +000011784 for (i=0; i < tablesize; ++i) {
Victor Stinner8c62be82010-05-06 00:08:46 +000011785 PyObject *o = PyLong_FromLong(table[i].value);
11786 if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
11787 Py_XDECREF(o);
11788 Py_DECREF(d);
11789 return -1;
11790 }
11791 Py_DECREF(o);
Fred Draked86ed291999-12-15 15:34:33 +000011792 }
Fred Drake4d1e64b2002-04-15 19:40:07 +000011793 return PyModule_AddObject(module, tablename, d);
Fred Draked86ed291999-12-15 15:34:33 +000011794}
11795
Fred Drakebec628d1999-12-15 18:31:10 +000011796/* Return -1 on failure, 0 on success. */
11797static int
Fred Drake4d1e64b2002-04-15 19:40:07 +000011798setup_confname_tables(PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011799{
11800#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
Fred Drakebec628d1999-12-15 18:31:10 +000011801 if (setup_confname_table(posix_constants_pathconf,
Fred Draked86ed291999-12-15 15:34:33 +000011802 sizeof(posix_constants_pathconf)
11803 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011804 "pathconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011805 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011806#endif
11807#ifdef HAVE_CONFSTR
Fred Drakebec628d1999-12-15 18:31:10 +000011808 if (setup_confname_table(posix_constants_confstr,
Fred Draked86ed291999-12-15 15:34:33 +000011809 sizeof(posix_constants_confstr)
11810 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011811 "confstr_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011812 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011813#endif
11814#ifdef HAVE_SYSCONF
Fred Drakebec628d1999-12-15 18:31:10 +000011815 if (setup_confname_table(posix_constants_sysconf,
Fred Draked86ed291999-12-15 15:34:33 +000011816 sizeof(posix_constants_sysconf)
11817 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011818 "sysconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011819 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011820#endif
Fred Drakebec628d1999-12-15 18:31:10 +000011821 return 0;
Fred Draked86ed291999-12-15 15:34:33 +000011822}
Fred Draked86ed291999-12-15 15:34:33 +000011823
11824
Larry Hastings2f936352014-08-05 14:04:04 +100011825/*[clinic input]
11826os.abort
11827
11828Abort the interpreter immediately.
11829
11830This function 'dumps core' or otherwise fails in the hardest way possible
11831on the hosting operating system. This function never returns.
11832[clinic start generated code]*/
11833
Larry Hastings2f936352014-08-05 14:04:04 +100011834static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011835os_abort_impl(PyObject *module)
11836/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011837{
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011838 abort();
11839 /*NOTREACHED*/
Victor Stinner9a2329f2016-12-05 17:56:36 +010011840#ifndef __clang__
11841 /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
11842 GCC emits a warning without "return NULL;" (compiler bug?), but Clang
11843 is smarter and emits a warning on the return. */
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011844 Py_FatalError("abort() called from Python code didn't abort!");
11845 return NULL;
Victor Stinner9a2329f2016-12-05 17:56:36 +010011846#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011847}
Fred Drakebec628d1999-12-15 18:31:10 +000011848
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011849#ifdef MS_WINDOWS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011850/* Grab ShellExecute dynamically from shell32 */
11851static int has_ShellExecute = -1;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011852static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
11853 LPCWSTR, INT);
11854static int
11855check_ShellExecute()
11856{
11857 HINSTANCE hShell32;
11858
11859 /* only recheck */
11860 if (-1 == has_ShellExecute) {
11861 Py_BEGIN_ALLOW_THREADS
Victor Stinnera9912152017-10-13 13:46:57 -070011862 /* Security note: this call is not vulnerable to "DLL hijacking".
11863 SHELL32 is part of "KnownDLLs" and so Windows always load
11864 the system SHELL32.DLL, even if there is another SHELL32.DLL
11865 in the DLL search path. */
Steve Dower7d0e0c92015-01-24 08:18:24 -080011866 hShell32 = LoadLibraryW(L"SHELL32");
Steve Dower7d0e0c92015-01-24 08:18:24 -080011867 if (hShell32) {
Steve Dower7d0e0c92015-01-24 08:18:24 -080011868 *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
11869 "ShellExecuteW");
Steve Dowercc16be82016-09-08 10:35:16 -070011870 has_ShellExecute = Py_ShellExecuteW != NULL;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011871 } else {
11872 has_ShellExecute = 0;
11873 }
Tony Roberts4860f012019-02-02 18:16:42 +010011874 Py_END_ALLOW_THREADS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011875 }
11876 return has_ShellExecute;
11877}
11878
11879
Steve Dowercc16be82016-09-08 10:35:16 -070011880/*[clinic input]
11881os.startfile
11882 filepath: path_t
11883 operation: Py_UNICODE = NULL
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +000011884
Steve Dowercc16be82016-09-08 10:35:16 -070011885Start a file with its associated application.
11886
11887When "operation" is not specified or "open", this acts like
11888double-clicking the file in Explorer, or giving the file name as an
11889argument to the DOS "start" command: the file is opened with whatever
11890application (if any) its extension is associated.
11891When another "operation" is given, it specifies what should be done with
11892the file. A typical operation is "print".
11893
11894startfile returns as soon as the associated application is launched.
11895There is no option to wait for the application to close, and no way
11896to retrieve the application's exit status.
11897
11898The filepath is relative to the current directory. If you want to use
11899an absolute path, make sure the first character is not a slash ("/");
11900the underlying Win32 ShellExecute function doesn't work if it is.
11901[clinic start generated code]*/
11902
11903static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +020011904os_startfile_impl(PyObject *module, path_t *filepath,
11905 const Py_UNICODE *operation)
Serhiy Storchaka279f4462019-09-14 12:24:05 +030011906/*[clinic end generated code: output=66dc311c94d50797 input=c940888a5390f039]*/
Steve Dowercc16be82016-09-08 10:35:16 -070011907{
11908 HINSTANCE rc;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011909
11910 if(!check_ShellExecute()) {
11911 /* If the OS doesn't have ShellExecute, return a
11912 NotImplementedError. */
11913 return PyErr_Format(PyExc_NotImplementedError,
11914 "startfile not available on this platform");
11915 }
11916
Saiyang Gou7514f4f2020-02-12 23:47:42 -080011917 if (PySys_Audit("os.startfile", "Ou", filepath->object, operation) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -080011918 return NULL;
11919 }
11920
Victor Stinner8c62be82010-05-06 00:08:46 +000011921 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -070011922 rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
Steve Dower7d0e0c92015-01-24 08:18:24 -080011923 NULL, NULL, SW_SHOWNORMAL);
Victor Stinner8c62be82010-05-06 00:08:46 +000011924 Py_END_ALLOW_THREADS
11925
Victor Stinner8c62be82010-05-06 00:08:46 +000011926 if (rc <= (HINSTANCE)32) {
Steve Dowercc16be82016-09-08 10:35:16 -070011927 win32_error_object("startfile", filepath->object);
Victor Stinnereb5657a2011-09-30 01:44:27 +020011928 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000011929 }
Steve Dowercc16be82016-09-08 10:35:16 -070011930 Py_RETURN_NONE;
Tim Petersf58a7aa2000-09-22 10:05:54 +000011931}
Larry Hastings2f936352014-08-05 14:04:04 +100011932#endif /* MS_WINDOWS */
11933
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011934
Martin v. Löwis438b5342002-12-27 10:16:42 +000011935#ifdef HAVE_GETLOADAVG
Larry Hastings2f936352014-08-05 14:04:04 +100011936/*[clinic input]
11937os.getloadavg
11938
11939Return average recent system load information.
11940
11941Return the number of processes in the system run queue averaged over
11942the last 1, 5, and 15 minutes as a tuple of three floats.
11943Raises OSError if the load average was unobtainable.
11944[clinic start generated code]*/
11945
Larry Hastings2f936352014-08-05 14:04:04 +100011946static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011947os_getloadavg_impl(PyObject *module)
11948/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
Martin v. Löwis438b5342002-12-27 10:16:42 +000011949{
11950 double loadavg[3];
Martin v. Löwis438b5342002-12-27 10:16:42 +000011951 if (getloadavg(loadavg, 3)!=3) {
Stefan Krah0e803b32010-11-26 16:16:47 +000011952 PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
11953 return NULL;
Martin v. Löwis438b5342002-12-27 10:16:42 +000011954 } else
Stefan Krah0e803b32010-11-26 16:16:47 +000011955 return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
Martin v. Löwis438b5342002-12-27 10:16:42 +000011956}
Larry Hastings2f936352014-08-05 14:04:04 +100011957#endif /* HAVE_GETLOADAVG */
Martin v. Löwis438b5342002-12-27 10:16:42 +000011958
Larry Hastings2f936352014-08-05 14:04:04 +100011959
11960/*[clinic input]
11961os.device_encoding
11962 fd: int
11963
11964Return a string describing the encoding of a terminal's file descriptor.
11965
11966The file descriptor must be attached to a terminal.
11967If the device is not a terminal, return None.
11968[clinic start generated code]*/
11969
Larry Hastings2f936352014-08-05 14:04:04 +100011970static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011971os_device_encoding_impl(PyObject *module, int fd)
11972/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011973{
Brett Cannonefb00c02012-02-29 18:31:31 -050011974 return _Py_device_encoding(fd);
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +000011975}
11976
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011977
Larry Hastings2f936352014-08-05 14:04:04 +100011978#ifdef HAVE_SETRESUID
11979/*[clinic input]
11980os.setresuid
11981
11982 ruid: uid_t
11983 euid: uid_t
11984 suid: uid_t
11985 /
11986
11987Set the current process's real, effective, and saved user ids.
11988[clinic start generated code]*/
11989
Larry Hastings2f936352014-08-05 14:04:04 +100011990static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011991os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
11992/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011993{
Victor Stinner8c62be82010-05-06 00:08:46 +000011994 if (setresuid(ruid, euid, suid) < 0)
11995 return posix_error();
11996 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011997}
Larry Hastings2f936352014-08-05 14:04:04 +100011998#endif /* HAVE_SETRESUID */
11999
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012000
12001#ifdef HAVE_SETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100012002/*[clinic input]
12003os.setresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012004
Larry Hastings2f936352014-08-05 14:04:04 +100012005 rgid: gid_t
12006 egid: gid_t
12007 sgid: gid_t
12008 /
12009
12010Set the current process's real, effective, and saved group ids.
12011[clinic start generated code]*/
12012
Larry Hastings2f936352014-08-05 14:04:04 +100012013static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012014os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
12015/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012016{
Victor Stinner8c62be82010-05-06 00:08:46 +000012017 if (setresgid(rgid, egid, sgid) < 0)
12018 return posix_error();
12019 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012020}
Larry Hastings2f936352014-08-05 14:04:04 +100012021#endif /* HAVE_SETRESGID */
12022
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012023
12024#ifdef HAVE_GETRESUID
Larry Hastings2f936352014-08-05 14:04:04 +100012025/*[clinic input]
12026os.getresuid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012027
Larry Hastings2f936352014-08-05 14:04:04 +100012028Return a tuple of the current process's real, effective, and saved user ids.
12029[clinic start generated code]*/
12030
Larry Hastings2f936352014-08-05 14:04:04 +100012031static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012032os_getresuid_impl(PyObject *module)
12033/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012034{
Victor Stinner8c62be82010-05-06 00:08:46 +000012035 uid_t ruid, euid, suid;
Victor Stinner8c62be82010-05-06 00:08:46 +000012036 if (getresuid(&ruid, &euid, &suid) < 0)
12037 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020012038 return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
12039 _PyLong_FromUid(euid),
12040 _PyLong_FromUid(suid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012041}
Larry Hastings2f936352014-08-05 14:04:04 +100012042#endif /* HAVE_GETRESUID */
12043
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012044
12045#ifdef HAVE_GETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100012046/*[clinic input]
12047os.getresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012048
Larry Hastings2f936352014-08-05 14:04:04 +100012049Return a tuple of the current process's real, effective, and saved group ids.
12050[clinic start generated code]*/
12051
Larry Hastings2f936352014-08-05 14:04:04 +100012052static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012053os_getresgid_impl(PyObject *module)
12054/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012055{
12056 gid_t rgid, egid, sgid;
Victor Stinner8c62be82010-05-06 00:08:46 +000012057 if (getresgid(&rgid, &egid, &sgid) < 0)
12058 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020012059 return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
12060 _PyLong_FromGid(egid),
12061 _PyLong_FromGid(sgid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012062}
Larry Hastings2f936352014-08-05 14:04:04 +100012063#endif /* HAVE_GETRESGID */
12064
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012065
Benjamin Peterson9428d532011-09-14 11:45:52 -040012066#ifdef USE_XATTRS
Larry Hastings2f936352014-08-05 14:04:04 +100012067/*[clinic input]
12068os.getxattr
Benjamin Peterson799bd802011-08-31 22:15:17 -040012069
Larry Hastings2f936352014-08-05 14:04:04 +100012070 path: path_t(allow_fd=True)
12071 attribute: path_t
12072 *
12073 follow_symlinks: bool = True
12074
12075Return the value of extended attribute attribute on path.
12076
BNMetricsb9427072018-11-02 15:20:19 +000012077path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012078If follow_symlinks is False, and the last element of the path is a symbolic
12079 link, getxattr will examine the symbolic link itself instead of the file
12080 the link points to.
12081
12082[clinic start generated code]*/
12083
Larry Hastings2f936352014-08-05 14:04:04 +100012084static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012085os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012086 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012087/*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012088{
12089 Py_ssize_t i;
12090 PyObject *buffer = NULL;
12091
12092 if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
12093 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012094
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012095 if (PySys_Audit("os.getxattr", "OO", path->object, attribute->object) < 0) {
12096 return NULL;
12097 }
12098
Larry Hastings9cf065c2012-06-22 16:30:09 -070012099 for (i = 0; ; i++) {
12100 void *ptr;
12101 ssize_t result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012102 static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
Larry Hastings9cf065c2012-06-22 16:30:09 -070012103 Py_ssize_t buffer_size = buffer_sizes[i];
12104 if (!buffer_size) {
Larry Hastings2f936352014-08-05 14:04:04 +100012105 path_error(path);
12106 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012107 }
12108 buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
12109 if (!buffer)
Larry Hastings2f936352014-08-05 14:04:04 +100012110 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012111 ptr = PyBytes_AS_STRING(buffer);
Benjamin Peterson799bd802011-08-31 22:15:17 -040012112
Larry Hastings9cf065c2012-06-22 16:30:09 -070012113 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012114 if (path->fd >= 0)
12115 result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012116 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100012117 result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012118 else
Larry Hastings2f936352014-08-05 14:04:04 +100012119 result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012120 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012121
Larry Hastings9cf065c2012-06-22 16:30:09 -070012122 if (result < 0) {
12123 Py_DECREF(buffer);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012124 if (errno == ERANGE)
12125 continue;
Larry Hastings2f936352014-08-05 14:04:04 +100012126 path_error(path);
12127 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012128 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012129
Larry Hastings9cf065c2012-06-22 16:30:09 -070012130 if (result != buffer_size) {
12131 /* Can only shrink. */
12132 _PyBytes_Resize(&buffer, result);
12133 }
12134 break;
12135 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012136
Larry Hastings9cf065c2012-06-22 16:30:09 -070012137 return buffer;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012138}
12139
Larry Hastings2f936352014-08-05 14:04:04 +100012140
12141/*[clinic input]
12142os.setxattr
12143
12144 path: path_t(allow_fd=True)
12145 attribute: path_t
12146 value: Py_buffer
12147 flags: int = 0
12148 *
12149 follow_symlinks: bool = True
12150
12151Set extended attribute attribute on path to value.
12152
BNMetricsb9427072018-11-02 15:20:19 +000012153path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012154If follow_symlinks is False, and the last element of the path is a symbolic
12155 link, setxattr will modify the symbolic link itself instead of the file
12156 the link points to.
12157
12158[clinic start generated code]*/
12159
Benjamin Peterson799bd802011-08-31 22:15:17 -040012160static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012161os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012162 Py_buffer *value, int flags, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012163/*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
Benjamin Peterson799bd802011-08-31 22:15:17 -040012164{
Larry Hastings2f936352014-08-05 14:04:04 +100012165 ssize_t result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012166
Larry Hastings2f936352014-08-05 14:04:04 +100012167 if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
Benjamin Peterson799bd802011-08-31 22:15:17 -040012168 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012169
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012170 if (PySys_Audit("os.setxattr", "OOy#i", path->object, attribute->object,
12171 value->buf, value->len, flags) < 0) {
12172 return NULL;
12173 }
12174
Benjamin Peterson799bd802011-08-31 22:15:17 -040012175 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012176 if (path->fd > -1)
12177 result = fsetxattr(path->fd, attribute->narrow,
12178 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012179 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100012180 result = setxattr(path->narrow, attribute->narrow,
12181 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012182 else
Larry Hastings2f936352014-08-05 14:04:04 +100012183 result = lsetxattr(path->narrow, attribute->narrow,
12184 value->buf, value->len, flags);
Benjamin Peterson799bd802011-08-31 22:15:17 -040012185 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012186
Larry Hastings9cf065c2012-06-22 16:30:09 -070012187 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100012188 path_error(path);
12189 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012190 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012191
Larry Hastings2f936352014-08-05 14:04:04 +100012192 Py_RETURN_NONE;
12193}
12194
12195
12196/*[clinic input]
12197os.removexattr
12198
12199 path: path_t(allow_fd=True)
12200 attribute: path_t
12201 *
12202 follow_symlinks: bool = True
12203
12204Remove extended attribute attribute on path.
12205
BNMetricsb9427072018-11-02 15:20:19 +000012206path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012207If follow_symlinks is False, and the last element of the path is a symbolic
12208 link, removexattr will modify the symbolic link itself instead of the file
12209 the link points to.
12210
12211[clinic start generated code]*/
12212
Larry Hastings2f936352014-08-05 14:04:04 +100012213static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012214os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012215 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012216/*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012217{
12218 ssize_t result;
12219
12220 if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
12221 return NULL;
12222
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012223 if (PySys_Audit("os.removexattr", "OO", path->object, attribute->object) < 0) {
12224 return NULL;
12225 }
12226
Larry Hastings2f936352014-08-05 14:04:04 +100012227 Py_BEGIN_ALLOW_THREADS;
12228 if (path->fd > -1)
12229 result = fremovexattr(path->fd, attribute->narrow);
12230 else if (follow_symlinks)
12231 result = removexattr(path->narrow, attribute->narrow);
12232 else
12233 result = lremovexattr(path->narrow, attribute->narrow);
12234 Py_END_ALLOW_THREADS;
12235
12236 if (result) {
12237 return path_error(path);
12238 }
12239
12240 Py_RETURN_NONE;
12241}
12242
12243
12244/*[clinic input]
12245os.listxattr
12246
12247 path: path_t(allow_fd=True, nullable=True) = None
12248 *
12249 follow_symlinks: bool = True
12250
12251Return a list of extended attributes on path.
12252
BNMetricsb9427072018-11-02 15:20:19 +000012253path may be either None, a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012254if path is None, listxattr will examine the current directory.
12255If follow_symlinks is False, and the last element of the path is a symbolic
12256 link, listxattr will examine the symbolic link itself instead of the file
12257 the link points to.
12258[clinic start generated code]*/
12259
Larry Hastings2f936352014-08-05 14:04:04 +100012260static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012261os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012262/*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012263{
Larry Hastings9cf065c2012-06-22 16:30:09 -070012264 Py_ssize_t i;
12265 PyObject *result = NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100012266 const char *name;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012267 char *buffer = NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012268
Larry Hastings2f936352014-08-05 14:04:04 +100012269 if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
Larry Hastings9cf065c2012-06-22 16:30:09 -070012270 goto exit;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012271
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012272 if (PySys_Audit("os.listxattr", "(O)",
12273 path->object ? path->object : Py_None) < 0) {
12274 return NULL;
12275 }
12276
Larry Hastings2f936352014-08-05 14:04:04 +100012277 name = path->narrow ? path->narrow : ".";
12278
Larry Hastings9cf065c2012-06-22 16:30:09 -070012279 for (i = 0; ; i++) {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012280 const char *start, *trace, *end;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012281 ssize_t length;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012282 static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
Larry Hastings9cf065c2012-06-22 16:30:09 -070012283 Py_ssize_t buffer_size = buffer_sizes[i];
12284 if (!buffer_size) {
Christian Heimes3b9493b2012-09-23 16:11:15 +020012285 /* ERANGE */
Larry Hastings2f936352014-08-05 14:04:04 +100012286 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012287 break;
12288 }
12289 buffer = PyMem_MALLOC(buffer_size);
12290 if (!buffer) {
12291 PyErr_NoMemory();
12292 break;
12293 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012294
Larry Hastings9cf065c2012-06-22 16:30:09 -070012295 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012296 if (path->fd > -1)
12297 length = flistxattr(path->fd, buffer, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012298 else if (follow_symlinks)
12299 length = listxattr(name, buffer, buffer_size);
12300 else
12301 length = llistxattr(name, buffer, buffer_size);
12302 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012303
Larry Hastings9cf065c2012-06-22 16:30:09 -070012304 if (length < 0) {
Antoine Pitrou7f987392013-05-13 19:46:29 +020012305 if (errno == ERANGE) {
12306 PyMem_FREE(buffer);
Benjamin Petersondedac522013-05-13 19:55:40 -050012307 buffer = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012308 continue;
Antoine Pitrou7f987392013-05-13 19:46:29 +020012309 }
Larry Hastings2f936352014-08-05 14:04:04 +100012310 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012311 break;
12312 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012313
Larry Hastings9cf065c2012-06-22 16:30:09 -070012314 result = PyList_New(0);
12315 if (!result) {
12316 goto exit;
12317 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012318
Larry Hastings9cf065c2012-06-22 16:30:09 -070012319 end = buffer + length;
12320 for (trace = start = buffer; trace != end; trace++) {
12321 if (!*trace) {
12322 int error;
12323 PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
12324 trace - start);
12325 if (!attribute) {
12326 Py_DECREF(result);
12327 result = NULL;
12328 goto exit;
12329 }
12330 error = PyList_Append(result, attribute);
12331 Py_DECREF(attribute);
12332 if (error) {
12333 Py_DECREF(result);
12334 result = NULL;
12335 goto exit;
12336 }
12337 start = trace + 1;
12338 }
12339 }
12340 break;
12341 }
12342exit:
Larry Hastings9cf065c2012-06-22 16:30:09 -070012343 if (buffer)
12344 PyMem_FREE(buffer);
12345 return result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012346}
Benjamin Peterson9428d532011-09-14 11:45:52 -040012347#endif /* USE_XATTRS */
Benjamin Peterson799bd802011-08-31 22:15:17 -040012348
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012349
Larry Hastings2f936352014-08-05 14:04:04 +100012350/*[clinic input]
12351os.urandom
12352
12353 size: Py_ssize_t
12354 /
12355
12356Return a bytes object containing random bytes suitable for cryptographic use.
12357[clinic start generated code]*/
12358
Larry Hastings2f936352014-08-05 14:04:04 +100012359static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012360os_urandom_impl(PyObject *module, Py_ssize_t size)
12361/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012362{
12363 PyObject *bytes;
12364 int result;
12365
Georg Brandl2fb477c2012-02-21 00:33:36 +010012366 if (size < 0)
12367 return PyErr_Format(PyExc_ValueError,
12368 "negative argument not allowed");
Larry Hastings2f936352014-08-05 14:04:04 +100012369 bytes = PyBytes_FromStringAndSize(NULL, size);
12370 if (bytes == NULL)
Georg Brandl2fb477c2012-02-21 00:33:36 +010012371 return NULL;
12372
Victor Stinnere66987e2016-09-06 16:33:52 -070012373 result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
Larry Hastings2f936352014-08-05 14:04:04 +100012374 if (result == -1) {
12375 Py_DECREF(bytes);
Georg Brandl2fb477c2012-02-21 00:33:36 +010012376 return NULL;
12377 }
Larry Hastings2f936352014-08-05 14:04:04 +100012378 return bytes;
Georg Brandl2fb477c2012-02-21 00:33:36 +010012379}
12380
Zackery Spytz43fdbd22019-05-29 13:57:07 -060012381#ifdef HAVE_MEMFD_CREATE
12382/*[clinic input]
12383os.memfd_create
12384
12385 name: FSConverter
12386 flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
12387
12388[clinic start generated code]*/
12389
12390static PyObject *
12391os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
12392/*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
12393{
12394 int fd;
12395 const char *bytes = PyBytes_AS_STRING(name);
12396 Py_BEGIN_ALLOW_THREADS
12397 fd = memfd_create(bytes, flags);
12398 Py_END_ALLOW_THREADS
12399 if (fd == -1) {
12400 return PyErr_SetFromErrno(PyExc_OSError);
12401 }
12402 return PyLong_FromLong(fd);
12403}
12404#endif
12405
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012406/* Terminal size querying */
12407
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012408PyDoc_STRVAR(TerminalSize_docstring,
12409 "A tuple of (columns, lines) for holding terminal window size");
12410
12411static PyStructSequence_Field TerminalSize_fields[] = {
12412 {"columns", "width of the terminal window in characters"},
12413 {"lines", "height of the terminal window in characters"},
12414 {NULL, NULL}
12415};
12416
12417static PyStructSequence_Desc TerminalSize_desc = {
12418 "os.terminal_size",
12419 TerminalSize_docstring,
12420 TerminalSize_fields,
12421 2,
12422};
12423
12424#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
Serhiy Storchaka2b560312020-04-18 19:14:10 +030012425/*[clinic input]
12426os.get_terminal_size
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012427
Serhiy Storchaka2b560312020-04-18 19:14:10 +030012428 fd: int(c_default="fileno(stdout)", py_default="<unrepresentable>") = -1
12429 /
12430
12431Return the size of the terminal window as (columns, lines).
12432
12433The optional argument fd (default standard output) specifies
12434which file descriptor should be queried.
12435
12436If the file descriptor is not connected to a terminal, an OSError
12437is thrown.
12438
12439This function will only be defined if an implementation is
12440available for this system.
12441
12442shutil.get_terminal_size is the high-level function which should
12443normally be used, os.get_terminal_size is the low-level implementation.
12444[clinic start generated code]*/
12445
12446static PyObject *
12447os_get_terminal_size_impl(PyObject *module, int fd)
12448/*[clinic end generated code: output=fbab93acef980508 input=ead5679b82ddb920]*/
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012449{
12450 int columns, lines;
12451 PyObject *termsize;
12452
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012453 /* Under some conditions stdout may not be connected and
12454 * fileno(stdout) may point to an invalid file descriptor. For example
12455 * GUI apps don't have valid standard streams by default.
12456 *
12457 * If this happens, and the optional fd argument is not present,
12458 * the ioctl below will fail returning EBADF. This is what we want.
12459 */
12460
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012461#ifdef TERMSIZE_USE_IOCTL
12462 {
12463 struct winsize w;
12464 if (ioctl(fd, TIOCGWINSZ, &w))
12465 return PyErr_SetFromErrno(PyExc_OSError);
12466 columns = w.ws_col;
12467 lines = w.ws_row;
12468 }
12469#endif /* TERMSIZE_USE_IOCTL */
12470
12471#ifdef TERMSIZE_USE_CONIO
12472 {
12473 DWORD nhandle;
12474 HANDLE handle;
12475 CONSOLE_SCREEN_BUFFER_INFO csbi;
12476 switch (fd) {
12477 case 0: nhandle = STD_INPUT_HANDLE;
12478 break;
12479 case 1: nhandle = STD_OUTPUT_HANDLE;
12480 break;
12481 case 2: nhandle = STD_ERROR_HANDLE;
12482 break;
12483 default:
12484 return PyErr_Format(PyExc_ValueError, "bad file descriptor");
12485 }
12486 handle = GetStdHandle(nhandle);
12487 if (handle == NULL)
12488 return PyErr_Format(PyExc_OSError, "handle cannot be retrieved");
12489 if (handle == INVALID_HANDLE_VALUE)
12490 return PyErr_SetFromWindowsErr(0);
12491
12492 if (!GetConsoleScreenBufferInfo(handle, &csbi))
12493 return PyErr_SetFromWindowsErr(0);
12494
12495 columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
12496 lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
12497 }
12498#endif /* TERMSIZE_USE_CONIO */
12499
Serhiy Storchaka2b560312020-04-18 19:14:10 +030012500 PyObject *TerminalSizeType = get_posix_state(module)->TerminalSizeType;
Eddie Elizondob3966632019-11-05 07:16:14 -080012501 termsize = PyStructSequence_New((PyTypeObject *)TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012502 if (termsize == NULL)
12503 return NULL;
12504 PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
12505 PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
12506 if (PyErr_Occurred()) {
12507 Py_DECREF(termsize);
12508 return NULL;
12509 }
12510 return termsize;
12511}
12512#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
12513
Larry Hastings2f936352014-08-05 14:04:04 +100012514
12515/*[clinic input]
12516os.cpu_count
12517
Charles-François Natali80d62e62015-08-13 20:37:08 +010012518Return the number of CPUs in the system; return None if indeterminable.
12519
12520This number is not equivalent to the number of CPUs the current process can
12521use. The number of usable CPUs can be obtained with
12522``len(os.sched_getaffinity(0))``
Larry Hastings2f936352014-08-05 14:04:04 +100012523[clinic start generated code]*/
12524
Larry Hastings2f936352014-08-05 14:04:04 +100012525static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012526os_cpu_count_impl(PyObject *module)
Serhiy Storchaka2954f832016-07-07 18:20:03 +030012527/*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012528{
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012529 int ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012530#ifdef MS_WINDOWS
Steve Doweraa929272019-09-11 16:15:39 +010012531 ncpu = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012532#elif defined(__hpux)
12533 ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
12534#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
12535 ncpu = sysconf(_SC_NPROCESSORS_ONLN);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012536#elif defined(__DragonFly__) || \
12537 defined(__OpenBSD__) || \
12538 defined(__FreeBSD__) || \
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012539 defined(__NetBSD__) || \
12540 defined(__APPLE__)
Charles-Francois Natali7c4f8da2013-05-20 17:40:32 +020012541 int mib[2];
12542 size_t len = sizeof(ncpu);
12543 mib[0] = CTL_HW;
12544 mib[1] = HW_NCPU;
12545 if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
12546 ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012547#endif
12548 if (ncpu >= 1)
12549 return PyLong_FromLong(ncpu);
12550 else
12551 Py_RETURN_NONE;
12552}
12553
Victor Stinnerdaf45552013-08-28 00:53:59 +020012554
Larry Hastings2f936352014-08-05 14:04:04 +100012555/*[clinic input]
12556os.get_inheritable -> bool
12557
12558 fd: int
12559 /
12560
12561Get the close-on-exe flag of the specified file descriptor.
12562[clinic start generated code]*/
12563
Larry Hastings2f936352014-08-05 14:04:04 +100012564static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012565os_get_inheritable_impl(PyObject *module, int fd)
12566/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012567{
Steve Dower8fc89802015-04-12 00:26:27 -040012568 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -040012569 _Py_BEGIN_SUPPRESS_IPH
12570 return_value = _Py_get_inheritable(fd);
12571 _Py_END_SUPPRESS_IPH
12572 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +100012573}
12574
12575
12576/*[clinic input]
12577os.set_inheritable
12578 fd: int
12579 inheritable: int
12580 /
12581
12582Set the inheritable flag of the specified file descriptor.
12583[clinic start generated code]*/
12584
Larry Hastings2f936352014-08-05 14:04:04 +100012585static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012586os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
12587/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
Victor Stinnerdaf45552013-08-28 00:53:59 +020012588{
Steve Dower8fc89802015-04-12 00:26:27 -040012589 int result;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012590
Steve Dower8fc89802015-04-12 00:26:27 -040012591 _Py_BEGIN_SUPPRESS_IPH
12592 result = _Py_set_inheritable(fd, inheritable, NULL);
12593 _Py_END_SUPPRESS_IPH
12594 if (result < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +020012595 return NULL;
12596 Py_RETURN_NONE;
12597}
12598
12599
12600#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100012601/*[clinic input]
12602os.get_handle_inheritable -> bool
Benjamin Petersonca470632016-09-06 13:47:26 -070012603 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012604 /
Victor Stinnerdaf45552013-08-28 00:53:59 +020012605
Larry Hastings2f936352014-08-05 14:04:04 +100012606Get the close-on-exe flag of the specified file descriptor.
12607[clinic start generated code]*/
12608
Larry Hastings2f936352014-08-05 14:04:04 +100012609static int
Benjamin Petersonca470632016-09-06 13:47:26 -070012610os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
Victor Stinner581139c2016-09-06 15:54:20 -070012611/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012612{
12613 DWORD flags;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012614
12615 if (!GetHandleInformation((HANDLE)handle, &flags)) {
12616 PyErr_SetFromWindowsErr(0);
Larry Hastings2f936352014-08-05 14:04:04 +100012617 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012618 }
12619
Larry Hastings2f936352014-08-05 14:04:04 +100012620 return flags & HANDLE_FLAG_INHERIT;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012621}
12622
Victor Stinnerdaf45552013-08-28 00:53:59 +020012623
Larry Hastings2f936352014-08-05 14:04:04 +100012624/*[clinic input]
12625os.set_handle_inheritable
Benjamin Petersonca470632016-09-06 13:47:26 -070012626 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012627 inheritable: bool
12628 /
12629
12630Set the inheritable flag of the specified handle.
12631[clinic start generated code]*/
12632
Larry Hastings2f936352014-08-05 14:04:04 +100012633static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -070012634os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
Larry Hastings89964c42015-04-14 18:07:59 -040012635 int inheritable)
Victor Stinner581139c2016-09-06 15:54:20 -070012636/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012637{
12638 DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012639 if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
12640 PyErr_SetFromWindowsErr(0);
12641 return NULL;
12642 }
12643 Py_RETURN_NONE;
12644}
Larry Hastings2f936352014-08-05 14:04:04 +100012645#endif /* MS_WINDOWS */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012646
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012647#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012648/*[clinic input]
12649os.get_blocking -> bool
12650 fd: int
12651 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012652
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012653Get the blocking mode of the file descriptor.
12654
12655Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
12656[clinic start generated code]*/
12657
12658static int
12659os_get_blocking_impl(PyObject *module, int fd)
12660/*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012661{
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012662 int blocking;
12663
Steve Dower8fc89802015-04-12 00:26:27 -040012664 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012665 blocking = _Py_get_blocking(fd);
Steve Dower8fc89802015-04-12 00:26:27 -040012666 _Py_END_SUPPRESS_IPH
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012667 return blocking;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012668}
12669
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012670/*[clinic input]
12671os.set_blocking
12672 fd: int
12673 blocking: bool(accept={int})
12674 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012675
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012676Set the blocking mode of the specified file descriptor.
12677
12678Set the O_NONBLOCK flag if blocking is False,
12679clear the O_NONBLOCK flag otherwise.
12680[clinic start generated code]*/
12681
12682static PyObject *
12683os_set_blocking_impl(PyObject *module, int fd, int blocking)
12684/*[clinic end generated code: output=384eb43aa0762a9d input=bf5c8efdc5860ff3]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012685{
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012686 int result;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012687
Steve Dower8fc89802015-04-12 00:26:27 -040012688 _Py_BEGIN_SUPPRESS_IPH
12689 result = _Py_set_blocking(fd, blocking);
12690 _Py_END_SUPPRESS_IPH
12691 if (result < 0)
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012692 return NULL;
12693 Py_RETURN_NONE;
12694}
12695#endif /* !MS_WINDOWS */
12696
12697
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012698/*[clinic input]
Eddie Elizondob3966632019-11-05 07:16:14 -080012699class os.DirEntry "DirEntry *" "DirEntryType"
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012700[clinic start generated code]*/
Eddie Elizondob3966632019-11-05 07:16:14 -080012701/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3c18c7a448247980]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012702
12703typedef struct {
12704 PyObject_HEAD
12705 PyObject *name;
12706 PyObject *path;
12707 PyObject *stat;
12708 PyObject *lstat;
12709#ifdef MS_WINDOWS
12710 struct _Py_stat_struct win32_lstat;
Victor Stinner0f6d7332017-03-09 17:34:28 +010012711 uint64_t win32_file_index;
Victor Stinner6036e442015-03-08 01:58:04 +010012712 int got_file_index;
12713#else /* POSIX */
Victor Stinner35a97c02015-03-08 02:59:09 +010012714#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012715 unsigned char d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012716#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012717 ino_t d_ino;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012718 int dir_fd;
Victor Stinner6036e442015-03-08 01:58:04 +010012719#endif
12720} DirEntry;
12721
Eddie Elizondob3966632019-11-05 07:16:14 -080012722static PyObject *
12723_disabled_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
12724{
12725 PyErr_Format(PyExc_TypeError,
12726 "cannot create '%.100s' instances", _PyType_Name(type));
12727 return NULL;
12728}
12729
Victor Stinner6036e442015-03-08 01:58:04 +010012730static void
12731DirEntry_dealloc(DirEntry *entry)
12732{
Eddie Elizondob3966632019-11-05 07:16:14 -080012733 PyTypeObject *tp = Py_TYPE(entry);
Victor Stinner6036e442015-03-08 01:58:04 +010012734 Py_XDECREF(entry->name);
12735 Py_XDECREF(entry->path);
12736 Py_XDECREF(entry->stat);
12737 Py_XDECREF(entry->lstat);
Eddie Elizondob3966632019-11-05 07:16:14 -080012738 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
12739 free_func(entry);
12740 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010012741}
12742
12743/* Forward reference */
12744static int
12745DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits);
12746
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012747/*[clinic input]
12748os.DirEntry.is_symlink -> bool
12749
12750Return True if the entry is a symbolic link; cached per entry.
12751[clinic start generated code]*/
12752
Victor Stinner6036e442015-03-08 01:58:04 +010012753static int
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012754os_DirEntry_is_symlink_impl(DirEntry *self)
12755/*[clinic end generated code: output=42244667d7bcfc25 input=1605a1b4b96976c3]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012756{
12757#ifdef MS_WINDOWS
12758 return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
Victor Stinner35a97c02015-03-08 02:59:09 +010012759#elif defined(HAVE_DIRENT_D_TYPE)
12760 /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010012761 if (self->d_type != DT_UNKNOWN)
12762 return self->d_type == DT_LNK;
12763 else
12764 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner35a97c02015-03-08 02:59:09 +010012765#else
12766 /* POSIX without d_type */
12767 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner6036e442015-03-08 01:58:04 +010012768#endif
12769}
12770
12771static PyObject *
Victor Stinner6036e442015-03-08 01:58:04 +010012772DirEntry_fetch_stat(DirEntry *self, int follow_symlinks)
12773{
12774 int result;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012775 STRUCT_STAT st;
12776 PyObject *ub;
Victor Stinner6036e442015-03-08 01:58:04 +010012777
12778#ifdef MS_WINDOWS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012779 if (!PyUnicode_FSDecoder(self->path, &ub))
12780 return NULL;
12781 const wchar_t *path = PyUnicode_AsUnicode(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012782#else /* POSIX */
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012783 if (!PyUnicode_FSConverter(self->path, &ub))
12784 return NULL;
12785 const char *path = PyBytes_AS_STRING(ub);
12786 if (self->dir_fd != DEFAULT_DIR_FD) {
12787#ifdef HAVE_FSTATAT
12788 result = fstatat(self->dir_fd, path, &st,
12789 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
12790#else
12791 PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
12792 return NULL;
12793#endif /* HAVE_FSTATAT */
12794 }
12795 else
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012796#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012797 {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012798 if (follow_symlinks)
12799 result = STAT(path, &st);
12800 else
12801 result = LSTAT(path, &st);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012802 }
12803 Py_DECREF(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012804
12805 if (result != 0)
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012806 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012807
12808 return _pystat_fromstructstat(&st);
12809}
12810
12811static PyObject *
12812DirEntry_get_lstat(DirEntry *self)
12813{
12814 if (!self->lstat) {
12815#ifdef MS_WINDOWS
12816 self->lstat = _pystat_fromstructstat(&self->win32_lstat);
12817#else /* POSIX */
12818 self->lstat = DirEntry_fetch_stat(self, 0);
12819#endif
12820 }
12821 Py_XINCREF(self->lstat);
12822 return self->lstat;
12823}
12824
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012825/*[clinic input]
12826os.DirEntry.stat
12827 *
12828 follow_symlinks: bool = True
12829
12830Return stat_result object for the entry; cached per entry.
12831[clinic start generated code]*/
12832
Victor Stinner6036e442015-03-08 01:58:04 +010012833static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012834os_DirEntry_stat_impl(DirEntry *self, int follow_symlinks)
12835/*[clinic end generated code: output=008593b3a6d01305 input=280d14c1d6f1d00d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012836{
12837 if (!follow_symlinks)
12838 return DirEntry_get_lstat(self);
12839
12840 if (!self->stat) {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012841 int result = os_DirEntry_is_symlink_impl(self);
Victor Stinner6036e442015-03-08 01:58:04 +010012842 if (result == -1)
12843 return NULL;
12844 else if (result)
12845 self->stat = DirEntry_fetch_stat(self, 1);
12846 else
12847 self->stat = DirEntry_get_lstat(self);
12848 }
12849
12850 Py_XINCREF(self->stat);
12851 return self->stat;
12852}
12853
Victor Stinner6036e442015-03-08 01:58:04 +010012854/* Set exception and return -1 on error, 0 for False, 1 for True */
12855static int
12856DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
12857{
12858 PyObject *stat = NULL;
12859 PyObject *st_mode = NULL;
12860 long mode;
12861 int result;
Victor Stinner35a97c02015-03-08 02:59:09 +010012862#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012863 int is_symlink;
12864 int need_stat;
Victor Stinner35a97c02015-03-08 02:59:09 +010012865#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012866#ifdef MS_WINDOWS
12867 unsigned long dir_bits;
12868#endif
12869
12870#ifdef MS_WINDOWS
12871 is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
12872 need_stat = follow_symlinks && is_symlink;
Victor Stinner35a97c02015-03-08 02:59:09 +010012873#elif defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012874 is_symlink = self->d_type == DT_LNK;
12875 need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
12876#endif
12877
Victor Stinner35a97c02015-03-08 02:59:09 +010012878#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012879 if (need_stat) {
Victor Stinner35a97c02015-03-08 02:59:09 +010012880#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012881 stat = os_DirEntry_stat_impl(self, follow_symlinks);
Victor Stinner6036e442015-03-08 01:58:04 +010012882 if (!stat) {
12883 if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
12884 /* If file doesn't exist (anymore), then return False
12885 (i.e., say it's not a file/directory) */
12886 PyErr_Clear();
12887 return 0;
12888 }
12889 goto error;
12890 }
Eddie Elizondob3966632019-11-05 07:16:14 -080012891 st_mode = PyObject_GetAttr(stat, _posixstate_global->st_mode);
Victor Stinner6036e442015-03-08 01:58:04 +010012892 if (!st_mode)
12893 goto error;
12894
12895 mode = PyLong_AsLong(st_mode);
12896 if (mode == -1 && PyErr_Occurred())
12897 goto error;
12898 Py_CLEAR(st_mode);
12899 Py_CLEAR(stat);
12900 result = (mode & S_IFMT) == mode_bits;
Victor Stinner35a97c02015-03-08 02:59:09 +010012901#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012902 }
12903 else if (is_symlink) {
12904 assert(mode_bits != S_IFLNK);
12905 result = 0;
12906 }
12907 else {
12908 assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
12909#ifdef MS_WINDOWS
12910 dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
12911 if (mode_bits == S_IFDIR)
12912 result = dir_bits != 0;
12913 else
12914 result = dir_bits == 0;
12915#else /* POSIX */
12916 if (mode_bits == S_IFDIR)
12917 result = self->d_type == DT_DIR;
12918 else
12919 result = self->d_type == DT_REG;
12920#endif
12921 }
Victor Stinner35a97c02015-03-08 02:59:09 +010012922#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012923
12924 return result;
12925
12926error:
12927 Py_XDECREF(st_mode);
12928 Py_XDECREF(stat);
12929 return -1;
12930}
12931
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012932/*[clinic input]
12933os.DirEntry.is_dir -> bool
12934 *
12935 follow_symlinks: bool = True
Victor Stinner6036e442015-03-08 01:58:04 +010012936
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012937Return True if the entry is a directory; cached per entry.
12938[clinic start generated code]*/
12939
12940static int
12941os_DirEntry_is_dir_impl(DirEntry *self, int follow_symlinks)
12942/*[clinic end generated code: output=ad2e8d54365da287 input=0135232766f53f58]*/
12943{
12944 return DirEntry_test_mode(self, follow_symlinks, S_IFDIR);
Victor Stinner6036e442015-03-08 01:58:04 +010012945}
12946
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012947/*[clinic input]
12948os.DirEntry.is_file -> bool
12949 *
12950 follow_symlinks: bool = True
12951
12952Return True if the entry is a file; cached per entry.
12953[clinic start generated code]*/
12954
12955static int
12956os_DirEntry_is_file_impl(DirEntry *self, int follow_symlinks)
12957/*[clinic end generated code: output=8462ade481d8a476 input=0dc90be168b041ee]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012958{
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012959 return DirEntry_test_mode(self, follow_symlinks, S_IFREG);
Victor Stinner6036e442015-03-08 01:58:04 +010012960}
12961
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012962/*[clinic input]
12963os.DirEntry.inode
Victor Stinner6036e442015-03-08 01:58:04 +010012964
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012965Return inode of the entry; cached per entry.
12966[clinic start generated code]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012967
12968static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012969os_DirEntry_inode_impl(DirEntry *self)
12970/*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012971{
12972#ifdef MS_WINDOWS
12973 if (!self->got_file_index) {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012974 PyObject *unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012975 const wchar_t *path;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012976 STRUCT_STAT stat;
12977 int result;
Victor Stinner6036e442015-03-08 01:58:04 +010012978
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012979 if (!PyUnicode_FSDecoder(self->path, &unicode))
Victor Stinner6036e442015-03-08 01:58:04 +010012980 return NULL;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012981 path = PyUnicode_AsUnicode(unicode);
12982 result = LSTAT(path, &stat);
12983 Py_DECREF(unicode);
Victor Stinner6036e442015-03-08 01:58:04 +010012984
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012985 if (result != 0)
12986 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012987
12988 self->win32_file_index = stat.st_ino;
12989 self->got_file_index = 1;
12990 }
Victor Stinner0f6d7332017-03-09 17:34:28 +010012991 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->win32_file_index));
12992 return PyLong_FromUnsignedLongLong(self->win32_file_index);
Victor Stinner6036e442015-03-08 01:58:04 +010012993#else /* POSIX */
xdegaye50e86032017-05-22 11:15:08 +020012994 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->d_ino));
12995 return PyLong_FromUnsignedLongLong(self->d_ino);
Victor Stinner6036e442015-03-08 01:58:04 +010012996#endif
12997}
12998
12999static PyObject *
13000DirEntry_repr(DirEntry *self)
13001{
13002 return PyUnicode_FromFormat("<DirEntry %R>", self->name);
13003}
13004
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013005/*[clinic input]
13006os.DirEntry.__fspath__
13007
13008Returns the path for the entry.
13009[clinic start generated code]*/
13010
Brett Cannon96881cd2016-06-10 14:37:21 -070013011static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013012os_DirEntry___fspath___impl(DirEntry *self)
13013/*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
Brett Cannon96881cd2016-06-10 14:37:21 -070013014{
13015 Py_INCREF(self->path);
13016 return self->path;
13017}
13018
Victor Stinner6036e442015-03-08 01:58:04 +010013019static PyMemberDef DirEntry_members[] = {
13020 {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
13021 "the entry's base filename, relative to scandir() \"path\" argument"},
13022 {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
13023 "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
13024 {NULL}
13025};
13026
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013027#include "clinic/posixmodule.c.h"
13028
Victor Stinner6036e442015-03-08 01:58:04 +010013029static PyMethodDef DirEntry_methods[] = {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013030 OS_DIRENTRY_IS_DIR_METHODDEF
13031 OS_DIRENTRY_IS_FILE_METHODDEF
13032 OS_DIRENTRY_IS_SYMLINK_METHODDEF
13033 OS_DIRENTRY_STAT_METHODDEF
13034 OS_DIRENTRY_INODE_METHODDEF
13035 OS_DIRENTRY___FSPATH___METHODDEF
Batuhan Taşkayaf9dd51e2020-04-08 00:37:19 +030013036 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
13037 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Victor Stinner6036e442015-03-08 01:58:04 +010013038 {NULL}
13039};
13040
Eddie Elizondob3966632019-11-05 07:16:14 -080013041static PyType_Slot DirEntryType_slots[] = {
13042 {Py_tp_new, _disabled_new},
13043 {Py_tp_dealloc, DirEntry_dealloc},
13044 {Py_tp_repr, DirEntry_repr},
13045 {Py_tp_methods, DirEntry_methods},
13046 {Py_tp_members, DirEntry_members},
13047 {0, 0},
Victor Stinner6036e442015-03-08 01:58:04 +010013048};
13049
Eddie Elizondob3966632019-11-05 07:16:14 -080013050static PyType_Spec DirEntryType_spec = {
13051 MODNAME ".DirEntry",
13052 sizeof(DirEntry),
13053 0,
13054 Py_TPFLAGS_DEFAULT,
13055 DirEntryType_slots
13056};
13057
13058
Victor Stinner6036e442015-03-08 01:58:04 +010013059#ifdef MS_WINDOWS
13060
13061static wchar_t *
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030013062join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
Victor Stinner6036e442015-03-08 01:58:04 +010013063{
13064 Py_ssize_t path_len;
13065 Py_ssize_t size;
13066 wchar_t *result;
13067 wchar_t ch;
13068
13069 if (!path_wide) { /* Default arg: "." */
13070 path_wide = L".";
13071 path_len = 1;
13072 }
13073 else {
13074 path_len = wcslen(path_wide);
13075 }
13076
13077 /* The +1's are for the path separator and the NUL */
13078 size = path_len + 1 + wcslen(filename) + 1;
13079 result = PyMem_New(wchar_t, size);
13080 if (!result) {
13081 PyErr_NoMemory();
13082 return NULL;
13083 }
13084 wcscpy(result, path_wide);
13085 if (path_len > 0) {
13086 ch = result[path_len - 1];
13087 if (ch != SEP && ch != ALTSEP && ch != L':')
13088 result[path_len++] = SEP;
13089 wcscpy(result + path_len, filename);
13090 }
13091 return result;
13092}
13093
13094static PyObject *
13095DirEntry_from_find_data(path_t *path, WIN32_FIND_DATAW *dataW)
13096{
13097 DirEntry *entry;
13098 BY_HANDLE_FILE_INFORMATION file_info;
13099 ULONG reparse_tag;
13100 wchar_t *joined_path;
13101
Eddie Elizondob3966632019-11-05 07:16:14 -080013102 PyObject *DirEntryType = _posixstate_global->DirEntryType;
13103 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010013104 if (!entry)
13105 return NULL;
13106 entry->name = NULL;
13107 entry->path = NULL;
13108 entry->stat = NULL;
13109 entry->lstat = NULL;
13110 entry->got_file_index = 0;
13111
13112 entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
13113 if (!entry->name)
13114 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070013115 if (path->narrow) {
13116 Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
13117 if (!entry->name)
13118 goto error;
13119 }
Victor Stinner6036e442015-03-08 01:58:04 +010013120
13121 joined_path = join_path_filenameW(path->wide, dataW->cFileName);
13122 if (!joined_path)
13123 goto error;
13124
13125 entry->path = PyUnicode_FromWideChar(joined_path, -1);
13126 PyMem_Free(joined_path);
13127 if (!entry->path)
13128 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070013129 if (path->narrow) {
13130 Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
13131 if (!entry->path)
13132 goto error;
13133 }
Victor Stinner6036e442015-03-08 01:58:04 +010013134
Steve Dowercc16be82016-09-08 10:35:16 -070013135 find_data_to_file_info(dataW, &file_info, &reparse_tag);
Victor Stinner6036e442015-03-08 01:58:04 +010013136 _Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
13137
13138 return (PyObject *)entry;
13139
13140error:
13141 Py_DECREF(entry);
13142 return NULL;
13143}
13144
13145#else /* POSIX */
13146
13147static char *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020013148join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
Victor Stinner6036e442015-03-08 01:58:04 +010013149{
13150 Py_ssize_t path_len;
13151 Py_ssize_t size;
13152 char *result;
13153
13154 if (!path_narrow) { /* Default arg: "." */
13155 path_narrow = ".";
13156 path_len = 1;
13157 }
13158 else {
13159 path_len = strlen(path_narrow);
13160 }
13161
13162 if (filename_len == -1)
13163 filename_len = strlen(filename);
13164
13165 /* The +1's are for the path separator and the NUL */
13166 size = path_len + 1 + filename_len + 1;
13167 result = PyMem_New(char, size);
13168 if (!result) {
13169 PyErr_NoMemory();
13170 return NULL;
13171 }
13172 strcpy(result, path_narrow);
13173 if (path_len > 0 && result[path_len - 1] != '/')
13174 result[path_len++] = '/';
13175 strcpy(result + path_len, filename);
13176 return result;
13177}
13178
13179static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020013180DirEntry_from_posix_info(path_t *path, const char *name, Py_ssize_t name_len,
Victor Stinner35a97c02015-03-08 02:59:09 +010013181 ino_t d_ino
13182#ifdef HAVE_DIRENT_D_TYPE
13183 , unsigned char d_type
13184#endif
13185 )
Victor Stinner6036e442015-03-08 01:58:04 +010013186{
13187 DirEntry *entry;
13188 char *joined_path;
13189
Eddie Elizondob3966632019-11-05 07:16:14 -080013190 PyObject *DirEntryType = _posixstate_global->DirEntryType;
13191 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010013192 if (!entry)
13193 return NULL;
13194 entry->name = NULL;
13195 entry->path = NULL;
13196 entry->stat = NULL;
13197 entry->lstat = NULL;
13198
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013199 if (path->fd != -1) {
13200 entry->dir_fd = path->fd;
13201 joined_path = NULL;
13202 }
13203 else {
13204 entry->dir_fd = DEFAULT_DIR_FD;
13205 joined_path = join_path_filename(path->narrow, name, name_len);
13206 if (!joined_path)
13207 goto error;
13208 }
Victor Stinner6036e442015-03-08 01:58:04 +010013209
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +030013210 if (!path->narrow || !PyObject_CheckBuffer(path->object)) {
Victor Stinner6036e442015-03-08 01:58:04 +010013211 entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013212 if (joined_path)
13213 entry->path = PyUnicode_DecodeFSDefault(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013214 }
13215 else {
13216 entry->name = PyBytes_FromStringAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013217 if (joined_path)
13218 entry->path = PyBytes_FromString(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013219 }
13220 PyMem_Free(joined_path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013221 if (!entry->name)
13222 goto error;
13223
13224 if (path->fd != -1) {
13225 entry->path = entry->name;
13226 Py_INCREF(entry->path);
13227 }
13228 else if (!entry->path)
Victor Stinner6036e442015-03-08 01:58:04 +010013229 goto error;
13230
Victor Stinner35a97c02015-03-08 02:59:09 +010013231#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010013232 entry->d_type = d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010013233#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013234 entry->d_ino = d_ino;
13235
13236 return (PyObject *)entry;
13237
13238error:
13239 Py_XDECREF(entry);
13240 return NULL;
13241}
13242
13243#endif
13244
13245
13246typedef struct {
13247 PyObject_HEAD
13248 path_t path;
13249#ifdef MS_WINDOWS
13250 HANDLE handle;
13251 WIN32_FIND_DATAW file_data;
13252 int first_time;
13253#else /* POSIX */
13254 DIR *dirp;
13255#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013256#ifdef HAVE_FDOPENDIR
13257 int fd;
13258#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013259} ScandirIterator;
13260
13261#ifdef MS_WINDOWS
13262
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013263static int
13264ScandirIterator_is_closed(ScandirIterator *iterator)
13265{
13266 return iterator->handle == INVALID_HANDLE_VALUE;
13267}
13268
Victor Stinner6036e442015-03-08 01:58:04 +010013269static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013270ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013271{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013272 HANDLE handle = iterator->handle;
13273
13274 if (handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013275 return;
13276
Victor Stinner6036e442015-03-08 01:58:04 +010013277 iterator->handle = INVALID_HANDLE_VALUE;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013278 Py_BEGIN_ALLOW_THREADS
13279 FindClose(handle);
13280 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013281}
13282
13283static PyObject *
13284ScandirIterator_iternext(ScandirIterator *iterator)
13285{
13286 WIN32_FIND_DATAW *file_data = &iterator->file_data;
13287 BOOL success;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013288 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013289
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013290 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013291 if (iterator->handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013292 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013293
13294 while (1) {
13295 if (!iterator->first_time) {
13296 Py_BEGIN_ALLOW_THREADS
13297 success = FindNextFileW(iterator->handle, file_data);
13298 Py_END_ALLOW_THREADS
13299 if (!success) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013300 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013301 if (GetLastError() != ERROR_NO_MORE_FILES)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013302 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013303 break;
13304 }
13305 }
13306 iterator->first_time = 0;
13307
13308 /* Skip over . and .. */
13309 if (wcscmp(file_data->cFileName, L".") != 0 &&
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013310 wcscmp(file_data->cFileName, L"..") != 0) {
13311 entry = DirEntry_from_find_data(&iterator->path, file_data);
13312 if (!entry)
13313 break;
13314 return entry;
13315 }
Victor Stinner6036e442015-03-08 01:58:04 +010013316
13317 /* Loop till we get a non-dot directory or finish iterating */
13318 }
13319
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013320 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013321 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013322 return NULL;
13323}
13324
13325#else /* POSIX */
13326
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013327static int
13328ScandirIterator_is_closed(ScandirIterator *iterator)
13329{
13330 return !iterator->dirp;
13331}
13332
Victor Stinner6036e442015-03-08 01:58:04 +010013333static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013334ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013335{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013336 DIR *dirp = iterator->dirp;
13337
13338 if (!dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013339 return;
13340
Victor Stinner6036e442015-03-08 01:58:04 +010013341 iterator->dirp = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013342 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013343#ifdef HAVE_FDOPENDIR
13344 if (iterator->path.fd != -1)
13345 rewinddir(dirp);
13346#endif
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013347 closedir(dirp);
13348 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013349 return;
13350}
13351
13352static PyObject *
13353ScandirIterator_iternext(ScandirIterator *iterator)
13354{
13355 struct dirent *direntp;
13356 Py_ssize_t name_len;
13357 int is_dot;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013358 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013359
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013360 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013361 if (!iterator->dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013362 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013363
13364 while (1) {
13365 errno = 0;
13366 Py_BEGIN_ALLOW_THREADS
13367 direntp = readdir(iterator->dirp);
13368 Py_END_ALLOW_THREADS
13369
13370 if (!direntp) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013371 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013372 if (errno != 0)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013373 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013374 break;
13375 }
13376
13377 /* Skip over . and .. */
13378 name_len = NAMLEN(direntp);
13379 is_dot = direntp->d_name[0] == '.' &&
13380 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
13381 if (!is_dot) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013382 entry = DirEntry_from_posix_info(&iterator->path, direntp->d_name,
Victor Stinner35a97c02015-03-08 02:59:09 +010013383 name_len, direntp->d_ino
13384#ifdef HAVE_DIRENT_D_TYPE
13385 , direntp->d_type
13386#endif
13387 );
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013388 if (!entry)
13389 break;
13390 return entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013391 }
13392
13393 /* Loop till we get a non-dot directory or finish iterating */
13394 }
13395
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013396 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013397 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013398 return NULL;
13399}
13400
13401#endif
13402
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013403static PyObject *
13404ScandirIterator_close(ScandirIterator *self, PyObject *args)
13405{
13406 ScandirIterator_closedir(self);
13407 Py_RETURN_NONE;
13408}
13409
13410static PyObject *
13411ScandirIterator_enter(PyObject *self, PyObject *args)
13412{
13413 Py_INCREF(self);
13414 return self;
13415}
13416
13417static PyObject *
13418ScandirIterator_exit(ScandirIterator *self, PyObject *args)
13419{
13420 ScandirIterator_closedir(self);
13421 Py_RETURN_NONE;
13422}
13423
Victor Stinner6036e442015-03-08 01:58:04 +010013424static void
Victor Stinner7bfa4092016-03-23 00:43:54 +010013425ScandirIterator_finalize(ScandirIterator *iterator)
13426{
13427 PyObject *error_type, *error_value, *error_traceback;
13428
13429 /* Save the current exception, if any. */
13430 PyErr_Fetch(&error_type, &error_value, &error_traceback);
13431
13432 if (!ScandirIterator_is_closed(iterator)) {
13433 ScandirIterator_closedir(iterator);
13434
13435 if (PyErr_ResourceWarning((PyObject *)iterator, 1,
13436 "unclosed scandir iterator %R", iterator)) {
13437 /* Spurious errors can appear at shutdown */
13438 if (PyErr_ExceptionMatches(PyExc_Warning)) {
13439 PyErr_WriteUnraisable((PyObject *) iterator);
13440 }
13441 }
13442 }
13443
Victor Stinner7bfa4092016-03-23 00:43:54 +010013444 path_cleanup(&iterator->path);
13445
13446 /* Restore the saved exception. */
13447 PyErr_Restore(error_type, error_value, error_traceback);
13448}
13449
13450static void
Victor Stinner6036e442015-03-08 01:58:04 +010013451ScandirIterator_dealloc(ScandirIterator *iterator)
13452{
Eddie Elizondob3966632019-11-05 07:16:14 -080013453 PyTypeObject *tp = Py_TYPE(iterator);
Victor Stinner7bfa4092016-03-23 00:43:54 +010013454 if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
13455 return;
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013456
Eddie Elizondob3966632019-11-05 07:16:14 -080013457 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
13458 free_func(iterator);
13459 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010013460}
13461
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013462static PyMethodDef ScandirIterator_methods[] = {
13463 {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
13464 {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
13465 {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
13466 {NULL}
13467};
13468
Eddie Elizondob3966632019-11-05 07:16:14 -080013469static PyType_Slot ScandirIteratorType_slots[] = {
13470 {Py_tp_new, _disabled_new},
13471 {Py_tp_dealloc, ScandirIterator_dealloc},
13472 {Py_tp_finalize, ScandirIterator_finalize},
13473 {Py_tp_iter, PyObject_SelfIter},
13474 {Py_tp_iternext, ScandirIterator_iternext},
13475 {Py_tp_methods, ScandirIterator_methods},
13476 {0, 0},
13477};
13478
13479static PyType_Spec ScandirIteratorType_spec = {
13480 MODNAME ".ScandirIterator",
13481 sizeof(ScandirIterator),
13482 0,
13483 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE,
13484 ScandirIteratorType_slots
Victor Stinner6036e442015-03-08 01:58:04 +010013485};
13486
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013487/*[clinic input]
13488os.scandir
13489
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013490 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013491
13492Return an iterator of DirEntry objects for given path.
13493
BNMetricsb9427072018-11-02 15:20:19 +000013494path can be specified as either str, bytes, or a path-like object. If path
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013495is bytes, the names of yielded DirEntry objects will also be bytes; in
13496all other circumstances they will be str.
13497
13498If path is None, uses the path='.'.
13499[clinic start generated code]*/
13500
Victor Stinner6036e442015-03-08 01:58:04 +010013501static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013502os_scandir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +000013503/*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013504{
13505 ScandirIterator *iterator;
Victor Stinner6036e442015-03-08 01:58:04 +010013506#ifdef MS_WINDOWS
13507 wchar_t *path_strW;
13508#else
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013509 const char *path_str;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013510#ifdef HAVE_FDOPENDIR
13511 int fd = -1;
13512#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013513#endif
13514
Steve Dower60419a72019-06-24 08:42:54 -070013515 if (PySys_Audit("os.scandir", "O",
13516 path->object ? path->object : Py_None) < 0) {
13517 return NULL;
13518 }
13519
Hai Shif707d942020-03-16 21:15:01 +080013520 PyObject *ScandirIteratorType = get_posix_state(module)->ScandirIteratorType;
Eddie Elizondob3966632019-11-05 07:16:14 -080013521 iterator = PyObject_New(ScandirIterator, (PyTypeObject *)ScandirIteratorType);
Victor Stinner6036e442015-03-08 01:58:04 +010013522 if (!iterator)
13523 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013524
13525#ifdef MS_WINDOWS
13526 iterator->handle = INVALID_HANDLE_VALUE;
13527#else
13528 iterator->dirp = NULL;
13529#endif
13530
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013531 memcpy(&iterator->path, path, sizeof(path_t));
Serhiy Storchaka095ef732017-02-09 20:05:51 +020013532 /* Move the ownership to iterator->path */
13533 path->object = NULL;
13534 path->cleanup = NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013535
13536#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +010013537 iterator->first_time = 1;
13538
13539 path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
13540 if (!path_strW)
13541 goto error;
13542
13543 Py_BEGIN_ALLOW_THREADS
13544 iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
13545 Py_END_ALLOW_THREADS
13546
13547 PyMem_Free(path_strW);
13548
13549 if (iterator->handle == INVALID_HANDLE_VALUE) {
13550 path_error(&iterator->path);
13551 goto error;
13552 }
13553#else /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010013554 errno = 0;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013555#ifdef HAVE_FDOPENDIR
13556 if (path->fd != -1) {
13557 /* closedir() closes the FD, so we duplicate it */
13558 fd = _Py_dup(path->fd);
13559 if (fd == -1)
13560 goto error;
13561
13562 Py_BEGIN_ALLOW_THREADS
13563 iterator->dirp = fdopendir(fd);
13564 Py_END_ALLOW_THREADS
13565 }
13566 else
13567#endif
13568 {
13569 if (iterator->path.narrow)
13570 path_str = iterator->path.narrow;
13571 else
13572 path_str = ".";
13573
13574 Py_BEGIN_ALLOW_THREADS
13575 iterator->dirp = opendir(path_str);
13576 Py_END_ALLOW_THREADS
13577 }
Victor Stinner6036e442015-03-08 01:58:04 +010013578
13579 if (!iterator->dirp) {
13580 path_error(&iterator->path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013581#ifdef HAVE_FDOPENDIR
13582 if (fd != -1) {
13583 Py_BEGIN_ALLOW_THREADS
13584 close(fd);
13585 Py_END_ALLOW_THREADS
13586 }
13587#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013588 goto error;
13589 }
13590#endif
13591
13592 return (PyObject *)iterator;
13593
13594error:
13595 Py_DECREF(iterator);
13596 return NULL;
13597}
13598
Ethan Furman410ef8e2016-06-04 12:06:26 -070013599/*
13600 Return the file system path representation of the object.
13601
13602 If the object is str or bytes, then allow it to pass through with
13603 an incremented refcount. If the object defines __fspath__(), then
13604 return the result of that method. All other types raise a TypeError.
13605*/
13606PyObject *
13607PyOS_FSPath(PyObject *path)
13608{
Brett Cannon3f9183b2016-08-26 14:44:48 -070013609 /* For error message reasons, this function is manually inlined in
13610 path_converter(). */
Ethan Furman410ef8e2016-06-04 12:06:26 -070013611 PyObject *func = NULL;
13612 PyObject *path_repr = NULL;
13613
13614 if (PyUnicode_Check(path) || PyBytes_Check(path)) {
13615 Py_INCREF(path);
13616 return path;
13617 }
13618
13619 func = _PyObject_LookupSpecial(path, &PyId___fspath__);
13620 if (NULL == func) {
13621 return PyErr_Format(PyExc_TypeError,
13622 "expected str, bytes or os.PathLike object, "
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013623 "not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -080013624 _PyType_Name(Py_TYPE(path)));
Ethan Furman410ef8e2016-06-04 12:06:26 -070013625 }
13626
Victor Stinnerf17c3de2016-12-06 18:46:19 +010013627 path_repr = _PyObject_CallNoArg(func);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013628 Py_DECREF(func);
Brett Cannon044283a2016-07-15 10:41:49 -070013629 if (NULL == path_repr) {
13630 return NULL;
13631 }
13632
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013633 if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
13634 PyErr_Format(PyExc_TypeError,
13635 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -080013636 "not %.200s", _PyType_Name(Py_TYPE(path)),
13637 _PyType_Name(Py_TYPE(path_repr)));
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013638 Py_DECREF(path_repr);
13639 return NULL;
13640 }
13641
Ethan Furman410ef8e2016-06-04 12:06:26 -070013642 return path_repr;
13643}
13644
13645/*[clinic input]
13646os.fspath
13647
13648 path: object
13649
13650Return the file system path representation of the object.
13651
Brett Cannonb4f43e92016-06-09 14:32:08 -070013652If the object is str or bytes, then allow it to pass through as-is. If the
13653object defines __fspath__(), then return the result of that method. All other
13654types raise a TypeError.
Ethan Furman410ef8e2016-06-04 12:06:26 -070013655[clinic start generated code]*/
13656
13657static PyObject *
Serhiy Storchaka2954f832016-07-07 18:20:03 +030013658os_fspath_impl(PyObject *module, PyObject *path)
13659/*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
Ethan Furman410ef8e2016-06-04 12:06:26 -070013660{
13661 return PyOS_FSPath(path);
13662}
Victor Stinner6036e442015-03-08 01:58:04 +010013663
Victor Stinner9b1f4742016-09-06 16:18:52 -070013664#ifdef HAVE_GETRANDOM_SYSCALL
13665/*[clinic input]
13666os.getrandom
13667
13668 size: Py_ssize_t
13669 flags: int=0
13670
13671Obtain a series of random bytes.
13672[clinic start generated code]*/
13673
13674static PyObject *
13675os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
13676/*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
13677{
Victor Stinner9b1f4742016-09-06 16:18:52 -070013678 PyObject *bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013679 Py_ssize_t n;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013680
13681 if (size < 0) {
13682 errno = EINVAL;
13683 return posix_error();
13684 }
13685
Victor Stinnerec2319c2016-09-20 23:00:59 +020013686 bytes = PyBytes_FromStringAndSize(NULL, size);
13687 if (bytes == NULL) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013688 PyErr_NoMemory();
13689 return NULL;
13690 }
13691
13692 while (1) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013693 n = syscall(SYS_getrandom,
13694 PyBytes_AS_STRING(bytes),
13695 PyBytes_GET_SIZE(bytes),
13696 flags);
Victor Stinner9b1f4742016-09-06 16:18:52 -070013697 if (n < 0 && errno == EINTR) {
13698 if (PyErr_CheckSignals() < 0) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013699 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013700 }
Victor Stinnerec2319c2016-09-20 23:00:59 +020013701
13702 /* getrandom() was interrupted by a signal: retry */
Victor Stinner9b1f4742016-09-06 16:18:52 -070013703 continue;
13704 }
13705 break;
13706 }
13707
13708 if (n < 0) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013709 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerec2319c2016-09-20 23:00:59 +020013710 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013711 }
13712
Victor Stinnerec2319c2016-09-20 23:00:59 +020013713 if (n != size) {
13714 _PyBytes_Resize(&bytes, n);
13715 }
Victor Stinner9b1f4742016-09-06 16:18:52 -070013716
13717 return bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013718
13719error:
13720 Py_DECREF(bytes);
13721 return NULL;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013722}
13723#endif /* HAVE_GETRANDOM_SYSCALL */
13724
Steve Dower2438cdf2019-03-29 16:37:16 -070013725#ifdef MS_WINDOWS
13726/* bpo-36085: Helper functions for managing DLL search directories
13727 * on win32
13728 */
13729
13730typedef DLL_DIRECTORY_COOKIE (WINAPI *PAddDllDirectory)(PCWSTR newDirectory);
13731typedef BOOL (WINAPI *PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE cookie);
13732
13733/*[clinic input]
13734os._add_dll_directory
13735
13736 path: path_t
13737
13738Add a path to the DLL search path.
13739
13740This search path is used when resolving dependencies for imported
13741extension modules (the module itself is resolved through sys.path),
13742and also by ctypes.
13743
13744Returns an opaque value that may be passed to os.remove_dll_directory
13745to remove this directory from the search path.
13746[clinic start generated code]*/
13747
13748static PyObject *
13749os__add_dll_directory_impl(PyObject *module, path_t *path)
13750/*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
13751{
13752 HMODULE hKernel32;
13753 PAddDllDirectory AddDllDirectory;
13754 DLL_DIRECTORY_COOKIE cookie = 0;
13755 DWORD err = 0;
13756
Saiyang Gou7514f4f2020-02-12 23:47:42 -080013757 if (PySys_Audit("os.add_dll_directory", "(O)", path->object) < 0) {
13758 return NULL;
13759 }
13760
Steve Dower2438cdf2019-03-29 16:37:16 -070013761 /* For Windows 7, we have to load this. As this will be a fairly
13762 infrequent operation, just do it each time. Kernel32 is always
13763 loaded. */
13764 Py_BEGIN_ALLOW_THREADS
13765 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13766 !(AddDllDirectory = (PAddDllDirectory)GetProcAddress(
13767 hKernel32, "AddDllDirectory")) ||
13768 !(cookie = (*AddDllDirectory)(path->wide))) {
13769 err = GetLastError();
13770 }
13771 Py_END_ALLOW_THREADS
13772
13773 if (err) {
13774 return win32_error_object_err("add_dll_directory",
13775 path->object, err);
13776 }
13777
13778 return PyCapsule_New(cookie, "DLL directory cookie", NULL);
13779}
13780
13781/*[clinic input]
13782os._remove_dll_directory
13783
13784 cookie: object
13785
13786Removes a path from the DLL search path.
13787
13788The parameter is an opaque value that was returned from
13789os.add_dll_directory. You can only remove directories that you added
13790yourself.
13791[clinic start generated code]*/
13792
13793static PyObject *
13794os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
13795/*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
13796{
13797 HMODULE hKernel32;
13798 PRemoveDllDirectory RemoveDllDirectory;
13799 DLL_DIRECTORY_COOKIE cookieValue;
13800 DWORD err = 0;
13801
13802 if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
13803 PyErr_SetString(PyExc_TypeError,
13804 "Provided cookie was not returned from os.add_dll_directory");
13805 return NULL;
13806 }
13807
13808 cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
13809 cookie, "DLL directory cookie");
13810
13811 /* For Windows 7, we have to load this. As this will be a fairly
13812 infrequent operation, just do it each time. Kernel32 is always
13813 loaded. */
13814 Py_BEGIN_ALLOW_THREADS
13815 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13816 !(RemoveDllDirectory = (PRemoveDllDirectory)GetProcAddress(
13817 hKernel32, "RemoveDllDirectory")) ||
13818 !(*RemoveDllDirectory)(cookieValue)) {
13819 err = GetLastError();
13820 }
13821 Py_END_ALLOW_THREADS
13822
13823 if (err) {
13824 return win32_error_object_err("remove_dll_directory",
13825 NULL, err);
13826 }
13827
13828 if (PyCapsule_SetName(cookie, NULL)) {
13829 return NULL;
13830 }
13831
13832 Py_RETURN_NONE;
13833}
13834
13835#endif
Larry Hastings31826802013-10-19 00:09:25 -070013836
Victor Stinner65a796e2020-04-01 18:49:29 +020013837
13838/* Only check if WIFEXITED is available: expect that it comes
13839 with WEXITSTATUS, WIFSIGNALED, etc.
13840
13841 os.waitstatus_to_exitcode() is implemented in C and not in Python, so
13842 subprocess can safely call it during late Python finalization without
13843 risking that used os attributes were set to None by _PyImport_Cleanup(). */
13844#if defined(WIFEXITED) || defined(MS_WINDOWS)
13845/*[clinic input]
13846os.waitstatus_to_exitcode
13847
Victor Stinner9bee32b2020-04-22 16:30:35 +020013848 status as status_obj: object
Victor Stinner65a796e2020-04-01 18:49:29 +020013849
13850Convert a wait status to an exit code.
13851
13852On Unix:
13853
13854* If WIFEXITED(status) is true, return WEXITSTATUS(status).
13855* If WIFSIGNALED(status) is true, return -WTERMSIG(status).
13856* Otherwise, raise a ValueError.
13857
13858On Windows, return status shifted right by 8 bits.
13859
13860On Unix, if the process is being traced or if waitpid() was called with
13861WUNTRACED option, the caller must first check if WIFSTOPPED(status) is true.
13862This function must not be called if WIFSTOPPED(status) is true.
13863[clinic start generated code]*/
13864
13865static PyObject *
Victor Stinner9bee32b2020-04-22 16:30:35 +020013866os_waitstatus_to_exitcode_impl(PyObject *module, PyObject *status_obj)
13867/*[clinic end generated code: output=db50b1b0ba3c7153 input=7fe2d7fdaea3db42]*/
Victor Stinner65a796e2020-04-01 18:49:29 +020013868{
Victor Stinner9bee32b2020-04-22 16:30:35 +020013869 if (PyFloat_Check(status_obj)) {
13870 PyErr_SetString(PyExc_TypeError,
13871 "integer argument expected, got float" );
13872 return NULL;
13873 }
Victor Stinner65a796e2020-04-01 18:49:29 +020013874#ifndef MS_WINDOWS
Victor Stinner9bee32b2020-04-22 16:30:35 +020013875 int status = _PyLong_AsInt(status_obj);
13876 if (status == -1 && PyErr_Occurred()) {
13877 return NULL;
13878 }
13879
Victor Stinner65a796e2020-04-01 18:49:29 +020013880 WAIT_TYPE wait_status;
13881 WAIT_STATUS_INT(wait_status) = status;
13882 int exitcode;
13883 if (WIFEXITED(wait_status)) {
13884 exitcode = WEXITSTATUS(wait_status);
13885 /* Sanity check to provide warranty on the function behavior.
13886 It should not occur in practice */
13887 if (exitcode < 0) {
13888 PyErr_Format(PyExc_ValueError, "invalid WEXITSTATUS: %i", exitcode);
13889 return NULL;
13890 }
13891 }
13892 else if (WIFSIGNALED(wait_status)) {
13893 int signum = WTERMSIG(wait_status);
13894 /* Sanity check to provide warranty on the function behavior.
13895 It should not occurs in practice */
13896 if (signum <= 0) {
13897 PyErr_Format(PyExc_ValueError, "invalid WTERMSIG: %i", signum);
13898 return NULL;
13899 }
13900 exitcode = -signum;
13901 } else if (WIFSTOPPED(wait_status)) {
13902 /* Status only received if the process is being traced
13903 or if waitpid() was called with WUNTRACED option. */
13904 int signum = WSTOPSIG(wait_status);
13905 PyErr_Format(PyExc_ValueError,
13906 "process stopped by delivery of signal %i",
13907 signum);
13908 return NULL;
13909 }
13910 else {
13911 PyErr_Format(PyExc_ValueError, "invalid wait status: %i", status);
13912 return NULL;
13913 }
13914 return PyLong_FromLong(exitcode);
13915#else
13916 /* Windows implementation: see os.waitpid() implementation
13917 which uses _cwait(). */
Victor Stinner9bee32b2020-04-22 16:30:35 +020013918 unsigned long long status = PyLong_AsUnsignedLongLong(status_obj);
13919 if (status == (unsigned long long)-1 && PyErr_Occurred()) {
13920 return NULL;
13921 }
13922
13923 unsigned long long exitcode = (status >> 8);
13924 /* ExitProcess() accepts an UINT type:
13925 reject exit code which doesn't fit in an UINT */
13926 if (exitcode > UINT_MAX) {
13927 PyErr_Format(PyExc_ValueError, "invalid exit code: %llu", exitcode);
13928 return NULL;
13929 }
13930 return PyLong_FromUnsignedLong((unsigned long)exitcode);
Victor Stinner65a796e2020-04-01 18:49:29 +020013931#endif
13932}
13933#endif
13934
13935
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013936static PyMethodDef posix_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -070013937
13938 OS_STAT_METHODDEF
13939 OS_ACCESS_METHODDEF
13940 OS_TTYNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013941 OS_CHDIR_METHODDEF
13942 OS_CHFLAGS_METHODDEF
13943 OS_CHMOD_METHODDEF
13944 OS_FCHMOD_METHODDEF
13945 OS_LCHMOD_METHODDEF
13946 OS_CHOWN_METHODDEF
13947 OS_FCHOWN_METHODDEF
13948 OS_LCHOWN_METHODDEF
13949 OS_LCHFLAGS_METHODDEF
13950 OS_CHROOT_METHODDEF
13951 OS_CTERMID_METHODDEF
13952 OS_GETCWD_METHODDEF
13953 OS_GETCWDB_METHODDEF
13954 OS_LINK_METHODDEF
13955 OS_LISTDIR_METHODDEF
13956 OS_LSTAT_METHODDEF
13957 OS_MKDIR_METHODDEF
13958 OS_NICE_METHODDEF
13959 OS_GETPRIORITY_METHODDEF
13960 OS_SETPRIORITY_METHODDEF
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000013961 OS_POSIX_SPAWN_METHODDEF
Joannah Nanjekye92b83222019-01-16 16:29:26 +030013962 OS_POSIX_SPAWNP_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013963 OS_READLINK_METHODDEF
Pablo Galindoaac4d032019-05-31 19:39:47 +010013964 OS_COPY_FILE_RANGE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013965 OS_RENAME_METHODDEF
13966 OS_REPLACE_METHODDEF
13967 OS_RMDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013968 OS_SYMLINK_METHODDEF
13969 OS_SYSTEM_METHODDEF
13970 OS_UMASK_METHODDEF
13971 OS_UNAME_METHODDEF
13972 OS_UNLINK_METHODDEF
13973 OS_REMOVE_METHODDEF
13974 OS_UTIME_METHODDEF
13975 OS_TIMES_METHODDEF
13976 OS__EXIT_METHODDEF
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020013977 OS__FCOPYFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013978 OS_EXECV_METHODDEF
13979 OS_EXECVE_METHODDEF
13980 OS_SPAWNV_METHODDEF
13981 OS_SPAWNVE_METHODDEF
13982 OS_FORK1_METHODDEF
13983 OS_FORK_METHODDEF
Antoine Pitrou346cbd32017-05-27 17:50:54 +020013984 OS_REGISTER_AT_FORK_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013985 OS_SCHED_GET_PRIORITY_MAX_METHODDEF
13986 OS_SCHED_GET_PRIORITY_MIN_METHODDEF
13987 OS_SCHED_GETPARAM_METHODDEF
13988 OS_SCHED_GETSCHEDULER_METHODDEF
13989 OS_SCHED_RR_GET_INTERVAL_METHODDEF
13990 OS_SCHED_SETPARAM_METHODDEF
13991 OS_SCHED_SETSCHEDULER_METHODDEF
13992 OS_SCHED_YIELD_METHODDEF
13993 OS_SCHED_SETAFFINITY_METHODDEF
13994 OS_SCHED_GETAFFINITY_METHODDEF
13995 OS_OPENPTY_METHODDEF
13996 OS_FORKPTY_METHODDEF
13997 OS_GETEGID_METHODDEF
13998 OS_GETEUID_METHODDEF
13999 OS_GETGID_METHODDEF
Serhiy Storchaka2b560312020-04-18 19:14:10 +030014000 OS_GETGROUPLIST_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014001 OS_GETGROUPS_METHODDEF
14002 OS_GETPID_METHODDEF
14003 OS_GETPGRP_METHODDEF
14004 OS_GETPPID_METHODDEF
14005 OS_GETUID_METHODDEF
14006 OS_GETLOGIN_METHODDEF
14007 OS_KILL_METHODDEF
14008 OS_KILLPG_METHODDEF
14009 OS_PLOCK_METHODDEF
Steve Dowercc16be82016-09-08 10:35:16 -070014010 OS_STARTFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014011 OS_SETUID_METHODDEF
14012 OS_SETEUID_METHODDEF
14013 OS_SETREUID_METHODDEF
14014 OS_SETGID_METHODDEF
14015 OS_SETEGID_METHODDEF
14016 OS_SETREGID_METHODDEF
14017 OS_SETGROUPS_METHODDEF
Serhiy Storchaka2b560312020-04-18 19:14:10 +030014018 OS_INITGROUPS_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014019 OS_GETPGID_METHODDEF
14020 OS_SETPGRP_METHODDEF
14021 OS_WAIT_METHODDEF
14022 OS_WAIT3_METHODDEF
14023 OS_WAIT4_METHODDEF
14024 OS_WAITID_METHODDEF
14025 OS_WAITPID_METHODDEF
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -080014026 OS_PIDFD_OPEN_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014027 OS_GETSID_METHODDEF
14028 OS_SETSID_METHODDEF
14029 OS_SETPGID_METHODDEF
14030 OS_TCGETPGRP_METHODDEF
14031 OS_TCSETPGRP_METHODDEF
14032 OS_OPEN_METHODDEF
14033 OS_CLOSE_METHODDEF
14034 OS_CLOSERANGE_METHODDEF
14035 OS_DEVICE_ENCODING_METHODDEF
14036 OS_DUP_METHODDEF
14037 OS_DUP2_METHODDEF
14038 OS_LOCKF_METHODDEF
14039 OS_LSEEK_METHODDEF
14040 OS_READ_METHODDEF
14041 OS_READV_METHODDEF
14042 OS_PREAD_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000014043 OS_PREADV_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014044 OS_WRITE_METHODDEF
14045 OS_WRITEV_METHODDEF
14046 OS_PWRITE_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000014047 OS_PWRITEV_METHODDEF
Serhiy Storchaka2b560312020-04-18 19:14:10 +030014048 OS_SENDFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014049 OS_FSTAT_METHODDEF
14050 OS_ISATTY_METHODDEF
14051 OS_PIPE_METHODDEF
14052 OS_PIPE2_METHODDEF
14053 OS_MKFIFO_METHODDEF
14054 OS_MKNOD_METHODDEF
14055 OS_MAJOR_METHODDEF
14056 OS_MINOR_METHODDEF
14057 OS_MAKEDEV_METHODDEF
14058 OS_FTRUNCATE_METHODDEF
14059 OS_TRUNCATE_METHODDEF
14060 OS_POSIX_FALLOCATE_METHODDEF
14061 OS_POSIX_FADVISE_METHODDEF
14062 OS_PUTENV_METHODDEF
14063 OS_UNSETENV_METHODDEF
14064 OS_STRERROR_METHODDEF
14065 OS_FCHDIR_METHODDEF
14066 OS_FSYNC_METHODDEF
14067 OS_SYNC_METHODDEF
14068 OS_FDATASYNC_METHODDEF
14069 OS_WCOREDUMP_METHODDEF
14070 OS_WIFCONTINUED_METHODDEF
14071 OS_WIFSTOPPED_METHODDEF
14072 OS_WIFSIGNALED_METHODDEF
14073 OS_WIFEXITED_METHODDEF
14074 OS_WEXITSTATUS_METHODDEF
14075 OS_WTERMSIG_METHODDEF
14076 OS_WSTOPSIG_METHODDEF
14077 OS_FSTATVFS_METHODDEF
14078 OS_STATVFS_METHODDEF
14079 OS_CONFSTR_METHODDEF
14080 OS_SYSCONF_METHODDEF
14081 OS_FPATHCONF_METHODDEF
14082 OS_PATHCONF_METHODDEF
14083 OS_ABORT_METHODDEF
Serhiy Storchakaf0b50152015-05-13 00:52:39 +030014084 OS__GETFULLPATHNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014085 OS__GETDISKUSAGE_METHODDEF
14086 OS__GETFINALPATHNAME_METHODDEF
14087 OS__GETVOLUMEPATHNAME_METHODDEF
14088 OS_GETLOADAVG_METHODDEF
14089 OS_URANDOM_METHODDEF
14090 OS_SETRESUID_METHODDEF
14091 OS_SETRESGID_METHODDEF
14092 OS_GETRESUID_METHODDEF
14093 OS_GETRESGID_METHODDEF
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000014094
Larry Hastings2f936352014-08-05 14:04:04 +100014095 OS_GETXATTR_METHODDEF
14096 OS_SETXATTR_METHODDEF
14097 OS_REMOVEXATTR_METHODDEF
14098 OS_LISTXATTR_METHODDEF
14099
Serhiy Storchaka2b560312020-04-18 19:14:10 +030014100 OS_GET_TERMINAL_SIZE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100014101 OS_CPU_COUNT_METHODDEF
14102 OS_GET_INHERITABLE_METHODDEF
14103 OS_SET_INHERITABLE_METHODDEF
14104 OS_GET_HANDLE_INHERITABLE_METHODDEF
14105 OS_SET_HANDLE_INHERITABLE_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030014106 OS_GET_BLOCKING_METHODDEF
14107 OS_SET_BLOCKING_METHODDEF
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020014108 OS_SCANDIR_METHODDEF
Ethan Furman410ef8e2016-06-04 12:06:26 -070014109 OS_FSPATH_METHODDEF
Victor Stinner9b1f4742016-09-06 16:18:52 -070014110 OS_GETRANDOM_METHODDEF
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014111 OS_MEMFD_CREATE_METHODDEF
Steve Dower2438cdf2019-03-29 16:37:16 -070014112 OS__ADD_DLL_DIRECTORY_METHODDEF
14113 OS__REMOVE_DLL_DIRECTORY_METHODDEF
Victor Stinner65a796e2020-04-01 18:49:29 +020014114 OS_WAITSTATUS_TO_EXITCODE_METHODDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000014115 {NULL, NULL} /* Sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000014116};
14117
Barry Warsaw4a342091996-12-19 23:50:02 +000014118static int
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014119all_ins(PyObject *m)
Barry Warsaw4a342091996-12-19 23:50:02 +000014120{
Guido van Rossum94f6f721999-01-06 18:42:14 +000014121#ifdef F_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014122 if (PyModule_AddIntMacro(m, F_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014123#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000014124#ifdef R_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014125 if (PyModule_AddIntMacro(m, R_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014126#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000014127#ifdef W_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014128 if (PyModule_AddIntMacro(m, W_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014129#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000014130#ifdef X_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014131 if (PyModule_AddIntMacro(m, X_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014132#endif
Fred Drakec9680921999-12-13 16:37:25 +000014133#ifdef NGROUPS_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014134 if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
Fred Drakec9680921999-12-13 16:37:25 +000014135#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000014136#ifdef TMP_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014137 if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
Fred Drake5ab8eaf1999-12-09 21:13:07 +000014138#endif
Fred Drake106c1a02002-04-23 15:58:02 +000014139#ifdef WCONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014140 if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000014141#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000014142#ifdef WNOHANG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014143 if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014144#endif
Fred Drake106c1a02002-04-23 15:58:02 +000014145#ifdef WUNTRACED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014146 if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000014147#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000014148#ifdef O_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014149 if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014150#endif
14151#ifdef O_WRONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014152 if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014153#endif
14154#ifdef O_RDWR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014155 if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014156#endif
14157#ifdef O_NDELAY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014158 if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014159#endif
14160#ifdef O_NONBLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014161 if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014162#endif
14163#ifdef O_APPEND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014164 if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014165#endif
14166#ifdef O_DSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014167 if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014168#endif
14169#ifdef O_RSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014170 if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014171#endif
14172#ifdef O_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014173 if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014174#endif
14175#ifdef O_NOCTTY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014176 if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014177#endif
14178#ifdef O_CREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014179 if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014180#endif
14181#ifdef O_EXCL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014182 if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014183#endif
14184#ifdef O_TRUNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014185 if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014186#endif
Guido van Rossum98d9d091997-08-08 21:48:51 +000014187#ifdef O_BINARY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014188 if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000014189#endif
14190#ifdef O_TEXT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014191 if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000014192#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020014193#ifdef O_XATTR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014194 if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020014195#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014196#ifdef O_LARGEFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014197 if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014198#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020014199#ifndef __GNU__
Skip Montanaro5ff14922005-05-16 02:42:22 +000014200#ifdef O_SHLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014201 if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000014202#endif
14203#ifdef O_EXLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014204 if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000014205#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020014206#endif
Jesus Ceacf381202012-04-24 20:44:40 +020014207#ifdef O_EXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014208 if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020014209#endif
14210#ifdef O_SEARCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014211 if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020014212#endif
Benjamin Peterson3b965a22013-03-13 10:27:41 -050014213#ifdef O_PATH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014214 if (PyModule_AddIntMacro(m, O_PATH)) return -1;
Benjamin Peterson3b965a22013-03-13 10:27:41 -050014215#endif
Jesus Ceacf381202012-04-24 20:44:40 +020014216#ifdef O_TTY_INIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014217 if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020014218#endif
Christian Heimes177b3f92013-08-16 14:35:09 +020014219#ifdef O_TMPFILE
14220 if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
14221#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014222#ifdef PRIO_PROCESS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014223 if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014224#endif
14225#ifdef PRIO_PGRP
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014226 if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014227#endif
14228#ifdef PRIO_USER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014229 if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014230#endif
Charles-François Natali1e045b12011-05-22 20:42:32 +020014231#ifdef O_CLOEXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014232 if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
Charles-François Natali1e045b12011-05-22 20:42:32 +020014233#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020014234#ifdef O_ACCMODE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014235 if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020014236#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014237
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014238
Jesus Cea94363612012-06-22 18:32:07 +020014239#ifdef SEEK_HOLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014240 if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020014241#endif
14242#ifdef SEEK_DATA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014243 if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020014244#endif
14245
Tim Peters5aa91602002-01-30 05:46:57 +000014246/* MS Windows */
14247#ifdef O_NOINHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000014248 /* Don't inherit in child processes. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014249 if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014250#endif
14251#ifdef _O_SHORT_LIVED
Victor Stinner8c62be82010-05-06 00:08:46 +000014252 /* Optimize for short life (keep in memory). */
14253 /* MS forgot to define this one with a non-underscore form too. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014254 if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014255#endif
14256#ifdef O_TEMPORARY
Victor Stinner8c62be82010-05-06 00:08:46 +000014257 /* Automatically delete when last handle is closed. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014258 if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014259#endif
14260#ifdef O_RANDOM
Victor Stinner8c62be82010-05-06 00:08:46 +000014261 /* Optimize for random access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014262 if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014263#endif
14264#ifdef O_SEQUENTIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000014265 /* Optimize for sequential access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014266 if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014267#endif
14268
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014269/* GNU extensions. */
Alexandre Vassalottibee32532008-05-16 18:15:12 +000014270#ifdef O_ASYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000014271 /* Send a SIGIO signal whenever input or output
14272 becomes available on file descriptor */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014273 if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
Alexandre Vassalottibee32532008-05-16 18:15:12 +000014274#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014275#ifdef O_DIRECT
Victor Stinner8c62be82010-05-06 00:08:46 +000014276 /* Direct disk access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014277 if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014278#endif
14279#ifdef O_DIRECTORY
Victor Stinner8c62be82010-05-06 00:08:46 +000014280 /* Must be a directory. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014281 if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014282#endif
14283#ifdef O_NOFOLLOW
Victor Stinner8c62be82010-05-06 00:08:46 +000014284 /* Do not follow links. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014285 if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014286#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020014287#ifdef O_NOLINKS
14288 /* Fails if link count of the named file is greater than 1 */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014289 if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020014290#endif
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000014291#ifdef O_NOATIME
Victor Stinner8c62be82010-05-06 00:08:46 +000014292 /* Do not update the access time. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014293 if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000014294#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +000014295
Victor Stinner8c62be82010-05-06 00:08:46 +000014296 /* These come from sysexits.h */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014297#ifdef EX_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014298 if (PyModule_AddIntMacro(m, EX_OK)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014299#endif /* EX_OK */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014300#ifdef EX_USAGE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014301 if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014302#endif /* EX_USAGE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014303#ifdef EX_DATAERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014304 if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014305#endif /* EX_DATAERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014306#ifdef EX_NOINPUT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014307 if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014308#endif /* EX_NOINPUT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014309#ifdef EX_NOUSER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014310 if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014311#endif /* EX_NOUSER */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014312#ifdef EX_NOHOST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014313 if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014314#endif /* EX_NOHOST */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014315#ifdef EX_UNAVAILABLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014316 if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014317#endif /* EX_UNAVAILABLE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014318#ifdef EX_SOFTWARE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014319 if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014320#endif /* EX_SOFTWARE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014321#ifdef EX_OSERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014322 if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014323#endif /* EX_OSERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014324#ifdef EX_OSFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014325 if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014326#endif /* EX_OSFILE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014327#ifdef EX_CANTCREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014328 if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014329#endif /* EX_CANTCREAT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014330#ifdef EX_IOERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014331 if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014332#endif /* EX_IOERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014333#ifdef EX_TEMPFAIL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014334 if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014335#endif /* EX_TEMPFAIL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014336#ifdef EX_PROTOCOL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014337 if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014338#endif /* EX_PROTOCOL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014339#ifdef EX_NOPERM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014340 if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014341#endif /* EX_NOPERM */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014342#ifdef EX_CONFIG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014343 if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014344#endif /* EX_CONFIG */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014345#ifdef EX_NOTFOUND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014346 if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014347#endif /* EX_NOTFOUND */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014348
Amaury Forgeot d'Arc66d00ad2010-09-10 18:11:45 +000014349 /* statvfs */
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014350#ifdef ST_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014351 if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014352#endif /* ST_RDONLY */
14353#ifdef ST_NOSUID
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014354 if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014355#endif /* ST_NOSUID */
14356
doko@ubuntu.comca616a22013-12-08 15:23:07 +010014357 /* GNU extensions */
14358#ifdef ST_NODEV
14359 if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
14360#endif /* ST_NODEV */
14361#ifdef ST_NOEXEC
14362 if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
14363#endif /* ST_NOEXEC */
14364#ifdef ST_SYNCHRONOUS
14365 if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
14366#endif /* ST_SYNCHRONOUS */
14367#ifdef ST_MANDLOCK
14368 if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
14369#endif /* ST_MANDLOCK */
14370#ifdef ST_WRITE
14371 if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
14372#endif /* ST_WRITE */
14373#ifdef ST_APPEND
14374 if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
14375#endif /* ST_APPEND */
14376#ifdef ST_NOATIME
14377 if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
14378#endif /* ST_NOATIME */
14379#ifdef ST_NODIRATIME
14380 if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
14381#endif /* ST_NODIRATIME */
14382#ifdef ST_RELATIME
14383 if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
14384#endif /* ST_RELATIME */
14385
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014386 /* FreeBSD sendfile() constants */
14387#ifdef SF_NODISKIO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014388 if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014389#endif
14390#ifdef SF_MNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014391 if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014392#endif
14393#ifdef SF_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014394 if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014395#endif
14396
Ross Lagerwall7807c352011-03-17 20:20:30 +020014397 /* constants for posix_fadvise */
14398#ifdef POSIX_FADV_NORMAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014399 if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014400#endif
14401#ifdef POSIX_FADV_SEQUENTIAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014402 if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014403#endif
14404#ifdef POSIX_FADV_RANDOM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014405 if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014406#endif
14407#ifdef POSIX_FADV_NOREUSE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014408 if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014409#endif
14410#ifdef POSIX_FADV_WILLNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014411 if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014412#endif
14413#ifdef POSIX_FADV_DONTNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014414 if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014415#endif
14416
14417 /* constants for waitid */
14418#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014419 if (PyModule_AddIntMacro(m, P_PID)) return -1;
14420 if (PyModule_AddIntMacro(m, P_PGID)) return -1;
14421 if (PyModule_AddIntMacro(m, P_ALL)) return -1;
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080014422#ifdef P_PIDFD
14423 if (PyModule_AddIntMacro(m, P_PIDFD)) return -1;
14424#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014425#endif
14426#ifdef WEXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014427 if (PyModule_AddIntMacro(m, WEXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014428#endif
14429#ifdef WNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014430 if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014431#endif
14432#ifdef WSTOPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014433 if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014434#endif
14435#ifdef CLD_EXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014436 if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014437#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014438#ifdef CLD_KILLED
14439 if (PyModule_AddIntMacro(m, CLD_KILLED)) return -1;
14440#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014441#ifdef CLD_DUMPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014442 if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014443#endif
14444#ifdef CLD_TRAPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014445 if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014446#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014447#ifdef CLD_STOPPED
14448 if (PyModule_AddIntMacro(m, CLD_STOPPED)) return -1;
14449#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014450#ifdef CLD_CONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014451 if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014452#endif
14453
14454 /* constants for lockf */
14455#ifdef F_LOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014456 if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014457#endif
14458#ifdef F_TLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014459 if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014460#endif
14461#ifdef F_ULOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014462 if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014463#endif
14464#ifdef F_TEST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014465 if (PyModule_AddIntMacro(m, F_TEST)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014466#endif
14467
Pablo Galindo4defba32018-01-27 16:16:37 +000014468#ifdef RWF_DSYNC
14469 if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
14470#endif
14471#ifdef RWF_HIPRI
14472 if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
14473#endif
14474#ifdef RWF_SYNC
14475 if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
14476#endif
14477#ifdef RWF_NOWAIT
14478 if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
14479#endif
14480
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000014481/* constants for posix_spawn */
14482#ifdef HAVE_POSIX_SPAWN
14483 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
14484 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
14485 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
14486#endif
14487
pxinwrf2d7ac72019-05-21 18:46:37 +080014488#if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014489 if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
14490 if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014491 if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
pxinwrf2d7ac72019-05-21 18:46:37 +080014492#endif
14493#ifdef HAVE_SPAWNV
14494 if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014495 if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
Guido van Rossum246bc171999-02-01 23:54:31 +000014496#endif
14497
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014498#ifdef HAVE_SCHED_H
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014499#ifdef SCHED_OTHER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014500 if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014501#endif
14502#ifdef SCHED_FIFO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014503 if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014504#endif
14505#ifdef SCHED_RR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014506 if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014507#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014508#ifdef SCHED_SPORADIC
messi Liao0d322182017-06-13 22:30:43 +080014509 if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014510#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014511#ifdef SCHED_BATCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014512 if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014513#endif
14514#ifdef SCHED_IDLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014515 if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014516#endif
14517#ifdef SCHED_RESET_ON_FORK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014518 if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014519#endif
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014520#ifdef SCHED_SYS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014521 if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014522#endif
14523#ifdef SCHED_IA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014524 if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014525#endif
14526#ifdef SCHED_FSS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014527 if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014528#endif
14529#ifdef SCHED_FX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014530 if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014531#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014532#endif
14533
Benjamin Peterson9428d532011-09-14 11:45:52 -040014534#ifdef USE_XATTRS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014535 if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
14536 if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
14537 if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
Benjamin Peterson799bd802011-08-31 22:15:17 -040014538#endif
14539
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014540#if HAVE_DECL_RTLD_LAZY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014541 if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014542#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014543#if HAVE_DECL_RTLD_NOW
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014544 if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014545#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014546#if HAVE_DECL_RTLD_GLOBAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014547 if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014548#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014549#if HAVE_DECL_RTLD_LOCAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014550 if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014551#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014552#if HAVE_DECL_RTLD_NODELETE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014553 if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014554#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014555#if HAVE_DECL_RTLD_NOLOAD
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014556 if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014557#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014558#if HAVE_DECL_RTLD_DEEPBIND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014559 if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014560#endif
Michael Feltc5ae1692017-12-19 13:58:49 +010014561#if HAVE_DECL_RTLD_MEMBER
14562 if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
14563#endif
Victor Stinner8b905bd2011-10-25 13:34:04 +020014564
Victor Stinner9b1f4742016-09-06 16:18:52 -070014565#ifdef HAVE_GETRANDOM_SYSCALL
14566 if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
14567 if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
14568#endif
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014569#ifdef HAVE_MEMFD_CREATE
14570 if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
14571 if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
14572#ifdef MFD_HUGETLB
14573 if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014574#endif
14575#ifdef MFD_HUGE_SHIFT
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014576 if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014577#endif
14578#ifdef MFD_HUGE_MASK
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014579 if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014580#endif
14581#ifdef MFD_HUGE_64KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014582 if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014583#endif
14584#ifdef MFD_HUGE_512KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014585 if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014586#endif
14587#ifdef MFD_HUGE_1MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014588 if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014589#endif
14590#ifdef MFD_HUGE_2MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014591 if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014592#endif
14593#ifdef MFD_HUGE_8MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014594 if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014595#endif
14596#ifdef MFD_HUGE_16MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014597 if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014598#endif
14599#ifdef MFD_HUGE_32MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014600 if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014601#endif
14602#ifdef MFD_HUGE_256MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014603 if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014604#endif
14605#ifdef MFD_HUGE_512MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014606 if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014607#endif
14608#ifdef MFD_HUGE_1GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014609 if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014610#endif
14611#ifdef MFD_HUGE_2GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014612 if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014613#endif
14614#ifdef MFD_HUGE_16GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014615 if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
14616#endif
14617#endif
Victor Stinner9b1f4742016-09-06 16:18:52 -070014618
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020014619#if defined(__APPLE__)
14620 if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
14621#endif
14622
Steve Dower2438cdf2019-03-29 16:37:16 -070014623#ifdef MS_WINDOWS
14624 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
14625 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
14626 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
14627 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
14628 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
14629#endif
14630
Victor Stinner8c62be82010-05-06 00:08:46 +000014631 return 0;
Barry Warsaw4a342091996-12-19 23:50:02 +000014632}
14633
14634
Martin v. Löwis1a214512008-06-11 05:26:20 +000014635static struct PyModuleDef posixmodule = {
Victor Stinner8c62be82010-05-06 00:08:46 +000014636 PyModuleDef_HEAD_INIT,
14637 MODNAME,
14638 posix__doc__,
Eddie Elizondob3966632019-11-05 07:16:14 -080014639 sizeof(_posixstate),
Victor Stinner8c62be82010-05-06 00:08:46 +000014640 posix_methods,
14641 NULL,
Eddie Elizondob3966632019-11-05 07:16:14 -080014642 _posix_traverse,
14643 _posix_clear,
14644 _posix_free,
Martin v. Löwis1a214512008-06-11 05:26:20 +000014645};
14646
14647
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014648static const char * const have_functions[] = {
Larry Hastings9cf065c2012-06-22 16:30:09 -070014649
14650#ifdef HAVE_FACCESSAT
14651 "HAVE_FACCESSAT",
14652#endif
14653
14654#ifdef HAVE_FCHDIR
14655 "HAVE_FCHDIR",
14656#endif
14657
14658#ifdef HAVE_FCHMOD
14659 "HAVE_FCHMOD",
14660#endif
14661
14662#ifdef HAVE_FCHMODAT
14663 "HAVE_FCHMODAT",
14664#endif
14665
14666#ifdef HAVE_FCHOWN
14667 "HAVE_FCHOWN",
14668#endif
14669
Larry Hastings00964ed2013-08-12 13:49:30 -040014670#ifdef HAVE_FCHOWNAT
14671 "HAVE_FCHOWNAT",
14672#endif
14673
Larry Hastings9cf065c2012-06-22 16:30:09 -070014674#ifdef HAVE_FEXECVE
14675 "HAVE_FEXECVE",
14676#endif
14677
14678#ifdef HAVE_FDOPENDIR
14679 "HAVE_FDOPENDIR",
14680#endif
14681
Georg Brandl306336b2012-06-24 12:55:33 +020014682#ifdef HAVE_FPATHCONF
14683 "HAVE_FPATHCONF",
14684#endif
14685
Larry Hastings9cf065c2012-06-22 16:30:09 -070014686#ifdef HAVE_FSTATAT
14687 "HAVE_FSTATAT",
14688#endif
14689
14690#ifdef HAVE_FSTATVFS
14691 "HAVE_FSTATVFS",
14692#endif
14693
Steve Dowerfe0a41a2015-03-20 19:50:46 -070014694#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Georg Brandl306336b2012-06-24 12:55:33 +020014695 "HAVE_FTRUNCATE",
14696#endif
14697
Larry Hastings9cf065c2012-06-22 16:30:09 -070014698#ifdef HAVE_FUTIMENS
14699 "HAVE_FUTIMENS",
14700#endif
14701
14702#ifdef HAVE_FUTIMES
14703 "HAVE_FUTIMES",
14704#endif
14705
14706#ifdef HAVE_FUTIMESAT
14707 "HAVE_FUTIMESAT",
14708#endif
14709
14710#ifdef HAVE_LINKAT
14711 "HAVE_LINKAT",
14712#endif
14713
14714#ifdef HAVE_LCHFLAGS
14715 "HAVE_LCHFLAGS",
14716#endif
14717
14718#ifdef HAVE_LCHMOD
14719 "HAVE_LCHMOD",
14720#endif
14721
14722#ifdef HAVE_LCHOWN
14723 "HAVE_LCHOWN",
14724#endif
14725
14726#ifdef HAVE_LSTAT
14727 "HAVE_LSTAT",
14728#endif
14729
14730#ifdef HAVE_LUTIMES
14731 "HAVE_LUTIMES",
14732#endif
14733
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014734#ifdef HAVE_MEMFD_CREATE
14735 "HAVE_MEMFD_CREATE",
14736#endif
14737
Larry Hastings9cf065c2012-06-22 16:30:09 -070014738#ifdef HAVE_MKDIRAT
14739 "HAVE_MKDIRAT",
14740#endif
14741
14742#ifdef HAVE_MKFIFOAT
14743 "HAVE_MKFIFOAT",
14744#endif
14745
14746#ifdef HAVE_MKNODAT
14747 "HAVE_MKNODAT",
14748#endif
14749
14750#ifdef HAVE_OPENAT
14751 "HAVE_OPENAT",
14752#endif
14753
14754#ifdef HAVE_READLINKAT
14755 "HAVE_READLINKAT",
14756#endif
14757
14758#ifdef HAVE_RENAMEAT
14759 "HAVE_RENAMEAT",
14760#endif
14761
14762#ifdef HAVE_SYMLINKAT
14763 "HAVE_SYMLINKAT",
14764#endif
14765
14766#ifdef HAVE_UNLINKAT
14767 "HAVE_UNLINKAT",
14768#endif
14769
14770#ifdef HAVE_UTIMENSAT
14771 "HAVE_UTIMENSAT",
14772#endif
14773
14774#ifdef MS_WINDOWS
14775 "MS_WINDOWS",
14776#endif
14777
14778 NULL
14779};
14780
14781
Mark Hammondfe51c6d2002-08-02 02:27:13 +000014782PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +000014783INITFUNC(void)
Guido van Rossumb6775db1994-08-01 11:34:53 +000014784{
Victor Stinner8c62be82010-05-06 00:08:46 +000014785 PyObject *m, *v;
Larry Hastings9cf065c2012-06-22 16:30:09 -070014786 PyObject *list;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014787 const char * const *trace;
Tim Peters5aa91602002-01-30 05:46:57 +000014788
Eddie Elizondob3966632019-11-05 07:16:14 -080014789 m = PyState_FindModule(&posixmodule);
14790 if (m != NULL) {
14791 Py_INCREF(m);
14792 return m;
14793 }
14794
Victor Stinner8c62be82010-05-06 00:08:46 +000014795 m = PyModule_Create(&posixmodule);
14796 if (m == NULL)
14797 return NULL;
Tim Peters5aa91602002-01-30 05:46:57 +000014798
Victor Stinner8c62be82010-05-06 00:08:46 +000014799 /* Initialize environ dictionary */
14800 v = convertenviron();
14801 Py_XINCREF(v);
14802 if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
14803 return NULL;
14804 Py_DECREF(v);
Fred Drakec9680921999-12-13 16:37:25 +000014805
Victor Stinner8c62be82010-05-06 00:08:46 +000014806 if (all_ins(m))
14807 return NULL;
Barry Warsaw4a342091996-12-19 23:50:02 +000014808
Victor Stinner8c62be82010-05-06 00:08:46 +000014809 if (setup_confname_tables(m))
14810 return NULL;
Fred Drakebec628d1999-12-15 18:31:10 +000014811
Victor Stinner8c62be82010-05-06 00:08:46 +000014812 Py_INCREF(PyExc_OSError);
14813 PyModule_AddObject(m, "error", PyExc_OSError);
Fred Drake762e2061999-08-26 17:23:54 +000014814
Ross Lagerwall7807c352011-03-17 20:20:30 +020014815#if defined(HAVE_WAITID) && !defined(__APPLE__)
Eddie Elizondob3966632019-11-05 07:16:14 -080014816 waitid_result_desc.name = MODNAME ".waitid_result";
14817 PyObject *WaitidResultType = (PyObject *)PyStructSequence_NewType(&waitid_result_desc);
14818 if (WaitidResultType == NULL) {
14819 return NULL;
14820 }
14821 Py_INCREF(WaitidResultType);
14822 PyModule_AddObject(m, "waitid_result", WaitidResultType);
Hai Shif707d942020-03-16 21:15:01 +080014823 get_posix_state(m)->WaitidResultType = WaitidResultType;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014824#endif
14825
Eddie Elizondob3966632019-11-05 07:16:14 -080014826 stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
14827 stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
14828 stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
14829 stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
14830 PyObject *StatResultType = (PyObject *)PyStructSequence_NewType(&stat_result_desc);
14831 if (StatResultType == NULL) {
14832 return NULL;
14833 }
14834 Py_INCREF(StatResultType);
14835 PyModule_AddObject(m, "stat_result", StatResultType);
Hai Shif707d942020-03-16 21:15:01 +080014836 get_posix_state(m)->StatResultType = StatResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014837 structseq_new = ((PyTypeObject *)StatResultType)->tp_new;
14838 ((PyTypeObject *)StatResultType)->tp_new = statresult_new;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014839
Eddie Elizondob3966632019-11-05 07:16:14 -080014840 statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
14841 PyObject *StatVFSResultType = (PyObject *)PyStructSequence_NewType(&statvfs_result_desc);
14842 if (StatVFSResultType == NULL) {
14843 return NULL;
14844 }
14845 Py_INCREF(StatVFSResultType);
14846 PyModule_AddObject(m, "statvfs_result", StatVFSResultType);
Hai Shif707d942020-03-16 21:15:01 +080014847 get_posix_state(m)->StatVFSResultType = StatVFSResultType;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014848#ifdef NEED_TICKS_PER_SECOND
14849# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Eddie Elizondob3966632019-11-05 07:16:14 -080014850 ticks_per_second = sysconf(_SC_CLK_TCK);
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014851# elif defined(HZ)
Eddie Elizondob3966632019-11-05 07:16:14 -080014852 ticks_per_second = HZ;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014853# else
Eddie Elizondob3966632019-11-05 07:16:14 -080014854 ticks_per_second = 60; /* magic fallback value; may be bogus */
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014855# endif
14856#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014857
William Orr81574b82018-10-01 22:19:56 -070014858#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Eddie Elizondob3966632019-11-05 07:16:14 -080014859 sched_param_desc.name = MODNAME ".sched_param";
14860 PyObject *SchedParamType = (PyObject *)PyStructSequence_NewType(&sched_param_desc);
14861 if (SchedParamType == NULL) {
14862 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000014863 }
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014864 Py_INCREF(SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -080014865 PyModule_AddObject(m, "sched_param", SchedParamType);
Hai Shif707d942020-03-16 21:15:01 +080014866 get_posix_state(m)->SchedParamType = SchedParamType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014867 ((PyTypeObject *)SchedParamType)->tp_new = os_sched_param;
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014868#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +000014869
Eddie Elizondob3966632019-11-05 07:16:14 -080014870 /* initialize TerminalSize_info */
14871 PyObject *TerminalSizeType = (PyObject *)PyStructSequence_NewType(&TerminalSize_desc);
14872 if (TerminalSizeType == NULL) {
14873 return NULL;
14874 }
14875 Py_INCREF(TerminalSizeType);
14876 PyModule_AddObject(m, "terminal_size", TerminalSizeType);
Hai Shif707d942020-03-16 21:15:01 +080014877 get_posix_state(m)->TerminalSizeType = TerminalSizeType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014878
14879 /* initialize scandir types */
14880 PyObject *ScandirIteratorType = PyType_FromSpec(&ScandirIteratorType_spec);
14881 if (ScandirIteratorType == NULL) {
14882 return NULL;
14883 }
Hai Shif707d942020-03-16 21:15:01 +080014884 get_posix_state(m)->ScandirIteratorType = ScandirIteratorType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014885
14886 PyObject *DirEntryType = PyType_FromSpec(&DirEntryType_spec);
14887 if (DirEntryType == NULL) {
14888 return NULL;
14889 }
14890 Py_INCREF(DirEntryType);
14891 PyModule_AddObject(m, "DirEntry", DirEntryType);
Hai Shif707d942020-03-16 21:15:01 +080014892 get_posix_state(m)->DirEntryType = DirEntryType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014893
Larry Hastings605a62d2012-06-24 04:33:36 -070014894 times_result_desc.name = MODNAME ".times_result";
Eddie Elizondob3966632019-11-05 07:16:14 -080014895 PyObject *TimesResultType = (PyObject *)PyStructSequence_NewType(&times_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014896 if (TimesResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014897 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014898 }
Eddie Elizondob3966632019-11-05 07:16:14 -080014899 Py_INCREF(TimesResultType);
14900 PyModule_AddObject(m, "times_result", TimesResultType);
Hai Shif707d942020-03-16 21:15:01 +080014901 get_posix_state(m)->TimesResultType = TimesResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070014902
Eddie Elizondob3966632019-11-05 07:16:14 -080014903 PyTypeObject *UnameResultType = PyStructSequence_NewType(&uname_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014904 if (UnameResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014905 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014906 }
Eddie Elizondob3966632019-11-05 07:16:14 -080014907 Py_INCREF(UnameResultType);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014908 PyModule_AddObject(m, "uname_result", (PyObject *)UnameResultType);
Hai Shif707d942020-03-16 21:15:01 +080014909 get_posix_state(m)->UnameResultType = (PyObject *)UnameResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070014910
Thomas Wouters477c8d52006-05-27 19:21:47 +000014911#ifdef __APPLE__
Victor Stinner8c62be82010-05-06 00:08:46 +000014912 /*
14913 * Step 2 of weak-linking support on Mac OS X.
14914 *
14915 * The code below removes functions that are not available on the
14916 * currently active platform.
14917 *
14918 * This block allow one to use a python binary that was build on
Larry Hastings9cf065c2012-06-22 16:30:09 -070014919 * OSX 10.4 on OSX 10.3, without losing access to new APIs on
Victor Stinner8c62be82010-05-06 00:08:46 +000014920 * OSX 10.4.
14921 */
Thomas Wouters477c8d52006-05-27 19:21:47 +000014922#ifdef HAVE_FSTATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014923 if (fstatvfs == NULL) {
14924 if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
14925 return NULL;
14926 }
14927 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014928#endif /* HAVE_FSTATVFS */
14929
14930#ifdef HAVE_STATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014931 if (statvfs == NULL) {
14932 if (PyObject_DelAttrString(m, "statvfs") == -1) {
14933 return NULL;
14934 }
14935 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014936#endif /* HAVE_STATVFS */
14937
14938# ifdef HAVE_LCHOWN
Victor Stinner8c62be82010-05-06 00:08:46 +000014939 if (lchown == NULL) {
14940 if (PyObject_DelAttrString(m, "lchown") == -1) {
14941 return NULL;
14942 }
14943 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014944#endif /* HAVE_LCHOWN */
14945
14946
14947#endif /* __APPLE__ */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014948
Hai Shif707d942020-03-16 21:15:01 +080014949 if ((get_posix_state(m)->billion = PyLong_FromLong(1000000000)) == NULL)
Eddie Elizondob3966632019-11-05 07:16:14 -080014950 return NULL;
14951#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
Hai Shif707d942020-03-16 21:15:01 +080014952 get_posix_state(m)->struct_rusage = PyUnicode_InternFromString("struct_rusage");
14953 if (get_posix_state(m)->struct_rusage == NULL)
Eddie Elizondob3966632019-11-05 07:16:14 -080014954 return NULL;
14955#endif
Hai Shif707d942020-03-16 21:15:01 +080014956 get_posix_state(m)->st_mode = PyUnicode_InternFromString("st_mode");
14957 if (get_posix_state(m)->st_mode == NULL)
Larry Hastings6fe20b32012-04-19 15:07:49 -070014958 return NULL;
14959
Larry Hastings9cf065c2012-06-22 16:30:09 -070014960 /* suppress "function not used" warnings */
14961 {
14962 int ignored;
14963 fd_specified("", -1);
14964 follow_symlinks_specified("", 1);
14965 dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
14966 dir_fd_converter(Py_None, &ignored);
14967 dir_fd_unavailable(Py_None, &ignored);
14968 }
14969
14970 /*
14971 * provide list of locally available functions
14972 * so os.py can populate support_* lists
14973 */
14974 list = PyList_New(0);
14975 if (!list)
14976 return NULL;
14977 for (trace = have_functions; *trace; trace++) {
14978 PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
14979 if (!unicode)
14980 return NULL;
14981 if (PyList_Append(list, unicode))
14982 return NULL;
14983 Py_DECREF(unicode);
14984 }
14985 PyModule_AddObject(m, "_have_functions", list);
Ned Deilyeb3be662016-08-15 14:40:38 -040014986
Victor Stinner8c62be82010-05-06 00:08:46 +000014987 return m;
Guido van Rossumb6775db1994-08-01 11:34:53 +000014988}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014989
14990#ifdef __cplusplus
14991}
14992#endif