blob: ffee87cbf11e4905920eb7daf60dd93c6fa32f19 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* POSIX module implementation */
3
Jesus Ceaab70e2a2012-10-05 01:48:08 +02004/* This file is also used for Windows NT/MS-Win. In that case the
5 module actually calls itself 'nt', not 'posix', and a few
Andrew MacIntyre6c73af22002-03-03 03:07:07 +00006 functions are either unimplemented or implemented differently. The source
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00007 assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent
Guido van Rossumad0ee831995-03-01 10:34:45 +00008 of the compiler used. Different compilers define their own feature
Victor Stinnerf427a142014-10-22 12:33:23 +02009 test macro, e.g. '_MSC_VER'. */
Guido van Rossumad0ee831995-03-01 10:34:45 +000010
Larry Hastings31826802013-10-19 00:09:25 -070011
12
Thomas Wouters477c8d52006-05-27 19:21:47 +000013#ifdef __APPLE__
14 /*
Victor Stinner8c62be82010-05-06 00:08:46 +000015 * Step 1 of support for weak-linking a number of symbols existing on
Thomas Wouters477c8d52006-05-27 19:21:47 +000016 * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block
17 * at the end of this file for more information.
18 */
19# pragma weak lchown
20# pragma weak statvfs
21# pragma weak fstatvfs
22
23#endif /* __APPLE__ */
24
Thomas Wouters68bc4f92006-03-01 01:05:10 +000025#define PY_SSIZE_T_CLEAN
26
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000027#include "Python.h"
Victor Stinnerd5d9e812019-05-13 12:35:37 +020028#ifdef MS_WINDOWS
29 /* include <windows.h> early to avoid conflict with pycore_condvar.h:
30
31 #define WIN32_LEAN_AND_MEAN
32 #include <windows.h>
33
34 FSCTL_GET_REPARSE_POINT is not exported with WIN32_LEAN_AND_MEAN. */
35# include <windows.h>
36#endif
37
38#include "pycore_ceval.h" /* _PyEval_ReInitThreads() */
Victor Stinner01b63ec2019-06-19 00:48:09 +020039#include "pycore_import.h" /* _PyImport_ReInitLock() */
Victor Stinnerd5d9e812019-05-13 12:35:37 +020040#include "pycore_pystate.h" /* _PyRuntime */
Antoine Pitrou346cbd32017-05-27 17:50:54 +020041#include "pythread.h"
Victor Stinner6036e442015-03-08 01:58:04 +010042#include "structmember.h"
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020043#ifndef MS_WINDOWS
Victor Stinnerd5d9e812019-05-13 12:35:37 +020044# include "posixmodule.h"
Tim Golden0321cf22014-05-05 19:46:17 +010045#else
Victor Stinnerd5d9e812019-05-13 12:35:37 +020046# include "winreparse.h"
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020047#endif
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000048
Stefan Krahfb7c8ae2016-04-26 17:04:18 +020049/* On android API level 21, 'AT_EACCESS' is not declared although
50 * HAVE_FACCESSAT is defined. */
51#ifdef __ANDROID__
52#undef HAVE_FACCESSAT
53#endif
54
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)fa76eee2016-05-28 21:03:48 +000055#include <stdio.h> /* needed for ctermid() */
56
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057#ifdef __cplusplus
58extern "C" {
59#endif
60
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000061PyDoc_STRVAR(posix__doc__,
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000062"This module provides access to operating system functionality that is\n\
63standardized by the C Standard and the POSIX standard (a thinly\n\
64disguised Unix interface). Refer to the library manual and\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000065corresponding Unix manual entries for more information on calls.");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000066
Martin v. Löwis0073f2e2002-11-21 23:52:35 +000067
Ross Lagerwall4d076da2011-03-18 06:56:53 +020068#ifdef HAVE_SYS_UIO_H
69#include <sys/uio.h>
70#endif
71
Christian Heimes75b96182017-09-05 15:53:09 +020072#ifdef HAVE_SYS_SYSMACROS_H
73/* GNU C Library: major(), minor(), makedev() */
74#include <sys/sysmacros.h>
75#endif
76
Thomas Wouters0e3f5912006-08-11 14:57:12 +000077#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000078#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000079#endif /* HAVE_SYS_TYPES_H */
80
81#ifdef HAVE_SYS_STAT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000082#include <sys/stat.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000083#endif /* HAVE_SYS_STAT_H */
Guido van Rossuma6535fd2001-10-18 19:44:10 +000084
Guido van Rossum36bc6801995-06-14 22:54:23 +000085#ifdef HAVE_SYS_WAIT_H
Victor Stinner8c62be82010-05-06 00:08:46 +000086#include <sys/wait.h> /* For WNOHANG */
Guido van Rossum36bc6801995-06-14 22:54:23 +000087#endif
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080088#ifdef HAVE_LINUX_WAIT_H
89#include <linux/wait.h> // For P_PIDFD
90#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +000091
Thomas Wouters0e3f5912006-08-11 14:57:12 +000092#ifdef HAVE_SIGNAL_H
Guido van Rossuma376cc51996-12-05 23:43:35 +000093#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000094#endif
Guido van Rossuma376cc51996-12-05 23:43:35 +000095
Guido van Rossumb6775db1994-08-01 11:34:53 +000096#ifdef HAVE_FCNTL_H
97#include <fcntl.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +000098#endif /* HAVE_FCNTL_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +000099
Guido van Rossuma6535fd2001-10-18 19:44:10 +0000100#ifdef HAVE_GRP_H
101#include <grp.h>
102#endif
103
Barry Warsaw5676bd12003-01-07 20:57:09 +0000104#ifdef HAVE_SYSEXITS_H
105#include <sysexits.h>
106#endif /* HAVE_SYSEXITS_H */
107
Anthony Baxter8a560de2004-10-13 15:30:56 +0000108#ifdef HAVE_SYS_LOADAVG_H
109#include <sys/loadavg.h>
110#endif
111
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000112#ifdef HAVE_SYS_SENDFILE_H
113#include <sys/sendfile.h>
114#endif
115
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +0200116#if defined(__APPLE__)
117#include <copyfile.h>
118#endif
119
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500120#ifdef HAVE_SCHED_H
121#include <sched.h>
122#endif
123
Pablo Galindoaac4d032019-05-31 19:39:47 +0100124#ifdef HAVE_COPY_FILE_RANGE
125#include <unistd.h>
126#endif
127
Benjamin Peterson2dbda072012-03-16 10:12:55 -0500128#if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
Benjamin Peterson7b51b8d2012-03-14 22:28:25 -0500129#undef HAVE_SCHED_SETAFFINITY
130#endif
131
doko@ubuntu.com4a173bc2014-04-17 19:47:16 +0200132#if defined(HAVE_SYS_XATTR_H) && defined(__GLIBC__) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
Benjamin Peterson9428d532011-09-14 11:45:52 -0400133#define USE_XATTRS
134#endif
135
136#ifdef USE_XATTRS
Benjamin Petersonb77fe172011-09-13 17:20:47 -0400137#include <sys/xattr.h>
Benjamin Peterson799bd802011-08-31 22:15:17 -0400138#endif
139
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000140#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
141#ifdef HAVE_SYS_SOCKET_H
142#include <sys/socket.h>
143#endif
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000144#endif
145
Victor Stinner8b905bd2011-10-25 13:34:04 +0200146#ifdef HAVE_DLFCN_H
147#include <dlfcn.h>
148#endif
149
Charles-Francois Natali44feda32013-05-20 14:40:46 +0200150#ifdef __hpux
151#include <sys/mpctl.h>
152#endif
153
154#if defined(__DragonFly__) || \
155 defined(__OpenBSD__) || \
156 defined(__FreeBSD__) || \
157 defined(__NetBSD__) || \
158 defined(__APPLE__)
159#include <sys/sysctl.h>
160#endif
161
Victor Stinner9b1f4742016-09-06 16:18:52 -0700162#ifdef HAVE_LINUX_RANDOM_H
163# include <linux/random.h>
164#endif
165#ifdef HAVE_GETRANDOM_SYSCALL
166# include <sys/syscall.h>
167#endif
168
Antoine Pitroubcf2b592012-02-08 23:28:36 +0100169#if defined(MS_WINDOWS)
170# define TERMSIZE_USE_CONIO
171#elif defined(HAVE_SYS_IOCTL_H)
172# include <sys/ioctl.h>
173# if defined(HAVE_TERMIOS_H)
174# include <termios.h>
175# endif
176# if defined(TIOCGWINSZ)
177# define TERMSIZE_USE_IOCTL
178# endif
179#endif /* MS_WINDOWS */
180
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000181/* Various compilers have only certain posix functions */
Martin v. Löwis4f1cd8b2001-07-26 13:41:06 +0000182/* XXX Gosh I wish these were all moved into pyconfig.h */
Victor Stinner8c62be82010-05-06 00:08:46 +0000183#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000184#define HAVE_OPENDIR 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000185#define HAVE_SYSTEM 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000186#include <process.h>
187#else
Victor Stinner8c62be82010-05-06 00:08:46 +0000188#ifdef _MSC_VER /* Microsoft compiler */
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +0000189#define HAVE_GETPPID 1
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000190#define HAVE_GETLOGIN 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000191#define HAVE_SPAWNV 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000192#define HAVE_EXECV 1
Steve Dowercc16be82016-09-08 10:35:16 -0700193#define HAVE_WSPAWNV 1
194#define HAVE_WEXECV 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000195#define HAVE_PIPE 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000196#define HAVE_SYSTEM 1
197#define HAVE_CWAIT 1
198#define HAVE_FSYNC 1
Tim Peters11b23062003-04-23 02:39:17 +0000199#define fsync _commit
Andrew MacIntyre6c73af22002-03-03 03:07:07 +0000200#else
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000201/* Unix functions that the configure script doesn't check for */
pxinwrf2d7ac72019-05-21 18:46:37 +0800202#ifndef __VXWORKS__
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000203#define HAVE_EXECV 1
204#define HAVE_FORK 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000205#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */
Guido van Rossum2242f2f2001-04-11 20:58:20 +0000206#define HAVE_FORK1 1
207#endif
pxinwrf2d7ac72019-05-21 18:46:37 +0800208#endif
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000209#define HAVE_GETEGID 1
210#define HAVE_GETEUID 1
211#define HAVE_GETGID 1
212#define HAVE_GETPPID 1
213#define HAVE_GETUID 1
214#define HAVE_KILL 1
215#define HAVE_OPENDIR 1
216#define HAVE_PIPE 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000217#define HAVE_SYSTEM 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000218#define HAVE_WAIT 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000219#define HAVE_TTYNAME 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000220#endif /* _MSC_VER */
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000221#endif /* ! __WATCOMC__ || __QNX__ */
Guido van Rossumad0ee831995-03-01 10:34:45 +0000222
Eddie Elizondob3966632019-11-05 07:16:14 -0800223_Py_IDENTIFIER(__fspath__);
Victor Stinnera2f7c002012-02-08 03:36:25 +0100224
Larry Hastings61272b72014-01-07 12:41:53 -0800225/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +1000226# one of the few times we lie about this name!
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800227module os
Larry Hastings61272b72014-01-07 12:41:53 -0800228[clinic start generated code]*/
Larry Hastings2f936352014-08-05 14:04:04 +1000229/*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
Victor Stinnera2f7c002012-02-08 03:36:25 +0100230
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000231#ifndef _MSC_VER
Guido van Rossum36bc6801995-06-14 22:54:23 +0000232
Martin v. Löwis8eb92a02002-09-19 08:03:21 +0000233#if defined(__sgi)&&_COMPILER_VERSION>=700
234/* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
235 (default) */
236extern char *ctermid_r(char *);
237#endif
238
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000239#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000240
pxinwrf2d7ac72019-05-21 18:46:37 +0800241#if defined(__VXWORKS__)
242#include <vxCpuLib.h>
243#include <rtpLib.h>
244#include <wait.h>
245#include <taskLib.h>
246#ifndef _P_WAIT
247#define _P_WAIT 0
248#define _P_NOWAIT 1
249#define _P_NOWAITO 1
250#endif
251#endif /* __VXWORKS__ */
252
Pablo Galindo6c6ddf92018-01-29 01:56:10 +0000253#ifdef HAVE_POSIX_SPAWN
254#include <spawn.h>
255#endif
256
Guido van Rossumb6775db1994-08-01 11:34:53 +0000257#ifdef HAVE_UTIME_H
258#include <utime.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000259#endif /* HAVE_UTIME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000260
Guido van Rossum14ed0b21994-09-29 09:50:09 +0000261#ifdef HAVE_SYS_UTIME_H
262#include <sys/utime.h>
263#define HAVE_UTIME_H /* pretend we do for the rest of this file */
264#endif /* HAVE_SYS_UTIME_H */
265
Guido van Rossumb6775db1994-08-01 11:34:53 +0000266#ifdef HAVE_SYS_TIMES_H
267#include <sys/times.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000268#endif /* HAVE_SYS_TIMES_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000269
270#ifdef HAVE_SYS_PARAM_H
271#include <sys/param.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000272#endif /* HAVE_SYS_PARAM_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000273
274#ifdef HAVE_SYS_UTSNAME_H
275#include <sys/utsname.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000276#endif /* HAVE_SYS_UTSNAME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000277
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000278#ifdef HAVE_DIRENT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000279#include <dirent.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000280#define NAMLEN(dirent) strlen((dirent)->d_name)
281#else
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000282#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000283#include <direct.h>
284#define NAMLEN(dirent) strlen((dirent)->d_name)
285#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000286#define dirent direct
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000287#define NAMLEN(dirent) (dirent)->d_namlen
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000288#endif
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000289#ifdef HAVE_SYS_NDIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000290#include <sys/ndir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000291#endif
292#ifdef HAVE_SYS_DIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000293#include <sys/dir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000294#endif
295#ifdef HAVE_NDIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000296#include <ndir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000297#endif
298#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000299
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000300#ifdef _MSC_VER
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000301#ifdef HAVE_DIRECT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000302#include <direct.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000303#endif
304#ifdef HAVE_IO_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000305#include <io.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000306#endif
307#ifdef HAVE_PROCESS_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000308#include <process.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000309#endif
Raymond Hettinger0291c9f2010-08-01 21:10:35 +0000310#ifndef IO_REPARSE_TAG_SYMLINK
Amaury Forgeot d'Arc844807e2010-08-16 22:16:51 +0000311#define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
Raymond Hettinger0291c9f2010-08-01 21:10:35 +0000312#endif
Tim Golden0321cf22014-05-05 19:46:17 +0100313#ifndef IO_REPARSE_TAG_MOUNT_POINT
314#define IO_REPARSE_TAG_MOUNT_POINT (0xA0000003L)
315#endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000316#include "osdefs.h"
Kristján Valur Jónssonf64e6512009-04-13 10:16:14 +0000317#include <malloc.h>
Guido van Rossumb6775db1994-08-01 11:34:53 +0000318#include <windows.h>
Victor Stinner8c62be82010-05-06 00:08:46 +0000319#include <shellapi.h> /* for ShellExecute() */
Brian Curtine8e4b3b2010-09-23 20:04:14 +0000320#include <lmcons.h> /* for UNLEN */
Brian Curtin52173d42010-12-02 18:29:18 +0000321#define HAVE_SYMLINK
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000322#endif /* _MSC_VER */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000323
Tim Petersbc2e10e2002-03-03 23:17:02 +0000324#ifndef MAXPATHLEN
Thomas Wouters477c8d52006-05-27 19:21:47 +0000325#if defined(PATH_MAX) && PATH_MAX > 1024
326#define MAXPATHLEN PATH_MAX
327#else
Tim Petersbc2e10e2002-03-03 23:17:02 +0000328#define MAXPATHLEN 1024
Thomas Wouters477c8d52006-05-27 19:21:47 +0000329#endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000330#endif /* MAXPATHLEN */
331
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000332#ifdef UNION_WAIT
333/* Emulate some macros on systems that have a union instead of macros */
334
335#ifndef WIFEXITED
336#define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
337#endif
338
339#ifndef WEXITSTATUS
340#define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
341#endif
342
343#ifndef WTERMSIG
344#define WTERMSIG(u_wait) ((u_wait).w_termsig)
345#endif
346
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000347#define WAIT_TYPE union wait
348#define WAIT_STATUS_INT(s) (s.w_status)
349
350#else /* !UNION_WAIT */
351#define WAIT_TYPE int
352#define WAIT_STATUS_INT(s) (s)
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000353#endif /* UNION_WAIT */
354
Greg Wardb48bc172000-03-01 21:51:56 +0000355/* Don't use the "_r" form if we don't need it (also, won't have a
356 prototype for it, at least on Solaris -- maybe others as well?). */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200357#if defined(HAVE_CTERMID_R)
Greg Wardb48bc172000-03-01 21:51:56 +0000358#define USE_CTERMID_R
359#endif
360
Fred Drake699f3522000-06-29 21:12:41 +0000361/* choose the appropriate stat and fstat functions and return structs */
Guido van Rossum64529cd2000-06-30 22:45:12 +0000362#undef STAT
Antoine Pitroue47e0932011-01-19 15:21:35 +0000363#undef FSTAT
364#undef STRUCT_STAT
Victor Stinner14b9b112013-06-25 00:37:25 +0200365#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +0000366# define STAT win32_stat
Larry Hastings9cf065c2012-06-22 16:30:09 -0700367# define LSTAT win32_lstat
Victor Stinnere134a7f2015-03-30 10:09:31 +0200368# define FSTAT _Py_fstat_noraise
Steve Dowerf2f373f2015-02-21 08:44:05 -0800369# define STRUCT_STAT struct _Py_stat_struct
Fred Drake699f3522000-06-29 21:12:41 +0000370#else
Victor Stinner8c62be82010-05-06 00:08:46 +0000371# define STAT stat
Larry Hastings9cf065c2012-06-22 16:30:09 -0700372# define LSTAT lstat
Victor Stinner8c62be82010-05-06 00:08:46 +0000373# define FSTAT fstat
374# define STRUCT_STAT struct stat
Fred Drake699f3522000-06-29 21:12:41 +0000375#endif
376
Tim Peters11b23062003-04-23 02:39:17 +0000377#if defined(MAJOR_IN_MKDEV)
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000378#include <sys/mkdev.h>
379#else
380#if defined(MAJOR_IN_SYSMACROS)
381#include <sys/sysmacros.h>
382#endif
Neal Norwitz3d949422002-04-20 13:46:43 +0000383#if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
384#include <sys/mkdev.h>
385#endif
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000386#endif
Fred Drake699f3522000-06-29 21:12:41 +0000387
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200388#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +0100389#define INITFUNC PyInit_nt
390#define MODNAME "nt"
391#else
392#define INITFUNC PyInit_posix
393#define MODNAME "posix"
394#endif
395
jcea6c51d512018-01-28 14:00:08 +0100396#if defined(__sun)
397/* Something to implement in autoconf, not present in autoconf 2.69 */
398#define HAVE_STRUCT_STAT_ST_FSTYPE 1
399#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200400
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600401/* memfd_create is either defined in sys/mman.h or sys/memfd.h
402 * linux/memfd.h defines additional flags
403 */
404#ifdef HAVE_SYS_MMAN_H
405#include <sys/mman.h>
406#endif
407#ifdef HAVE_SYS_MEMFD_H
408#include <sys/memfd.h>
409#endif
410#ifdef HAVE_LINUX_MEMFD_H
411#include <linux/memfd.h>
412#endif
413
Gregory P. Smith1d300ce2018-12-30 21:13:02 -0800414#ifdef _Py_MEMORY_SANITIZER
415# include <sanitizer/msan_interface.h>
416#endif
417
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200418#ifdef HAVE_FORK
419static void
420run_at_forkers(PyObject *lst, int reverse)
421{
422 Py_ssize_t i;
423 PyObject *cpy;
424
425 if (lst != NULL) {
426 assert(PyList_CheckExact(lst));
427
428 /* Use a list copy in case register_at_fork() is called from
429 * one of the callbacks.
430 */
431 cpy = PyList_GetSlice(lst, 0, PyList_GET_SIZE(lst));
432 if (cpy == NULL)
433 PyErr_WriteUnraisable(lst);
434 else {
435 if (reverse)
436 PyList_Reverse(cpy);
437 for (i = 0; i < PyList_GET_SIZE(cpy); i++) {
438 PyObject *func, *res;
439 func = PyList_GET_ITEM(cpy, i);
Jeroen Demeyer7f41c8e2019-07-04 12:35:31 +0200440 res = _PyObject_CallNoArg(func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200441 if (res == NULL)
442 PyErr_WriteUnraisable(func);
443 else
444 Py_DECREF(res);
445 }
446 Py_DECREF(cpy);
447 }
448 }
449}
450
451void
452PyOS_BeforeFork(void)
453{
Victor Stinnerff4584c2020-03-13 18:03:56 +0100454 run_at_forkers(_PyInterpreterState_GET_UNSAFE()->before_forkers, 1);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200455
456 _PyImport_AcquireLock();
457}
458
459void
460PyOS_AfterFork_Parent(void)
461{
462 if (_PyImport_ReleaseLock() <= 0)
463 Py_FatalError("failed releasing import lock after fork");
464
Victor Stinnerff4584c2020-03-13 18:03:56 +0100465 run_at_forkers(_PyInterpreterState_GET_UNSAFE()->after_forkers_parent, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200466}
467
468void
469PyOS_AfterFork_Child(void)
470{
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200471 _PyRuntimeState *runtime = &_PyRuntime;
472 _PyGILState_Reinit(runtime);
Victor Stinnerd5d9e812019-05-13 12:35:37 +0200473 _PyEval_ReInitThreads(runtime);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200474 _PyImport_ReInitLock();
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200475 _PySignal_AfterFork();
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200476 _PyRuntimeState_ReInitThreads(runtime);
Victor Stinnerb49858b2019-05-24 15:20:23 +0200477 _PyInterpreterState_DeleteExceptMain(runtime);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200478
Victor Stinnerff4584c2020-03-13 18:03:56 +0100479 run_at_forkers(_PyInterpreterState_GET_UNSAFE()->after_forkers_child, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200480}
481
482static int
483register_at_forker(PyObject **lst, PyObject *func)
484{
Gregory P. Smith163468a2017-05-29 10:03:41 -0700485 if (func == NULL) /* nothing to register? do nothing. */
486 return 0;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200487 if (*lst == NULL) {
488 *lst = PyList_New(0);
489 if (*lst == NULL)
490 return -1;
491 }
492 return PyList_Append(*lst, func);
493}
494#endif
495
496/* Legacy wrapper */
497void
498PyOS_AfterFork(void)
499{
500#ifdef HAVE_FORK
501 PyOS_AfterFork_Child();
502#endif
503}
504
505
Victor Stinner6036e442015-03-08 01:58:04 +0100506#ifdef MS_WINDOWS
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200507/* defined in fileutils.c */
Benjamin Petersone5024512018-09-12 12:06:42 -0700508void _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
509void _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *,
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200510 ULONG, struct _Py_stat_struct *);
511#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700512
Larry Hastings9cf065c2012-06-22 16:30:09 -0700513
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200514#ifndef MS_WINDOWS
515PyObject *
516_PyLong_FromUid(uid_t uid)
517{
518 if (uid == (uid_t)-1)
519 return PyLong_FromLong(-1);
520 return PyLong_FromUnsignedLong(uid);
521}
522
523PyObject *
524_PyLong_FromGid(gid_t gid)
525{
526 if (gid == (gid_t)-1)
527 return PyLong_FromLong(-1);
528 return PyLong_FromUnsignedLong(gid);
529}
530
531int
532_Py_Uid_Converter(PyObject *obj, void *p)
533{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700534 uid_t uid;
535 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200536 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200537 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700538 unsigned long uresult;
539
540 index = PyNumber_Index(obj);
541 if (index == NULL) {
542 PyErr_Format(PyExc_TypeError,
543 "uid should be integer, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800544 _PyType_Name(Py_TYPE(obj)));
Serhiy Storchakab4621892013-02-10 23:28:02 +0200545 return 0;
546 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700547
548 /*
549 * Handling uid_t is complicated for two reasons:
550 * * Although uid_t is (always?) unsigned, it still
551 * accepts -1.
552 * * We don't know its size in advance--it may be
553 * bigger than an int, or it may be smaller than
554 * a long.
555 *
556 * So a bit of defensive programming is in order.
557 * Start with interpreting the value passed
558 * in as a signed long and see if it works.
559 */
560
561 result = PyLong_AsLongAndOverflow(index, &overflow);
562
563 if (!overflow) {
564 uid = (uid_t)result;
565
566 if (result == -1) {
567 if (PyErr_Occurred())
568 goto fail;
569 /* It's a legitimate -1, we're done. */
570 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200571 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700572
573 /* Any other negative number is disallowed. */
574 if (result < 0)
575 goto underflow;
576
577 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200578 if (sizeof(uid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700579 (long)uid != result)
580 goto underflow;
581 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200582 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700583
584 if (overflow < 0)
585 goto underflow;
586
587 /*
588 * Okay, the value overflowed a signed long. If it
589 * fits in an *unsigned* long, it may still be okay,
590 * as uid_t may be unsigned long on this platform.
591 */
592 uresult = PyLong_AsUnsignedLong(index);
593 if (PyErr_Occurred()) {
594 if (PyErr_ExceptionMatches(PyExc_OverflowError))
595 goto overflow;
596 goto fail;
597 }
598
599 uid = (uid_t)uresult;
600
601 /*
602 * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
603 * but this value would get interpreted as (uid_t)-1 by chown
604 * and its siblings. That's not what the user meant! So we
605 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100606 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700607 */
608 if (uid == (uid_t)-1)
609 goto overflow;
610
611 /* Ensure the value wasn't truncated. */
612 if (sizeof(uid_t) < sizeof(long) &&
613 (unsigned long)uid != uresult)
614 goto overflow;
615 /* fallthrough */
616
617success:
618 Py_DECREF(index);
619 *(uid_t *)p = uid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200620 return 1;
621
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700622underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200623 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700624 "uid is less than minimum");
625 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200626
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700627overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200628 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700629 "uid is greater than maximum");
630 /* fallthrough */
631
632fail:
633 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200634 return 0;
635}
636
637int
638_Py_Gid_Converter(PyObject *obj, void *p)
639{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700640 gid_t gid;
641 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200642 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200643 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700644 unsigned long uresult;
645
646 index = PyNumber_Index(obj);
647 if (index == NULL) {
648 PyErr_Format(PyExc_TypeError,
649 "gid should be integer, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800650 _PyType_Name(Py_TYPE(obj)));
Serhiy Storchakab4621892013-02-10 23:28:02 +0200651 return 0;
652 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700653
654 /*
655 * Handling gid_t is complicated for two reasons:
656 * * Although gid_t is (always?) unsigned, it still
657 * accepts -1.
658 * * We don't know its size in advance--it may be
659 * bigger than an int, or it may be smaller than
660 * a long.
661 *
662 * So a bit of defensive programming is in order.
663 * Start with interpreting the value passed
664 * in as a signed long and see if it works.
665 */
666
667 result = PyLong_AsLongAndOverflow(index, &overflow);
668
669 if (!overflow) {
670 gid = (gid_t)result;
671
672 if (result == -1) {
673 if (PyErr_Occurred())
674 goto fail;
675 /* It's a legitimate -1, we're done. */
676 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200677 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700678
679 /* Any other negative number is disallowed. */
680 if (result < 0) {
681 goto underflow;
682 }
683
684 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200685 if (sizeof(gid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700686 (long)gid != result)
687 goto underflow;
688 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200689 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700690
691 if (overflow < 0)
692 goto underflow;
693
694 /*
695 * Okay, the value overflowed a signed long. If it
696 * fits in an *unsigned* long, it may still be okay,
697 * as gid_t may be unsigned long on this platform.
698 */
699 uresult = PyLong_AsUnsignedLong(index);
700 if (PyErr_Occurred()) {
701 if (PyErr_ExceptionMatches(PyExc_OverflowError))
702 goto overflow;
703 goto fail;
704 }
705
706 gid = (gid_t)uresult;
707
708 /*
709 * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
710 * but this value would get interpreted as (gid_t)-1 by chown
711 * and its siblings. That's not what the user meant! So we
712 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100713 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700714 */
715 if (gid == (gid_t)-1)
716 goto overflow;
717
718 /* Ensure the value wasn't truncated. */
719 if (sizeof(gid_t) < sizeof(long) &&
720 (unsigned long)gid != uresult)
721 goto overflow;
722 /* fallthrough */
723
724success:
725 Py_DECREF(index);
726 *(gid_t *)p = gid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200727 return 1;
728
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700729underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200730 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700731 "gid is less than minimum");
732 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200733
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700734overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200735 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700736 "gid is greater than maximum");
737 /* fallthrough */
738
739fail:
740 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200741 return 0;
742}
743#endif /* MS_WINDOWS */
744
745
Benjamin Petersoned4aa832016-09-05 17:44:18 -0700746#define _PyLong_FromDev PyLong_FromLongLong
Gregory P. Smith702dada2015-01-28 16:07:52 -0800747
748
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200749#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
750static int
751_Py_Dev_Converter(PyObject *obj, void *p)
752{
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200753 *((dev_t *)p) = PyLong_AsUnsignedLongLong(obj);
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200754 if (PyErr_Occurred())
755 return 0;
756 return 1;
757}
Gregory P. Smith702dada2015-01-28 16:07:52 -0800758#endif /* HAVE_MKNOD && HAVE_MAKEDEV */
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200759
760
Larry Hastings9cf065c2012-06-22 16:30:09 -0700761#ifdef AT_FDCWD
Trent Nelson9a461052012-09-18 21:50:06 -0400762/*
763 * Why the (int) cast? Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
764 * without the int cast, the value gets interpreted as uint (4291925331),
765 * which doesn't play nicely with all the initializer lines in this file that
766 * look like this:
767 * int dir_fd = DEFAULT_DIR_FD;
768 */
769#define DEFAULT_DIR_FD (int)AT_FDCWD
Larry Hastings9cf065c2012-06-22 16:30:09 -0700770#else
771#define DEFAULT_DIR_FD (-100)
772#endif
773
774static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300775_fd_converter(PyObject *o, int *p)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200776{
777 int overflow;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700778 long long_value;
779
780 PyObject *index = PyNumber_Index(o);
781 if (index == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700782 return 0;
783 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700784
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300785 assert(PyLong_Check(index));
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700786 long_value = PyLong_AsLongAndOverflow(index, &overflow);
787 Py_DECREF(index);
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300788 assert(!PyErr_Occurred());
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200789 if (overflow > 0 || long_value > INT_MAX) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700790 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700791 "fd is greater than maximum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700792 return 0;
793 }
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200794 if (overflow < 0 || long_value < INT_MIN) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700795 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700796 "fd is less than minimum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700797 return 0;
798 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700799
Larry Hastings9cf065c2012-06-22 16:30:09 -0700800 *p = (int)long_value;
801 return 1;
802}
803
804static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200805dir_fd_converter(PyObject *o, void *p)
806{
807 if (o == Py_None) {
808 *(int *)p = DEFAULT_DIR_FD;
809 return 1;
810 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300811 else if (PyIndex_Check(o)) {
812 return _fd_converter(o, (int *)p);
813 }
814 else {
815 PyErr_Format(PyExc_TypeError,
816 "argument should be integer or None, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800817 _PyType_Name(Py_TYPE(o)));
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300818 return 0;
819 }
Larry Hastings9cf065c2012-06-22 16:30:09 -0700820}
821
Eddie Elizondob3966632019-11-05 07:16:14 -0800822typedef struct {
823 PyObject *billion;
Eddie Elizondob3966632019-11-05 07:16:14 -0800824 PyObject *DirEntryType;
825 PyObject *ScandirIteratorType;
826#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
827 PyObject *SchedParamType;
828#endif
829 PyObject *StatResultType;
830 PyObject *StatVFSResultType;
831 PyObject *TerminalSizeType;
832 PyObject *TimesResultType;
833 PyObject *UnameResultType;
834#if defined(HAVE_WAITID) && !defined(__APPLE__)
835 PyObject *WaitidResultType;
836#endif
837#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
838 PyObject *struct_rusage;
839#endif
840 PyObject *st_mode;
841} _posixstate;
842
843static struct PyModuleDef posixmodule;
844
Hai Shif707d942020-03-16 21:15:01 +0800845static inline _posixstate*
846get_posix_state(PyObject *module)
847{
848 void *state = PyModule_GetState(module);
849 assert(state != NULL);
850 return (_posixstate *)state;
851}
852
Eddie Elizondob3966632019-11-05 07:16:14 -0800853#define _posixstate_global ((_posixstate *)PyModule_GetState(PyState_FindModule(&posixmodule)))
Larry Hastings9cf065c2012-06-22 16:30:09 -0700854
Larry Hastings9cf065c2012-06-22 16:30:09 -0700855/*
856 * A PyArg_ParseTuple "converter" function
857 * that handles filesystem paths in the manner
858 * preferred by the os module.
859 *
860 * path_converter accepts (Unicode) strings and their
861 * subclasses, and bytes and their subclasses. What
862 * it does with the argument depends on the platform:
863 *
864 * * On Windows, if we get a (Unicode) string we
865 * extract the wchar_t * and return it; if we get
Steve Dowercc16be82016-09-08 10:35:16 -0700866 * bytes we decode to wchar_t * and return that.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700867 *
868 * * On all other platforms, strings are encoded
869 * to bytes using PyUnicode_FSConverter, then we
870 * extract the char * from the bytes object and
871 * return that.
872 *
873 * path_converter also optionally accepts signed
874 * integers (representing open file descriptors) instead
875 * of path strings.
876 *
877 * Input fields:
878 * path.nullable
879 * If nonzero, the path is permitted to be None.
880 * path.allow_fd
881 * If nonzero, the path is permitted to be a file handle
882 * (a signed int) instead of a string.
883 * path.function_name
884 * If non-NULL, path_converter will use that as the name
885 * of the function in error messages.
Larry Hastings31826802013-10-19 00:09:25 -0700886 * (If path.function_name is NULL it omits the function name.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700887 * path.argument_name
888 * If non-NULL, path_converter will use that as the name
889 * of the parameter in error messages.
890 * (If path.argument_name is NULL it uses "path".)
891 *
892 * Output fields:
893 * path.wide
894 * Points to the path if it was expressed as Unicode
895 * and was not encoded. (Only used on Windows.)
896 * path.narrow
897 * Points to the path if it was expressed as bytes,
Steve Dowercc16be82016-09-08 10:35:16 -0700898 * or it was Unicode and was encoded to bytes. (On Windows,
Martin Panterb1321fb2016-10-10 00:38:21 +0000899 * is a non-zero integer if the path was expressed as bytes.
Steve Dowercc16be82016-09-08 10:35:16 -0700900 * The type is deliberately incompatible to prevent misuse.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700901 * path.fd
902 * Contains a file descriptor if path.accept_fd was true
903 * and the caller provided a signed integer instead of any
904 * sort of string.
905 *
906 * WARNING: if your "path" parameter is optional, and is
907 * unspecified, path_converter will never get called.
908 * So if you set allow_fd, you *MUST* initialize path.fd = -1
909 * yourself!
910 * path.length
911 * The length of the path in characters, if specified as
912 * a string.
913 * path.object
Xiang Zhang04316c42017-01-08 23:26:57 +0800914 * The original object passed in (if get a PathLike object,
915 * the result of PyOS_FSPath() is treated as the original object).
916 * Own a reference to the object.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700917 * path.cleanup
918 * For internal use only. May point to a temporary object.
919 * (Pay no attention to the man behind the curtain.)
920 *
921 * At most one of path.wide or path.narrow will be non-NULL.
922 * If path was None and path.nullable was set,
923 * or if path was an integer and path.allow_fd was set,
924 * both path.wide and path.narrow will be NULL
925 * and path.length will be 0.
Georg Brandlf7875592012-06-24 13:58:31 +0200926 *
Larry Hastings9cf065c2012-06-22 16:30:09 -0700927 * path_converter takes care to not write to the path_t
928 * unless it's successful. However it must reset the
929 * "cleanup" field each time it's called.
930 *
931 * Use as follows:
932 * path_t path;
933 * memset(&path, 0, sizeof(path));
934 * PyArg_ParseTuple(args, "O&", path_converter, &path);
935 * // ... use values from path ...
936 * path_cleanup(&path);
937 *
938 * (Note that if PyArg_Parse fails you don't need to call
939 * path_cleanup(). However it is safe to do so.)
940 */
941typedef struct {
Victor Stinner292c8352012-10-30 02:17:38 +0100942 const char *function_name;
943 const char *argument_name;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700944 int nullable;
945 int allow_fd;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300946 const wchar_t *wide;
Steve Dowercc16be82016-09-08 10:35:16 -0700947#ifdef MS_WINDOWS
948 BOOL narrow;
949#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300950 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700951#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700952 int fd;
953 Py_ssize_t length;
954 PyObject *object;
955 PyObject *cleanup;
956} path_t;
957
Steve Dowercc16be82016-09-08 10:35:16 -0700958#ifdef MS_WINDOWS
959#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
960 {function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
961#else
Larry Hastings2f936352014-08-05 14:04:04 +1000962#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
963 {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
Steve Dowercc16be82016-09-08 10:35:16 -0700964#endif
Larry Hastings31826802013-10-19 00:09:25 -0700965
Larry Hastings9cf065c2012-06-22 16:30:09 -0700966static void
Xiang Zhang04316c42017-01-08 23:26:57 +0800967path_cleanup(path_t *path)
968{
969 Py_CLEAR(path->object);
970 Py_CLEAR(path->cleanup);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700971}
972
973static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300974path_converter(PyObject *o, void *p)
975{
Larry Hastings9cf065c2012-06-22 16:30:09 -0700976 path_t *path = (path_t *)p;
Xiang Zhang04316c42017-01-08 23:26:57 +0800977 PyObject *bytes = NULL;
978 Py_ssize_t length = 0;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700979 int is_index, is_buffer, is_bytes, is_unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300980 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700981#ifdef MS_WINDOWS
Xiang Zhang04316c42017-01-08 23:26:57 +0800982 PyObject *wo = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700983 const wchar_t *wide;
984#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700985
986#define FORMAT_EXCEPTION(exc, fmt) \
987 PyErr_Format(exc, "%s%s" fmt, \
988 path->function_name ? path->function_name : "", \
989 path->function_name ? ": " : "", \
990 path->argument_name ? path->argument_name : "path")
991
992 /* Py_CLEANUP_SUPPORTED support */
993 if (o == NULL) {
994 path_cleanup(path);
995 return 1;
996 }
997
Brett Cannon3f9183b2016-08-26 14:44:48 -0700998 /* Ensure it's always safe to call path_cleanup(). */
Xiang Zhang04316c42017-01-08 23:26:57 +0800999 path->object = path->cleanup = NULL;
1000 /* path->object owns a reference to the original object */
1001 Py_INCREF(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001002
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001003 if ((o == Py_None) && path->nullable) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001004 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001005#ifdef MS_WINDOWS
1006 path->narrow = FALSE;
1007#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001008 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001009#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07001010 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001011 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001012 }
1013
Brett Cannon3f9183b2016-08-26 14:44:48 -07001014 /* Only call this here so that we don't treat the return value of
1015 os.fspath() as an fd or buffer. */
1016 is_index = path->allow_fd && PyIndex_Check(o);
1017 is_buffer = PyObject_CheckBuffer(o);
1018 is_bytes = PyBytes_Check(o);
1019 is_unicode = PyUnicode_Check(o);
1020
1021 if (!is_index && !is_buffer && !is_unicode && !is_bytes) {
1022 /* Inline PyOS_FSPath() for better error messages. */
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001023 PyObject *func, *res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001024
1025 func = _PyObject_LookupSpecial(o, &PyId___fspath__);
1026 if (NULL == func) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001027 goto error_format;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001028 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001029 res = _PyObject_CallNoArg(func);
Brett Cannon3f9183b2016-08-26 14:44:48 -07001030 Py_DECREF(func);
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001031 if (NULL == res) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001032 goto error_exit;
1033 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001034 else if (PyUnicode_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001035 is_unicode = 1;
1036 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001037 else if (PyBytes_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001038 is_bytes = 1;
1039 }
1040 else {
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001041 PyErr_Format(PyExc_TypeError,
1042 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -08001043 "not %.200s", _PyType_Name(Py_TYPE(o)),
1044 _PyType_Name(Py_TYPE(res)));
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001045 Py_DECREF(res);
1046 goto error_exit;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001047 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001048
1049 /* still owns a reference to the original object */
1050 Py_DECREF(o);
1051 o = res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001052 }
1053
1054 if (is_unicode) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001055#ifdef MS_WINDOWS
Victor Stinner26c03bd2016-09-19 11:55:44 +02001056 wide = PyUnicode_AsUnicodeAndSize(o, &length);
Victor Stinner59799a82013-11-13 14:17:30 +01001057 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001058 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001059 }
Victor Stinner59799a82013-11-13 14:17:30 +01001060 if (length > 32767) {
1061 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001062 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001063 }
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001064 if (wcslen(wide) != length) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001065 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001066 goto error_exit;
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001067 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001068
1069 path->wide = wide;
Xiang Zhang04316c42017-01-08 23:26:57 +08001070 path->narrow = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001071 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001072 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001073#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001074 if (!PyUnicode_FSConverter(o, &bytes)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001075 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001076 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001077#endif
1078 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001079 else if (is_bytes) {
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001080 bytes = o;
1081 Py_INCREF(bytes);
1082 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001083 else if (is_buffer) {
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03001084 /* XXX Replace PyObject_CheckBuffer with PyBytes_Check in other code
Ville Skyttä49b27342017-08-03 09:00:59 +03001085 after removing support of non-bytes buffer objects. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001086 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1087 "%s%s%s should be %s, not %.200s",
1088 path->function_name ? path->function_name : "",
1089 path->function_name ? ": " : "",
1090 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001091 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1092 "integer or None" :
1093 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1094 path->nullable ? "string, bytes, os.PathLike or None" :
1095 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001096 _PyType_Name(Py_TYPE(o)))) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001097 goto error_exit;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001098 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001099 bytes = PyBytes_FromObject(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001100 if (!bytes) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001101 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001102 }
1103 }
Steve Dowercc16be82016-09-08 10:35:16 -07001104 else if (is_index) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001105 if (!_fd_converter(o, &path->fd)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001106 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001107 }
1108 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001109#ifdef MS_WINDOWS
1110 path->narrow = FALSE;
1111#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001112 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001113#endif
Xiang Zhang04316c42017-01-08 23:26:57 +08001114 goto success_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001115 }
1116 else {
Xiang Zhang04316c42017-01-08 23:26:57 +08001117 error_format:
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001118 PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
1119 path->function_name ? path->function_name : "",
1120 path->function_name ? ": " : "",
1121 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001122 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1123 "integer or None" :
1124 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1125 path->nullable ? "string, bytes, os.PathLike or None" :
1126 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001127 _PyType_Name(Py_TYPE(o)));
Xiang Zhang04316c42017-01-08 23:26:57 +08001128 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001129 }
1130
Larry Hastings9cf065c2012-06-22 16:30:09 -07001131 length = PyBytes_GET_SIZE(bytes);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001132 narrow = PyBytes_AS_STRING(bytes);
Victor Stinner706768c2014-08-16 01:03:39 +02001133 if ((size_t)length != strlen(narrow)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03001134 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001135 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001136 }
1137
Steve Dowercc16be82016-09-08 10:35:16 -07001138#ifdef MS_WINDOWS
1139 wo = PyUnicode_DecodeFSDefaultAndSize(
1140 narrow,
1141 length
1142 );
1143 if (!wo) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001144 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001145 }
1146
Xiang Zhang04316c42017-01-08 23:26:57 +08001147 wide = PyUnicode_AsUnicodeAndSize(wo, &length);
Steve Dowercc16be82016-09-08 10:35:16 -07001148 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001149 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001150 }
1151 if (length > 32767) {
1152 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001153 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001154 }
1155 if (wcslen(wide) != length) {
1156 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001157 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001158 }
1159 path->wide = wide;
1160 path->narrow = TRUE;
Xiang Zhang04316c42017-01-08 23:26:57 +08001161 path->cleanup = wo;
1162 Py_DECREF(bytes);
Steve Dowercc16be82016-09-08 10:35:16 -07001163#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001164 path->wide = NULL;
1165 path->narrow = narrow;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001166 if (bytes == o) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001167 /* Still a reference owned by path->object, don't have to
1168 worry about path->narrow is used after free. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001169 Py_DECREF(bytes);
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001170 }
1171 else {
1172 path->cleanup = bytes;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001173 }
Xiang Zhang04316c42017-01-08 23:26:57 +08001174#endif
1175 path->fd = -1;
1176
1177 success_exit:
1178 path->length = length;
1179 path->object = o;
1180 return Py_CLEANUP_SUPPORTED;
1181
1182 error_exit:
1183 Py_XDECREF(o);
1184 Py_XDECREF(bytes);
1185#ifdef MS_WINDOWS
1186 Py_XDECREF(wo);
1187#endif
1188 return 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001189}
1190
1191static void
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001192argument_unavailable_error(const char *function_name, const char *argument_name)
1193{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001194 PyErr_Format(PyExc_NotImplementedError,
1195 "%s%s%s unavailable on this platform",
1196 (function_name != NULL) ? function_name : "",
1197 (function_name != NULL) ? ": ": "",
1198 argument_name);
1199}
1200
1201static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001202dir_fd_unavailable(PyObject *o, void *p)
1203{
1204 int dir_fd;
1205 if (!dir_fd_converter(o, &dir_fd))
Larry Hastings9cf065c2012-06-22 16:30:09 -07001206 return 0;
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001207 if (dir_fd != DEFAULT_DIR_FD) {
1208 argument_unavailable_error(NULL, "dir_fd");
1209 return 0;
1210 }
1211 *(int *)p = dir_fd;
1212 return 1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001213}
1214
1215static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001216fd_specified(const char *function_name, int fd)
1217{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001218 if (fd == -1)
1219 return 0;
1220
1221 argument_unavailable_error(function_name, "fd");
1222 return 1;
1223}
1224
1225static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001226follow_symlinks_specified(const char *function_name, int follow_symlinks)
1227{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001228 if (follow_symlinks)
1229 return 0;
1230
1231 argument_unavailable_error(function_name, "follow_symlinks");
1232 return 1;
1233}
1234
1235static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001236path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
1237{
Steve Dowercc16be82016-09-08 10:35:16 -07001238 if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
1239#ifndef MS_WINDOWS
1240 && !path->narrow
1241#endif
1242 ) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001243 PyErr_Format(PyExc_ValueError,
1244 "%s: can't specify dir_fd without matching path",
1245 function_name);
1246 return 1;
1247 }
1248 return 0;
1249}
1250
1251static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001252dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
1253{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001254 if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
1255 PyErr_Format(PyExc_ValueError,
1256 "%s: can't specify both dir_fd and fd",
1257 function_name);
1258 return 1;
1259 }
1260 return 0;
1261}
1262
1263static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001264fd_and_follow_symlinks_invalid(const char *function_name, int fd,
1265 int follow_symlinks)
1266{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001267 if ((fd > 0) && (!follow_symlinks)) {
1268 PyErr_Format(PyExc_ValueError,
1269 "%s: cannot use fd and follow_symlinks together",
1270 function_name);
1271 return 1;
1272 }
1273 return 0;
1274}
1275
1276static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001277dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
1278 int follow_symlinks)
1279{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001280 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
1281 PyErr_Format(PyExc_ValueError,
1282 "%s: cannot use dir_fd and follow_symlinks together",
1283 function_name);
1284 return 1;
1285 }
1286 return 0;
1287}
1288
Larry Hastings2f936352014-08-05 14:04:04 +10001289#ifdef MS_WINDOWS
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001290 typedef long long Py_off_t;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001291#else
Larry Hastings2f936352014-08-05 14:04:04 +10001292 typedef off_t Py_off_t;
1293#endif
1294
1295static int
1296Py_off_t_converter(PyObject *arg, void *addr)
1297{
1298#ifdef HAVE_LARGEFILE_SUPPORT
1299 *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
1300#else
1301 *((Py_off_t *)addr) = PyLong_AsLong(arg);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001302#endif
1303 if (PyErr_Occurred())
1304 return 0;
1305 return 1;
1306}
Larry Hastings2f936352014-08-05 14:04:04 +10001307
1308static PyObject *
1309PyLong_FromPy_off_t(Py_off_t offset)
1310{
1311#ifdef HAVE_LARGEFILE_SUPPORT
1312 return PyLong_FromLongLong(offset);
1313#else
1314 return PyLong_FromLong(offset);
Ross Lagerwallb1e5d592011-09-19 08:30:43 +02001315#endif
Larry Hastings2f936352014-08-05 14:04:04 +10001316}
1317
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001318#ifdef HAVE_SIGSET_T
1319/* Convert an iterable of integers to a sigset.
1320 Return 1 on success, return 0 and raise an exception on error. */
1321int
1322_Py_Sigset_Converter(PyObject *obj, void *addr)
1323{
1324 sigset_t *mask = (sigset_t *)addr;
1325 PyObject *iterator, *item;
1326 long signum;
1327 int overflow;
1328
Rémi Lapeyref0900192019-05-04 01:30:53 +02001329 // The extra parens suppress the unreachable-code warning with clang on MacOS
1330 if (sigemptyset(mask) < (0)) {
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001331 /* Probably only if mask == NULL. */
1332 PyErr_SetFromErrno(PyExc_OSError);
1333 return 0;
1334 }
1335
1336 iterator = PyObject_GetIter(obj);
1337 if (iterator == NULL) {
1338 return 0;
1339 }
1340
1341 while ((item = PyIter_Next(iterator)) != NULL) {
1342 signum = PyLong_AsLongAndOverflow(item, &overflow);
1343 Py_DECREF(item);
1344 if (signum <= 0 || signum >= NSIG) {
1345 if (overflow || signum != -1 || !PyErr_Occurred()) {
1346 PyErr_Format(PyExc_ValueError,
1347 "signal number %ld out of range", signum);
1348 }
1349 goto error;
1350 }
1351 if (sigaddset(mask, (int)signum)) {
1352 if (errno != EINVAL) {
1353 /* Probably impossible */
1354 PyErr_SetFromErrno(PyExc_OSError);
1355 goto error;
1356 }
1357 /* For backwards compatibility, allow idioms such as
1358 * `range(1, NSIG)` but warn about invalid signal numbers
1359 */
1360 const char msg[] =
1361 "invalid signal number %ld, please use valid_signals()";
1362 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
1363 goto error;
1364 }
1365 }
1366 }
1367 if (!PyErr_Occurred()) {
1368 Py_DECREF(iterator);
1369 return 1;
1370 }
1371
1372error:
1373 Py_DECREF(iterator);
1374 return 0;
1375}
1376#endif /* HAVE_SIGSET_T */
1377
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001378#ifdef MS_WINDOWS
Brian Curtinf5e76d02010-11-24 13:14:05 +00001379
1380static int
Brian Curtind25aef52011-06-13 15:16:04 -05001381win32_get_reparse_tag(HANDLE reparse_point_handle, ULONG *reparse_tag)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001382{
Martin Panter70214ad2016-08-04 02:38:59 +00001383 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1384 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001385 DWORD n_bytes_returned;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001386
1387 if (0 == DeviceIoControl(
1388 reparse_point_handle,
1389 FSCTL_GET_REPARSE_POINT,
1390 NULL, 0, /* in buffer */
1391 target_buffer, sizeof(target_buffer),
1392 &n_bytes_returned,
1393 NULL)) /* we're not using OVERLAPPED_IO */
Brian Curtind25aef52011-06-13 15:16:04 -05001394 return FALSE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001395
1396 if (reparse_tag)
1397 *reparse_tag = rdb->ReparseTag;
1398
Brian Curtind25aef52011-06-13 15:16:04 -05001399 return TRUE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001400}
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001401
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001402#endif /* MS_WINDOWS */
Brian Curtinf5e76d02010-11-24 13:14:05 +00001403
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001404/* Return a dictionary corresponding to the POSIX environment table */
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001405#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Jack Jansenea0c3822002-08-01 21:57:49 +00001406/* On Darwin/MacOSX a shared library or framework has no access to
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001407** environ directly, we must obtain it with _NSGetEnviron(). See also
1408** man environ(7).
Jack Jansenea0c3822002-08-01 21:57:49 +00001409*/
1410#include <crt_externs.h>
pxinwrf2d7ac72019-05-21 18:46:37 +08001411#elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001412extern char **environ;
Guido van Rossuma4916fa1996-05-23 22:58:55 +00001413#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001414
Barry Warsaw53699e91996-12-10 23:23:01 +00001415static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001416convertenviron(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001417{
Victor Stinner8c62be82010-05-06 00:08:46 +00001418 PyObject *d;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001419#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00001420 wchar_t **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001421#else
Victor Stinner8c62be82010-05-06 00:08:46 +00001422 char **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001423#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +00001424
Victor Stinner8c62be82010-05-06 00:08:46 +00001425 d = PyDict_New();
1426 if (d == NULL)
1427 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001428#ifdef MS_WINDOWS
1429 /* _wenviron must be initialized in this way if the program is started
1430 through main() instead of wmain(). */
1431 _wgetenv(L"");
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001432 e = _wenviron;
Benoit Hudson723f71a2019-12-06 14:15:03 -05001433#elif defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
1434 /* environ is not accessible as an extern in a shared object on OSX; use
1435 _NSGetEnviron to resolve it. The value changes if you add environment
1436 variables between calls to Py_Initialize, so don't cache the value. */
1437 e = *_NSGetEnviron();
Victor Stinner8c62be82010-05-06 00:08:46 +00001438#else
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001439 e = environ;
1440#endif
1441 if (e == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +00001442 return d;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001443 for (; *e != NULL; e++) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001444 PyObject *k;
1445 PyObject *v;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001446#ifdef MS_WINDOWS
1447 const wchar_t *p = wcschr(*e, L'=');
1448#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03001449 const char *p = strchr(*e, '=');
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001450#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001451 if (p == NULL)
1452 continue;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001453#ifdef MS_WINDOWS
1454 k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
1455#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001456 k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001457#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001458 if (k == NULL) {
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001459 Py_DECREF(d);
1460 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001461 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001462#ifdef MS_WINDOWS
1463 v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
1464#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001465 v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001466#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001467 if (v == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001468 Py_DECREF(k);
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001469 Py_DECREF(d);
1470 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001471 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001472 if (PyDict_GetItemWithError(d, k) == NULL) {
1473 if (PyErr_Occurred() || PyDict_SetItem(d, k, v) != 0) {
1474 Py_DECREF(v);
1475 Py_DECREF(k);
1476 Py_DECREF(d);
1477 return NULL;
1478 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001479 }
1480 Py_DECREF(k);
1481 Py_DECREF(v);
Guido van Rossumd48f2521997-12-05 22:19:34 +00001482 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001483 return d;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001484}
1485
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001486/* Set a POSIX-specific error from errno, and return NULL */
1487
Barry Warsawd58d7641998-07-23 16:14:40 +00001488static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001489posix_error(void)
Guido van Rossumad0ee831995-03-01 10:34:45 +00001490{
Victor Stinner8c62be82010-05-06 00:08:46 +00001491 return PyErr_SetFromErrno(PyExc_OSError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001492}
Mark Hammondef8b6542001-05-13 08:04:26 +00001493
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001494#ifdef MS_WINDOWS
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001495static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001496win32_error(const char* function, const char* filename)
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001497{
Victor Stinner8c62be82010-05-06 00:08:46 +00001498 /* XXX We should pass the function name along in the future.
1499 (winreg.c also wants to pass the function name.)
1500 This would however require an additional param to the
1501 Windows error object, which is non-trivial.
1502 */
1503 errno = GetLastError();
1504 if (filename)
1505 return PyErr_SetFromWindowsErrWithFilename(errno, filename);
1506 else
1507 return PyErr_SetFromWindowsErr(errno);
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001508}
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001509
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001510static PyObject *
Steve Dower2438cdf2019-03-29 16:37:16 -07001511win32_error_object_err(const char* function, PyObject* filename, DWORD err)
Victor Stinnereb5657a2011-09-30 01:44:27 +02001512{
1513 /* XXX - see win32_error for comments on 'function' */
Victor Stinnereb5657a2011-09-30 01:44:27 +02001514 if (filename)
1515 return PyErr_SetExcFromWindowsErrWithFilenameObject(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001516 PyExc_OSError,
Steve Dower2438cdf2019-03-29 16:37:16 -07001517 err,
Victor Stinnereb5657a2011-09-30 01:44:27 +02001518 filename);
1519 else
Steve Dower2438cdf2019-03-29 16:37:16 -07001520 return PyErr_SetFromWindowsErr(err);
1521}
1522
1523static PyObject *
1524win32_error_object(const char* function, PyObject* filename)
1525{
1526 errno = GetLastError();
1527 return win32_error_object_err(function, filename, errno);
Victor Stinnereb5657a2011-09-30 01:44:27 +02001528}
1529
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001530#endif /* MS_WINDOWS */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001531
Larry Hastings9cf065c2012-06-22 16:30:09 -07001532static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001533posix_path_object_error(PyObject *path)
1534{
1535 return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
1536}
1537
1538static PyObject *
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001539path_object_error(PyObject *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001540{
1541#ifdef MS_WINDOWS
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001542 return PyErr_SetExcFromWindowsErrWithFilenameObject(
1543 PyExc_OSError, 0, path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001544#else
Alexey Izbyshev83460312018-10-20 03:28:22 +03001545 return posix_path_object_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001546#endif
1547}
1548
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001549static PyObject *
1550path_object_error2(PyObject *path, PyObject *path2)
1551{
1552#ifdef MS_WINDOWS
1553 return PyErr_SetExcFromWindowsErrWithFilenameObjects(
1554 PyExc_OSError, 0, path, path2);
1555#else
1556 return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
1557#endif
1558}
1559
1560static PyObject *
1561path_error(path_t *path)
1562{
1563 return path_object_error(path->object);
1564}
Larry Hastings31826802013-10-19 00:09:25 -07001565
Larry Hastingsb0827312014-02-09 22:05:19 -08001566static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001567posix_path_error(path_t *path)
1568{
1569 return posix_path_object_error(path->object);
1570}
1571
1572static PyObject *
Larry Hastingsb0827312014-02-09 22:05:19 -08001573path_error2(path_t *path, path_t *path2)
1574{
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001575 return path_object_error2(path->object, path2->object);
Larry Hastingsb0827312014-02-09 22:05:19 -08001576}
1577
1578
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001579/* POSIX generic methods */
1580
Larry Hastings2f936352014-08-05 14:04:04 +10001581static int
1582fildes_converter(PyObject *o, void *p)
Fred Drake4d1e64b2002-04-15 19:40:07 +00001583{
Victor Stinner8c62be82010-05-06 00:08:46 +00001584 int fd;
Larry Hastings2f936352014-08-05 14:04:04 +10001585 int *pointer = (int *)p;
1586 fd = PyObject_AsFileDescriptor(o);
Victor Stinner8c62be82010-05-06 00:08:46 +00001587 if (fd < 0)
Larry Hastings2f936352014-08-05 14:04:04 +10001588 return 0;
Larry Hastings2f936352014-08-05 14:04:04 +10001589 *pointer = fd;
1590 return 1;
1591}
1592
1593static PyObject *
1594posix_fildes_fd(int fd, int (*func)(int))
1595{
1596 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001597 int async_err = 0;
1598
1599 do {
1600 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001601 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001602 res = (*func)(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001603 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001604 Py_END_ALLOW_THREADS
1605 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1606 if (res != 0)
1607 return (!async_err) ? posix_error() : NULL;
1608 Py_RETURN_NONE;
Fred Drake4d1e64b2002-04-15 19:40:07 +00001609}
Guido van Rossum21142a01999-01-08 21:05:37 +00001610
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001611
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001612#ifdef MS_WINDOWS
Thomas Wouters477c8d52006-05-27 19:21:47 +00001613/* This is a reimplementation of the C library's chdir function,
1614 but one that produces Win32 errors instead of DOS error codes.
1615 chdir is essentially a wrapper around SetCurrentDirectory; however,
1616 it also needs to set "magic" environment variables indicating
1617 the per-drive current directory, which are of the form =<drive>: */
Benjamin Peterson206e3072008-10-19 14:07:49 +00001618static BOOL __stdcall
Thomas Wouters477c8d52006-05-27 19:21:47 +00001619win32_wchdir(LPCWSTR path)
1620{
Victor Stinnered537822015-12-13 21:40:26 +01001621 wchar_t path_buf[MAX_PATH], *new_path = path_buf;
Victor Stinner8c62be82010-05-06 00:08:46 +00001622 int result;
1623 wchar_t env[4] = L"=x:";
Thomas Wouters477c8d52006-05-27 19:21:47 +00001624
Victor Stinner8c62be82010-05-06 00:08:46 +00001625 if(!SetCurrentDirectoryW(path))
1626 return FALSE;
Victor Stinnered537822015-12-13 21:40:26 +01001627 result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001628 if (!result)
1629 return FALSE;
Victor Stinnere847d712015-12-14 00:21:50 +01001630 if (result > Py_ARRAY_LENGTH(path_buf)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001631 new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00001632 if (!new_path) {
1633 SetLastError(ERROR_OUTOFMEMORY);
1634 return FALSE;
1635 }
1636 result = GetCurrentDirectoryW(result, new_path);
1637 if (!result) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001638 PyMem_RawFree(new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001639 return FALSE;
1640 }
1641 }
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001642 int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
1643 wcsncmp(new_path, L"//", 2) == 0);
1644 if (!is_unc_like_path) {
1645 env[1] = new_path[0];
1646 result = SetEnvironmentVariableW(env, new_path);
1647 }
Victor Stinnered537822015-12-13 21:40:26 +01001648 if (new_path != path_buf)
Victor Stinnerb6404912013-07-07 16:21:41 +02001649 PyMem_RawFree(new_path);
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001650 return result ? TRUE : FALSE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001651}
1652#endif
1653
Martin v. Löwis14694662006-02-03 12:54:16 +00001654#ifdef MS_WINDOWS
1655/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
1656 - time stamps are restricted to second resolution
1657 - file modification times suffer from forth-and-back conversions between
1658 UTC and local time
1659 Therefore, we implement our own stat, based on the Win32 API directly.
1660*/
Victor Stinner8c62be82010-05-06 00:08:46 +00001661#define HAVE_STAT_NSEC 1
Zachary Ware63f277b2014-06-19 09:46:37 -05001662#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001663#define HAVE_STRUCT_STAT_ST_REPARSE_TAG 1
Martin v. Löwis14694662006-02-03 12:54:16 +00001664
Victor Stinner6036e442015-03-08 01:58:04 +01001665static void
Steve Dowercc16be82016-09-08 10:35:16 -07001666find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
1667 BY_HANDLE_FILE_INFORMATION *info,
1668 ULONG *reparse_tag)
Victor Stinner6036e442015-03-08 01:58:04 +01001669{
1670 memset(info, 0, sizeof(*info));
1671 info->dwFileAttributes = pFileData->dwFileAttributes;
1672 info->ftCreationTime = pFileData->ftCreationTime;
1673 info->ftLastAccessTime = pFileData->ftLastAccessTime;
1674 info->ftLastWriteTime = pFileData->ftLastWriteTime;
1675 info->nFileSizeHigh = pFileData->nFileSizeHigh;
1676 info->nFileSizeLow = pFileData->nFileSizeLow;
1677/* info->nNumberOfLinks = 1; */
1678 if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
1679 *reparse_tag = pFileData->dwReserved0;
1680 else
1681 *reparse_tag = 0;
1682}
1683
Guido van Rossumd8faa362007-04-27 19:54:29 +00001684static BOOL
Steve Dowercc16be82016-09-08 10:35:16 -07001685attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001686{
Victor Stinner8c62be82010-05-06 00:08:46 +00001687 HANDLE hFindFile;
1688 WIN32_FIND_DATAW FileData;
1689 hFindFile = FindFirstFileW(pszFile, &FileData);
1690 if (hFindFile == INVALID_HANDLE_VALUE)
1691 return FALSE;
1692 FindClose(hFindFile);
Steve Dowercc16be82016-09-08 10:35:16 -07001693 find_data_to_file_info(&FileData, info, reparse_tag);
Victor Stinner8c62be82010-05-06 00:08:46 +00001694 return TRUE;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001695}
1696
Brian Curtind25aef52011-06-13 15:16:04 -05001697static int
Steve Dowercc16be82016-09-08 10:35:16 -07001698win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
Brian Curtind25aef52011-06-13 15:16:04 -05001699 BOOL traverse)
1700{
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001701 HANDLE hFile;
1702 BY_HANDLE_FILE_INFORMATION fileInfo;
1703 FILE_ATTRIBUTE_TAG_INFO tagInfo = { 0 };
1704 DWORD fileType, error;
1705 BOOL isUnhandledTag = FALSE;
1706 int retval = 0;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001707
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001708 DWORD access = FILE_READ_ATTRIBUTES;
1709 DWORD flags = FILE_FLAG_BACKUP_SEMANTICS; /* Allow opening directories. */
1710 if (!traverse) {
1711 flags |= FILE_FLAG_OPEN_REPARSE_POINT;
1712 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001713
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001714 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING, flags, NULL);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001715 if (hFile == INVALID_HANDLE_VALUE) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001716 /* Either the path doesn't exist, or the caller lacks access. */
1717 error = GetLastError();
1718 switch (error) {
1719 case ERROR_ACCESS_DENIED: /* Cannot sync or read attributes. */
1720 case ERROR_SHARING_VIOLATION: /* It's a paging file. */
1721 /* Try reading the parent directory. */
1722 if (!attributes_from_dir(path, &fileInfo, &tagInfo.ReparseTag)) {
1723 /* Cannot read the parent directory. */
1724 SetLastError(error);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001725 return -1;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001726 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001727 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1728 if (traverse ||
1729 !IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1730 /* The stat call has to traverse but cannot, so fail. */
1731 SetLastError(error);
Brian Curtind25aef52011-06-13 15:16:04 -05001732 return -1;
Mark Becwarb82bfac2019-02-02 16:08:23 -05001733 }
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001734 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001735 break;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001736
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001737 case ERROR_INVALID_PARAMETER:
1738 /* \\.\con requires read or write access. */
1739 hFile = CreateFileW(path, access | GENERIC_READ,
1740 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1741 OPEN_EXISTING, flags, NULL);
1742 if (hFile == INVALID_HANDLE_VALUE) {
1743 SetLastError(error);
1744 return -1;
1745 }
1746 break;
1747
1748 case ERROR_CANT_ACCESS_FILE:
1749 /* bpo37834: open unhandled reparse points if traverse fails. */
1750 if (traverse) {
1751 traverse = FALSE;
1752 isUnhandledTag = TRUE;
1753 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING,
1754 flags | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
1755 }
1756 if (hFile == INVALID_HANDLE_VALUE) {
1757 SetLastError(error);
1758 return -1;
1759 }
1760 break;
1761
1762 default:
1763 return -1;
1764 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001765 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001766
1767 if (hFile != INVALID_HANDLE_VALUE) {
1768 /* Handle types other than files on disk. */
1769 fileType = GetFileType(hFile);
1770 if (fileType != FILE_TYPE_DISK) {
1771 if (fileType == FILE_TYPE_UNKNOWN && GetLastError() != 0) {
1772 retval = -1;
1773 goto cleanup;
1774 }
1775 DWORD fileAttributes = GetFileAttributesW(path);
1776 memset(result, 0, sizeof(*result));
1777 if (fileAttributes != INVALID_FILE_ATTRIBUTES &&
1778 fileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1779 /* \\.\pipe\ or \\.\mailslot\ */
1780 result->st_mode = _S_IFDIR;
1781 } else if (fileType == FILE_TYPE_CHAR) {
1782 /* \\.\nul */
1783 result->st_mode = _S_IFCHR;
1784 } else if (fileType == FILE_TYPE_PIPE) {
1785 /* \\.\pipe\spam */
1786 result->st_mode = _S_IFIFO;
1787 }
1788 /* FILE_TYPE_UNKNOWN, e.g. \\.\mailslot\waitfor.exe\spam */
1789 goto cleanup;
1790 }
1791
1792 /* Query the reparse tag, and traverse a non-link. */
1793 if (!traverse) {
1794 if (!GetFileInformationByHandleEx(hFile, FileAttributeTagInfo,
1795 &tagInfo, sizeof(tagInfo))) {
1796 /* Allow devices that do not support FileAttributeTagInfo. */
1797 switch (GetLastError()) {
1798 case ERROR_INVALID_PARAMETER:
1799 case ERROR_INVALID_FUNCTION:
1800 case ERROR_NOT_SUPPORTED:
1801 tagInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1802 tagInfo.ReparseTag = 0;
1803 break;
1804 default:
1805 retval = -1;
1806 goto cleanup;
1807 }
1808 } else if (tagInfo.FileAttributes &
1809 FILE_ATTRIBUTE_REPARSE_POINT) {
1810 if (IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1811 if (isUnhandledTag) {
1812 /* Traversing previously failed for either this link
1813 or its target. */
1814 SetLastError(ERROR_CANT_ACCESS_FILE);
1815 retval = -1;
1816 goto cleanup;
1817 }
1818 /* Traverse a non-link, but not if traversing already failed
1819 for an unhandled tag. */
1820 } else if (!isUnhandledTag) {
1821 CloseHandle(hFile);
1822 return win32_xstat_impl(path, result, TRUE);
1823 }
1824 }
1825 }
1826
1827 if (!GetFileInformationByHandle(hFile, &fileInfo)) {
1828 switch (GetLastError()) {
1829 case ERROR_INVALID_PARAMETER:
1830 case ERROR_INVALID_FUNCTION:
1831 case ERROR_NOT_SUPPORTED:
Steve Dower772ec0f2019-09-04 14:42:54 -07001832 /* Volumes and physical disks are block devices, e.g.
1833 \\.\C: and \\.\PhysicalDrive0. */
1834 memset(result, 0, sizeof(*result));
1835 result->st_mode = 0x6000; /* S_IFBLK */
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001836 goto cleanup;
1837 }
Steve Dower772ec0f2019-09-04 14:42:54 -07001838 retval = -1;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001839 goto cleanup;
1840 }
1841 }
1842
1843 _Py_attribute_data_to_stat(&fileInfo, tagInfo.ReparseTag, result);
1844
1845 if (!(fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
1846 /* Fix the file execute permissions. This hack sets S_IEXEC if
1847 the filename has an extension that is commonly used by files
1848 that CreateProcessW can execute. A real implementation calls
1849 GetSecurityInfo, OpenThreadToken/OpenProcessToken, and
1850 AccessCheck to check for generic read, write, and execute
1851 access. */
1852 const wchar_t *fileExtension = wcsrchr(path, '.');
1853 if (fileExtension) {
1854 if (_wcsicmp(fileExtension, L".exe") == 0 ||
1855 _wcsicmp(fileExtension, L".bat") == 0 ||
1856 _wcsicmp(fileExtension, L".cmd") == 0 ||
1857 _wcsicmp(fileExtension, L".com") == 0) {
1858 result->st_mode |= 0111;
1859 }
1860 }
1861 }
1862
1863cleanup:
1864 if (hFile != INVALID_HANDLE_VALUE) {
Steve Dower772ec0f2019-09-04 14:42:54 -07001865 /* Preserve last error if we are failing */
1866 error = retval ? GetLastError() : 0;
1867 if (!CloseHandle(hFile)) {
1868 retval = -1;
1869 } else if (retval) {
1870 /* Restore last error */
1871 SetLastError(error);
1872 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001873 }
1874
1875 return retval;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001876}
1877
1878static int
Steve Dowercc16be82016-09-08 10:35:16 -07001879win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001880{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001881 /* Protocol violation: we explicitly clear errno, instead of
1882 setting it to a POSIX error. Callers should use GetLastError. */
Brian Curtind25aef52011-06-13 15:16:04 -05001883 int code = win32_xstat_impl(path, result, traverse);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001884 errno = 0;
1885 return code;
1886}
Brian Curtind25aef52011-06-13 15:16:04 -05001887/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
Brian Curtind40e6f72010-07-08 21:39:08 +00001888
1889 In Posix, stat automatically traverses symlinks and returns the stat
1890 structure for the target. In Windows, the equivalent GetFileAttributes by
1891 default does not traverse symlinks and instead returns attributes for
1892 the symlink.
1893
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001894 Instead, we will open the file (which *does* traverse symlinks by default)
1895 and GetFileInformationByHandle(). */
Brian Curtind40e6f72010-07-08 21:39:08 +00001896
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001897static int
Steve Dowercc16be82016-09-08 10:35:16 -07001898win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
Martin v. Löwis14694662006-02-03 12:54:16 +00001899{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001900 return win32_xstat(path, result, FALSE);
Martin v. Löwis14694662006-02-03 12:54:16 +00001901}
1902
Victor Stinner8c62be82010-05-06 00:08:46 +00001903static int
Steve Dowercc16be82016-09-08 10:35:16 -07001904win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
Brian Curtind40e6f72010-07-08 21:39:08 +00001905{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001906 return win32_xstat(path, result, TRUE);
Brian Curtind40e6f72010-07-08 21:39:08 +00001907}
1908
Martin v. Löwis14694662006-02-03 12:54:16 +00001909#endif /* MS_WINDOWS */
1910
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001911PyDoc_STRVAR(stat_result__doc__,
Larry Hastings9cf065c2012-06-22 16:30:09 -07001912"stat_result: Result from stat, fstat, or lstat.\n\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001913This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001914 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001915or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1916\n\
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001917Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1918or st_flags, they are available as attributes only.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001919\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001920See os.stat for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001921
1922static PyStructSequence_Field stat_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001923 {"st_mode", "protection bits"},
1924 {"st_ino", "inode"},
1925 {"st_dev", "device"},
1926 {"st_nlink", "number of hard links"},
1927 {"st_uid", "user ID of owner"},
1928 {"st_gid", "group ID of owner"},
1929 {"st_size", "total size, in bytes"},
1930 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1931 {NULL, "integer time of last access"},
1932 {NULL, "integer time of last modification"},
1933 {NULL, "integer time of last change"},
1934 {"st_atime", "time of last access"},
1935 {"st_mtime", "time of last modification"},
1936 {"st_ctime", "time of last change"},
Larry Hastings6fe20b32012-04-19 15:07:49 -07001937 {"st_atime_ns", "time of last access in nanoseconds"},
1938 {"st_mtime_ns", "time of last modification in nanoseconds"},
1939 {"st_ctime_ns", "time of last change in nanoseconds"},
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001940#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00001941 {"st_blksize", "blocksize for filesystem I/O"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001942#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001943#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00001944 {"st_blocks", "number of blocks allocated"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001945#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001946#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00001947 {"st_rdev", "device type (if inode device)"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001948#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001949#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00001950 {"st_flags", "user defined flags for file"},
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001951#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001952#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00001953 {"st_gen", "generation number"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001954#endif
1955#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00001956 {"st_birthtime", "time of creation"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001957#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05001958#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1959 {"st_file_attributes", "Windows file attribute bits"},
1960#endif
jcea6c51d512018-01-28 14:00:08 +01001961#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1962 {"st_fstype", "Type of filesystem"},
1963#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001964#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
1965 {"st_reparse_tag", "Windows reparse tag"},
1966#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001967 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001968};
1969
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001970#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Larry Hastings6fe20b32012-04-19 15:07:49 -07001971#define ST_BLKSIZE_IDX 16
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001972#else
Larry Hastings6fe20b32012-04-19 15:07:49 -07001973#define ST_BLKSIZE_IDX 15
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001974#endif
1975
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001976#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001977#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
1978#else
1979#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
1980#endif
1981
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001982#ifdef HAVE_STRUCT_STAT_ST_RDEV
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001983#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
1984#else
1985#define ST_RDEV_IDX ST_BLOCKS_IDX
1986#endif
1987
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001988#ifdef HAVE_STRUCT_STAT_ST_FLAGS
1989#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
1990#else
1991#define ST_FLAGS_IDX ST_RDEV_IDX
1992#endif
1993
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001994#ifdef HAVE_STRUCT_STAT_ST_GEN
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001995#define ST_GEN_IDX (ST_FLAGS_IDX+1)
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001996#else
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001997#define ST_GEN_IDX ST_FLAGS_IDX
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001998#endif
1999
2000#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
2001#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
2002#else
2003#define ST_BIRTHTIME_IDX ST_GEN_IDX
2004#endif
2005
Zachary Ware63f277b2014-06-19 09:46:37 -05002006#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2007#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_IDX+1)
2008#else
2009#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_IDX
2010#endif
2011
jcea6c51d512018-01-28 14:00:08 +01002012#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2013#define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
2014#else
2015#define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
2016#endif
2017
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002018#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2019#define ST_REPARSE_TAG_IDX (ST_FSTYPE_IDX+1)
2020#else
2021#define ST_REPARSE_TAG_IDX ST_FSTYPE_IDX
2022#endif
2023
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002024static PyStructSequence_Desc stat_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002025 "stat_result", /* name */
2026 stat_result__doc__, /* doc */
2027 stat_result_fields,
2028 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002029};
2030
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002031PyDoc_STRVAR(statvfs_result__doc__,
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002032"statvfs_result: Result from statvfs or fstatvfs.\n\n\
2033This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00002034 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
Guido van Rossuma4dc73e2001-10-18 20:53:15 +00002035or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002036\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002037See os.statvfs for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002038
2039static PyStructSequence_Field statvfs_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002040 {"f_bsize", },
2041 {"f_frsize", },
2042 {"f_blocks", },
2043 {"f_bfree", },
2044 {"f_bavail", },
2045 {"f_files", },
2046 {"f_ffree", },
2047 {"f_favail", },
2048 {"f_flag", },
2049 {"f_namemax",},
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +01002050 {"f_fsid", },
Victor Stinner8c62be82010-05-06 00:08:46 +00002051 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002052};
2053
2054static PyStructSequence_Desc statvfs_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002055 "statvfs_result", /* name */
2056 statvfs_result__doc__, /* doc */
2057 statvfs_result_fields,
2058 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002059};
2060
Ross Lagerwall7807c352011-03-17 20:20:30 +02002061#if defined(HAVE_WAITID) && !defined(__APPLE__)
2062PyDoc_STRVAR(waitid_result__doc__,
2063"waitid_result: Result from waitid.\n\n\
2064This object may be accessed either as a tuple of\n\
2065 (si_pid, si_uid, si_signo, si_status, si_code),\n\
2066or via the attributes si_pid, si_uid, and so on.\n\
2067\n\
2068See os.waitid for more information.");
2069
2070static PyStructSequence_Field waitid_result_fields[] = {
2071 {"si_pid", },
2072 {"si_uid", },
2073 {"si_signo", },
2074 {"si_status", },
2075 {"si_code", },
2076 {0}
2077};
2078
2079static PyStructSequence_Desc waitid_result_desc = {
2080 "waitid_result", /* name */
2081 waitid_result__doc__, /* doc */
2082 waitid_result_fields,
2083 5
2084};
Benjamin Petersonbad9c2f2011-08-02 18:42:14 -05002085#endif
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002086static newfunc structseq_new;
2087
2088static PyObject *
2089statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2090{
Victor Stinner8c62be82010-05-06 00:08:46 +00002091 PyStructSequence *result;
2092 int i;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002093
Victor Stinner8c62be82010-05-06 00:08:46 +00002094 result = (PyStructSequence*)structseq_new(type, args, kwds);
2095 if (!result)
2096 return NULL;
2097 /* If we have been initialized from a tuple,
2098 st_?time might be set to None. Initialize it
2099 from the int slots. */
2100 for (i = 7; i <= 9; i++) {
2101 if (result->ob_item[i+3] == Py_None) {
2102 Py_DECREF(Py_None);
2103 Py_INCREF(result->ob_item[i]);
2104 result->ob_item[i+3] = result->ob_item[i];
2105 }
2106 }
2107 return (PyObject*)result;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002108}
2109
Eddie Elizondob3966632019-11-05 07:16:14 -08002110static int
2111_posix_clear(PyObject *module)
2112{
Hai Shif707d942020-03-16 21:15:01 +08002113 Py_CLEAR(get_posix_state(module)->billion);
2114 Py_CLEAR(get_posix_state(module)->DirEntryType);
2115 Py_CLEAR(get_posix_state(module)->ScandirIteratorType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002116#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Hai Shif707d942020-03-16 21:15:01 +08002117 Py_CLEAR(get_posix_state(module)->SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002118#endif
Hai Shif707d942020-03-16 21:15:01 +08002119 Py_CLEAR(get_posix_state(module)->StatResultType);
2120 Py_CLEAR(get_posix_state(module)->StatVFSResultType);
2121 Py_CLEAR(get_posix_state(module)->TerminalSizeType);
2122 Py_CLEAR(get_posix_state(module)->TimesResultType);
2123 Py_CLEAR(get_posix_state(module)->UnameResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002124#if defined(HAVE_WAITID) && !defined(__APPLE__)
Hai Shif707d942020-03-16 21:15:01 +08002125 Py_CLEAR(get_posix_state(module)->WaitidResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002126#endif
2127#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
Hai Shif707d942020-03-16 21:15:01 +08002128 Py_CLEAR(get_posix_state(module)->struct_rusage);
Eddie Elizondob3966632019-11-05 07:16:14 -08002129#endif
Hai Shif707d942020-03-16 21:15:01 +08002130 Py_CLEAR(get_posix_state(module)->st_mode);
Eddie Elizondob3966632019-11-05 07:16:14 -08002131 return 0;
2132}
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002133
Eddie Elizondob3966632019-11-05 07:16:14 -08002134static int
2135_posix_traverse(PyObject *module, visitproc visit, void *arg)
2136{
Hai Shif707d942020-03-16 21:15:01 +08002137 Py_VISIT(get_posix_state(module)->billion);
2138 Py_VISIT(get_posix_state(module)->DirEntryType);
2139 Py_VISIT(get_posix_state(module)->ScandirIteratorType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002140#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Hai Shif707d942020-03-16 21:15:01 +08002141 Py_VISIT(get_posix_state(module)->SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002142#endif
Hai Shif707d942020-03-16 21:15:01 +08002143 Py_VISIT(get_posix_state(module)->StatResultType);
2144 Py_VISIT(get_posix_state(module)->StatVFSResultType);
2145 Py_VISIT(get_posix_state(module)->TerminalSizeType);
2146 Py_VISIT(get_posix_state(module)->TimesResultType);
2147 Py_VISIT(get_posix_state(module)->UnameResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002148#if defined(HAVE_WAITID) && !defined(__APPLE__)
Hai Shif707d942020-03-16 21:15:01 +08002149 Py_VISIT(get_posix_state(module)->WaitidResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -08002150#endif
2151#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
Hai Shif707d942020-03-16 21:15:01 +08002152 Py_VISIT(get_posix_state(module)->struct_rusage);
Eddie Elizondob3966632019-11-05 07:16:14 -08002153#endif
Hai Shif707d942020-03-16 21:15:01 +08002154 Py_VISIT(get_posix_state(module)->st_mode);
Eddie Elizondob3966632019-11-05 07:16:14 -08002155 return 0;
2156}
2157
2158static void
2159_posix_free(void *module)
2160{
2161 _posix_clear((PyObject *)module);
2162}
Larry Hastings6fe20b32012-04-19 15:07:49 -07002163
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002164static void
Victor Stinner4195b5c2012-02-08 23:03:19 +01002165fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002166{
Larry Hastings6fe20b32012-04-19 15:07:49 -07002167 PyObject *s = _PyLong_FromTime_t(sec);
2168 PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
2169 PyObject *s_in_ns = NULL;
2170 PyObject *ns_total = NULL;
2171 PyObject *float_s = NULL;
2172
2173 if (!(s && ns_fractional))
2174 goto exit;
2175
Eddie Elizondob3966632019-11-05 07:16:14 -08002176 s_in_ns = PyNumber_Multiply(s, _posixstate_global->billion);
Larry Hastings6fe20b32012-04-19 15:07:49 -07002177 if (!s_in_ns)
2178 goto exit;
2179
2180 ns_total = PyNumber_Add(s_in_ns, ns_fractional);
2181 if (!ns_total)
2182 goto exit;
2183
Victor Stinner01b5aab2017-10-24 02:02:00 -07002184 float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
2185 if (!float_s) {
2186 goto exit;
Larry Hastings6fe20b32012-04-19 15:07:49 -07002187 }
2188
2189 PyStructSequence_SET_ITEM(v, index, s);
2190 PyStructSequence_SET_ITEM(v, index+3, float_s);
2191 PyStructSequence_SET_ITEM(v, index+6, ns_total);
2192 s = NULL;
2193 float_s = NULL;
2194 ns_total = NULL;
2195exit:
2196 Py_XDECREF(s);
2197 Py_XDECREF(ns_fractional);
2198 Py_XDECREF(s_in_ns);
2199 Py_XDECREF(ns_total);
2200 Py_XDECREF(float_s);
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002201}
2202
Tim Peters5aa91602002-01-30 05:46:57 +00002203/* pack a system stat C structure into the Python stat tuple
Fred Drake699f3522000-06-29 21:12:41 +00002204 (used by posix_stat() and posix_fstat()) */
2205static PyObject*
Victor Stinner4195b5c2012-02-08 23:03:19 +01002206_pystat_fromstructstat(STRUCT_STAT *st)
Fred Drake699f3522000-06-29 21:12:41 +00002207{
Victor Stinner8c62be82010-05-06 00:08:46 +00002208 unsigned long ansec, mnsec, cnsec;
Eddie Elizondob3966632019-11-05 07:16:14 -08002209 PyObject *StatResultType = _posixstate_global->StatResultType;
2210 PyObject *v = PyStructSequence_New((PyTypeObject *)StatResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +00002211 if (v == NULL)
2212 return NULL;
Fred Drake699f3522000-06-29 21:12:41 +00002213
Victor Stinner8c62be82010-05-06 00:08:46 +00002214 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode));
Victor Stinner0f6d7332017-03-09 17:34:28 +01002215 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(st->st_ino));
xdegaye50e86032017-05-22 11:15:08 +02002216 PyStructSequence_SET_ITEM(v, 1, PyLong_FromUnsignedLongLong(st->st_ino));
Serhiy Storchaka404fa922013-01-02 18:22:23 +02002217#ifdef MS_WINDOWS
2218 PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002219#else
Serhiy Storchakab2653b32015-01-18 11:12:11 +02002220 PyStructSequence_SET_ITEM(v, 2, _PyLong_FromDev(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002221#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002222 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02002223#if defined(MS_WINDOWS)
2224 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong(0));
2225 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong(0));
2226#else
2227 PyStructSequence_SET_ITEM(v, 4, _PyLong_FromUid(st->st_uid));
2228 PyStructSequence_SET_ITEM(v, 5, _PyLong_FromGid(st->st_gid));
2229#endif
xdegaye50e86032017-05-22 11:15:08 +02002230 Py_BUILD_ASSERT(sizeof(long long) >= sizeof(st->st_size));
2231 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLongLong(st->st_size));
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002232
Martin v. Löwis14694662006-02-03 12:54:16 +00002233#if defined(HAVE_STAT_TV_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002234 ansec = st->st_atim.tv_nsec;
2235 mnsec = st->st_mtim.tv_nsec;
2236 cnsec = st->st_ctim.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002237#elif defined(HAVE_STAT_TV_NSEC2)
Victor Stinner8c62be82010-05-06 00:08:46 +00002238 ansec = st->st_atimespec.tv_nsec;
2239 mnsec = st->st_mtimespec.tv_nsec;
2240 cnsec = st->st_ctimespec.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002241#elif defined(HAVE_STAT_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002242 ansec = st->st_atime_nsec;
2243 mnsec = st->st_mtime_nsec;
2244 cnsec = st->st_ctime_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002245#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002246 ansec = mnsec = cnsec = 0;
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002247#endif
Victor Stinner4195b5c2012-02-08 23:03:19 +01002248 fill_time(v, 7, st->st_atime, ansec);
2249 fill_time(v, 8, st->st_mtime, mnsec);
2250 fill_time(v, 9, st->st_ctime, cnsec);
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002251
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002252#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00002253 PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
2254 PyLong_FromLong((long)st->st_blksize));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002255#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002256#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00002257 PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
2258 PyLong_FromLong((long)st->st_blocks));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002259#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002260#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00002261 PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
2262 PyLong_FromLong((long)st->st_rdev));
Fred Drake699f3522000-06-29 21:12:41 +00002263#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002264#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00002265 PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
2266 PyLong_FromLong((long)st->st_gen));
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002267#endif
2268#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00002269 {
Victor Stinner4195b5c2012-02-08 23:03:19 +01002270 PyObject *val;
2271 unsigned long bsec,bnsec;
2272 bsec = (long)st->st_birthtime;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002273#ifdef HAVE_STAT_TV_NSEC2
Victor Stinner4195b5c2012-02-08 23:03:19 +01002274 bnsec = st->st_birthtimespec.tv_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002275#else
Victor Stinner4195b5c2012-02-08 23:03:19 +01002276 bnsec = 0;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002277#endif
Victor Stinner01b5aab2017-10-24 02:02:00 -07002278 val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
Victor Stinner4195b5c2012-02-08 23:03:19 +01002279 PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
2280 val);
Victor Stinner8c62be82010-05-06 00:08:46 +00002281 }
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002282#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002283#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00002284 PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
2285 PyLong_FromLong((long)st->st_flags));
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002286#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05002287#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2288 PyStructSequence_SET_ITEM(v, ST_FILE_ATTRIBUTES_IDX,
2289 PyLong_FromUnsignedLong(st->st_file_attributes));
2290#endif
jcea6c51d512018-01-28 14:00:08 +01002291#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2292 PyStructSequence_SET_ITEM(v, ST_FSTYPE_IDX,
2293 PyUnicode_FromString(st->st_fstype));
2294#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002295#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2296 PyStructSequence_SET_ITEM(v, ST_REPARSE_TAG_IDX,
2297 PyLong_FromUnsignedLong(st->st_reparse_tag));
2298#endif
Fred Drake699f3522000-06-29 21:12:41 +00002299
Victor Stinner8c62be82010-05-06 00:08:46 +00002300 if (PyErr_Occurred()) {
2301 Py_DECREF(v);
2302 return NULL;
2303 }
Fred Drake699f3522000-06-29 21:12:41 +00002304
Victor Stinner8c62be82010-05-06 00:08:46 +00002305 return v;
Fred Drake699f3522000-06-29 21:12:41 +00002306}
2307
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002308/* POSIX methods */
2309
Guido van Rossum94f6f721999-01-06 18:42:14 +00002310
2311static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002312posix_do_stat(const char *function_name, path_t *path,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002313 int dir_fd, int follow_symlinks)
Guido van Rossum94f6f721999-01-06 18:42:14 +00002314{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002315 STRUCT_STAT st;
2316 int result;
2317
2318#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
2319 if (follow_symlinks_specified(function_name, follow_symlinks))
2320 return NULL;
2321#endif
2322
2323 if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
2324 dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
2325 fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
2326 return NULL;
2327
2328 Py_BEGIN_ALLOW_THREADS
2329 if (path->fd != -1)
2330 result = FSTAT(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002331#ifdef MS_WINDOWS
Steve Dower513d7472016-09-08 10:41:50 -07002332 else if (follow_symlinks)
Steve Dowercc16be82016-09-08 10:35:16 -07002333 result = win32_stat(path->wide, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002334 else
Steve Dowercc16be82016-09-08 10:35:16 -07002335 result = win32_lstat(path->wide, &st);
2336#else
2337 else
2338#if defined(HAVE_LSTAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002339 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
2340 result = LSTAT(path->narrow, &st);
2341 else
Steve Dowercc16be82016-09-08 10:35:16 -07002342#endif /* HAVE_LSTAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002343#ifdef HAVE_FSTATAT
2344 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks)
2345 result = fstatat(dir_fd, path->narrow, &st,
2346 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2347 else
Steve Dowercc16be82016-09-08 10:35:16 -07002348#endif /* HAVE_FSTATAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002349 result = STAT(path->narrow, &st);
Steve Dowercc16be82016-09-08 10:35:16 -07002350#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002351 Py_END_ALLOW_THREADS
2352
Victor Stinner292c8352012-10-30 02:17:38 +01002353 if (result != 0) {
2354 return path_error(path);
2355 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07002356
2357 return _pystat_fromstructstat(&st);
2358}
2359
Larry Hastings2f936352014-08-05 14:04:04 +10002360/*[python input]
2361
2362for s in """
2363
2364FACCESSAT
2365FCHMODAT
2366FCHOWNAT
2367FSTATAT
2368LINKAT
2369MKDIRAT
2370MKFIFOAT
2371MKNODAT
2372OPENAT
2373READLINKAT
2374SYMLINKAT
2375UNLINKAT
2376
2377""".strip().split():
2378 s = s.strip()
2379 print("""
2380#ifdef HAVE_{s}
2381 #define {s}_DIR_FD_CONVERTER dir_fd_converter
Larry Hastings31826802013-10-19 00:09:25 -07002382#else
Larry Hastings2f936352014-08-05 14:04:04 +10002383 #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings31826802013-10-19 00:09:25 -07002384#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002385""".rstrip().format(s=s))
2386
2387for s in """
2388
2389FCHDIR
2390FCHMOD
2391FCHOWN
2392FDOPENDIR
2393FEXECVE
2394FPATHCONF
2395FSTATVFS
2396FTRUNCATE
2397
2398""".strip().split():
2399 s = s.strip()
2400 print("""
2401#ifdef HAVE_{s}
2402 #define PATH_HAVE_{s} 1
2403#else
2404 #define PATH_HAVE_{s} 0
2405#endif
2406
2407""".rstrip().format(s=s))
2408[python start generated code]*/
2409
2410#ifdef HAVE_FACCESSAT
2411 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
2412#else
2413 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
2414#endif
2415
2416#ifdef HAVE_FCHMODAT
2417 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
2418#else
2419 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
2420#endif
2421
2422#ifdef HAVE_FCHOWNAT
2423 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
2424#else
2425 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
2426#endif
2427
2428#ifdef HAVE_FSTATAT
2429 #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
2430#else
2431 #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
2432#endif
2433
2434#ifdef HAVE_LINKAT
2435 #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
2436#else
2437 #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2438#endif
2439
2440#ifdef HAVE_MKDIRAT
2441 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
2442#else
2443 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
2444#endif
2445
2446#ifdef HAVE_MKFIFOAT
2447 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
2448#else
2449 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
2450#endif
2451
2452#ifdef HAVE_MKNODAT
2453 #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
2454#else
2455 #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
2456#endif
2457
2458#ifdef HAVE_OPENAT
2459 #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
2460#else
2461 #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
2462#endif
2463
2464#ifdef HAVE_READLINKAT
2465 #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
2466#else
2467 #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2468#endif
2469
2470#ifdef HAVE_SYMLINKAT
2471 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
2472#else
2473 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2474#endif
2475
2476#ifdef HAVE_UNLINKAT
2477 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
2478#else
2479 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2480#endif
2481
2482#ifdef HAVE_FCHDIR
2483 #define PATH_HAVE_FCHDIR 1
2484#else
2485 #define PATH_HAVE_FCHDIR 0
2486#endif
2487
2488#ifdef HAVE_FCHMOD
2489 #define PATH_HAVE_FCHMOD 1
2490#else
2491 #define PATH_HAVE_FCHMOD 0
2492#endif
2493
2494#ifdef HAVE_FCHOWN
2495 #define PATH_HAVE_FCHOWN 1
2496#else
2497 #define PATH_HAVE_FCHOWN 0
2498#endif
2499
2500#ifdef HAVE_FDOPENDIR
2501 #define PATH_HAVE_FDOPENDIR 1
2502#else
2503 #define PATH_HAVE_FDOPENDIR 0
2504#endif
2505
2506#ifdef HAVE_FEXECVE
2507 #define PATH_HAVE_FEXECVE 1
2508#else
2509 #define PATH_HAVE_FEXECVE 0
2510#endif
2511
2512#ifdef HAVE_FPATHCONF
2513 #define PATH_HAVE_FPATHCONF 1
2514#else
2515 #define PATH_HAVE_FPATHCONF 0
2516#endif
2517
2518#ifdef HAVE_FSTATVFS
2519 #define PATH_HAVE_FSTATVFS 1
2520#else
2521 #define PATH_HAVE_FSTATVFS 0
2522#endif
2523
2524#ifdef HAVE_FTRUNCATE
2525 #define PATH_HAVE_FTRUNCATE 1
2526#else
2527 #define PATH_HAVE_FTRUNCATE 0
2528#endif
2529/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
Larry Hastings31826802013-10-19 00:09:25 -07002530
Steve Dowerfe0a41a2015-03-20 19:50:46 -07002531#ifdef MS_WINDOWS
2532 #undef PATH_HAVE_FTRUNCATE
2533 #define PATH_HAVE_FTRUNCATE 1
2534#endif
Larry Hastings31826802013-10-19 00:09:25 -07002535
Larry Hastings61272b72014-01-07 12:41:53 -08002536/*[python input]
Larry Hastings31826802013-10-19 00:09:25 -07002537
2538class path_t_converter(CConverter):
2539
2540 type = "path_t"
2541 impl_by_reference = True
2542 parse_by_reference = True
2543
2544 converter = 'path_converter'
2545
2546 def converter_init(self, *, allow_fd=False, nullable=False):
Larry Hastings31826802013-10-19 00:09:25 -07002547 # right now path_t doesn't support default values.
2548 # to support a default value, you'll need to override initialize().
Larry Hastings2f936352014-08-05 14:04:04 +10002549 if self.default not in (unspecified, None):
Larry Hastings7726ac92014-01-31 22:03:12 -08002550 fail("Can't specify a default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002551
Larry Hastings2f936352014-08-05 14:04:04 +10002552 if self.c_default not in (None, 'Py_None'):
2553 raise RuntimeError("Can't specify a c_default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002554
2555 self.nullable = nullable
2556 self.allow_fd = allow_fd
2557
Larry Hastings7726ac92014-01-31 22:03:12 -08002558 def pre_render(self):
2559 def strify(value):
Larry Hastings2f936352014-08-05 14:04:04 +10002560 if isinstance(value, str):
2561 return value
Larry Hastings7726ac92014-01-31 22:03:12 -08002562 return str(int(bool(value)))
2563
2564 # add self.py_name here when merging with posixmodule conversion
Larry Hastings2f936352014-08-05 14:04:04 +10002565 self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
Larry Hastings31826802013-10-19 00:09:25 -07002566 self.function.name,
Larry Hastings2f936352014-08-05 14:04:04 +10002567 self.name,
Larry Hastings7726ac92014-01-31 22:03:12 -08002568 strify(self.nullable),
2569 strify(self.allow_fd),
Larry Hastings31826802013-10-19 00:09:25 -07002570 )
2571
2572 def cleanup(self):
2573 return "path_cleanup(&" + self.name + ");\n"
2574
2575
2576class dir_fd_converter(CConverter):
2577 type = 'int'
Larry Hastings31826802013-10-19 00:09:25 -07002578
Larry Hastings2f936352014-08-05 14:04:04 +10002579 def converter_init(self, requires=None):
Larry Hastings31826802013-10-19 00:09:25 -07002580 if self.default in (unspecified, None):
2581 self.c_default = 'DEFAULT_DIR_FD'
Larry Hastings2f936352014-08-05 14:04:04 +10002582 if isinstance(requires, str):
2583 self.converter = requires.upper() + '_DIR_FD_CONVERTER'
2584 else:
2585 self.converter = 'dir_fd_converter'
Larry Hastings31826802013-10-19 00:09:25 -07002586
Larry Hastings2f936352014-08-05 14:04:04 +10002587class fildes_converter(CConverter):
2588 type = 'int'
2589 converter = 'fildes_converter'
2590
2591class uid_t_converter(CConverter):
2592 type = "uid_t"
2593 converter = '_Py_Uid_Converter'
2594
2595class gid_t_converter(CConverter):
2596 type = "gid_t"
2597 converter = '_Py_Gid_Converter'
2598
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02002599class dev_t_converter(CConverter):
2600 type = 'dev_t'
2601 converter = '_Py_Dev_Converter'
2602
2603class dev_t_return_converter(unsigned_long_return_converter):
2604 type = 'dev_t'
2605 conversion_fn = '_PyLong_FromDev'
2606 unsigned_cast = '(dev_t)'
2607
Larry Hastings2f936352014-08-05 14:04:04 +10002608class FSConverter_converter(CConverter):
2609 type = 'PyObject *'
2610 converter = 'PyUnicode_FSConverter'
2611 def converter_init(self):
2612 if self.default is not unspecified:
2613 fail("FSConverter_converter does not support default values")
2614 self.c_default = 'NULL'
2615
2616 def cleanup(self):
2617 return "Py_XDECREF(" + self.name + ");\n"
2618
2619class pid_t_converter(CConverter):
2620 type = 'pid_t'
2621 format_unit = '" _Py_PARSE_PID "'
2622
2623class idtype_t_converter(int_converter):
2624 type = 'idtype_t'
2625
2626class id_t_converter(CConverter):
2627 type = 'id_t'
2628 format_unit = '" _Py_PARSE_PID "'
2629
Benjamin Petersonca470632016-09-06 13:47:26 -07002630class intptr_t_converter(CConverter):
2631 type = 'intptr_t'
Larry Hastings2f936352014-08-05 14:04:04 +10002632 format_unit = '" _Py_PARSE_INTPTR "'
2633
2634class Py_off_t_converter(CConverter):
2635 type = 'Py_off_t'
2636 converter = 'Py_off_t_converter'
2637
2638class Py_off_t_return_converter(long_return_converter):
2639 type = 'Py_off_t'
2640 conversion_fn = 'PyLong_FromPy_off_t'
2641
2642class path_confname_converter(CConverter):
2643 type="int"
2644 converter="conv_path_confname"
2645
2646class confstr_confname_converter(path_confname_converter):
2647 converter='conv_confstr_confname'
2648
2649class sysconf_confname_converter(path_confname_converter):
2650 converter="conv_sysconf_confname"
2651
2652class sched_param_converter(CConverter):
2653 type = 'struct sched_param'
2654 converter = 'convert_sched_param'
2655 impl_by_reference = True;
Larry Hastings31826802013-10-19 00:09:25 -07002656
Larry Hastings61272b72014-01-07 12:41:53 -08002657[python start generated code]*/
Victor Stinner581139c2016-09-06 15:54:20 -07002658/*[python end generated code: output=da39a3ee5e6b4b0d input=418fce0e01144461]*/
Larry Hastings31826802013-10-19 00:09:25 -07002659
Larry Hastings61272b72014-01-07 12:41:53 -08002660/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002661
Larry Hastings2a727912014-01-16 11:32:01 -08002662os.stat
Larry Hastings31826802013-10-19 00:09:25 -07002663
2664 path : path_t(allow_fd=True)
BNMetricsb9427072018-11-02 15:20:19 +00002665 Path to be examined; can be string, bytes, a path-like object or
Xiang Zhang4459e002017-01-22 13:04:17 +08002666 open-file-descriptor int.
Larry Hastings31826802013-10-19 00:09:25 -07002667
2668 *
2669
Larry Hastings2f936352014-08-05 14:04:04 +10002670 dir_fd : dir_fd(requires='fstatat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002671 If not None, it should be a file descriptor open to a directory,
2672 and path should be a relative string; path will then be relative to
2673 that directory.
2674
2675 follow_symlinks: bool = True
2676 If False, and the last element of the path is a symbolic link,
2677 stat will examine the symbolic link itself instead of the file
2678 the link points to.
2679
2680Perform a stat system call on the given path.
2681
2682dir_fd and follow_symlinks may not be implemented
2683 on your platform. If they are unavailable, using them will raise a
2684 NotImplementedError.
2685
2686It's an error to use dir_fd or follow_symlinks when specifying path as
2687 an open file descriptor.
2688
Larry Hastings61272b72014-01-07 12:41:53 -08002689[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002690
Larry Hastings31826802013-10-19 00:09:25 -07002691static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002692os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002693/*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
Larry Hastings31826802013-10-19 00:09:25 -07002694{
2695 return posix_do_stat("stat", path, dir_fd, follow_symlinks);
2696}
2697
Larry Hastings2f936352014-08-05 14:04:04 +10002698
2699/*[clinic input]
2700os.lstat
2701
2702 path : path_t
2703
2704 *
2705
2706 dir_fd : dir_fd(requires='fstatat') = None
2707
2708Perform a stat system call on the given path, without following symbolic links.
2709
2710Like stat(), but do not follow symbolic links.
2711Equivalent to stat(path, follow_symlinks=False).
2712[clinic start generated code]*/
2713
Larry Hastings2f936352014-08-05 14:04:04 +10002714static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002715os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
2716/*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002717{
2718 int follow_symlinks = 0;
2719 return posix_do_stat("lstat", path, dir_fd, follow_symlinks);
2720}
Larry Hastings31826802013-10-19 00:09:25 -07002721
Larry Hastings2f936352014-08-05 14:04:04 +10002722
Larry Hastings61272b72014-01-07 12:41:53 -08002723/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10002724os.access -> bool
Larry Hastings31826802013-10-19 00:09:25 -07002725
Benjamin Peterson768f3b42016-09-05 15:29:33 -07002726 path: path_t
BNMetricsb9427072018-11-02 15:20:19 +00002727 Path to be tested; can be string, bytes, or a path-like object.
Larry Hastings31826802013-10-19 00:09:25 -07002728
2729 mode: int
2730 Operating-system mode bitfield. Can be F_OK to test existence,
2731 or the inclusive-OR of R_OK, W_OK, and X_OK.
2732
2733 *
2734
Larry Hastings2f936352014-08-05 14:04:04 +10002735 dir_fd : dir_fd(requires='faccessat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002736 If not None, it should be a file descriptor open to a directory,
2737 and path should be relative; path will then be relative to that
2738 directory.
2739
2740 effective_ids: bool = False
2741 If True, access will use the effective uid/gid instead of
2742 the real uid/gid.
2743
2744 follow_symlinks: bool = True
2745 If False, and the last element of the path is a symbolic link,
2746 access will examine the symbolic link itself instead of the file
2747 the link points to.
2748
2749Use the real uid/gid to test for access to a path.
2750
2751{parameters}
2752dir_fd, effective_ids, and follow_symlinks may not be implemented
2753 on your platform. If they are unavailable, using them will raise a
2754 NotImplementedError.
2755
2756Note that most operations will use the effective uid/gid, therefore this
2757 routine can be used in a suid/sgid environment to test if the invoking user
2758 has the specified access to the path.
2759
Larry Hastings61272b72014-01-07 12:41:53 -08002760[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002761
Larry Hastings2f936352014-08-05 14:04:04 +10002762static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002763os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002764 int effective_ids, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002765/*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
Larry Hastings31826802013-10-19 00:09:25 -07002766{
Larry Hastings2f936352014-08-05 14:04:04 +10002767 int return_value;
Victor Stinner8c62be82010-05-06 00:08:46 +00002768
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002769#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002770 DWORD attr;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002771#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07002772 int result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002773#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07002774
Larry Hastings9cf065c2012-06-22 16:30:09 -07002775#ifndef HAVE_FACCESSAT
2776 if (follow_symlinks_specified("access", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002777 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002778
2779 if (effective_ids) {
2780 argument_unavailable_error("access", "effective_ids");
Larry Hastings2f936352014-08-05 14:04:04 +10002781 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002782 }
2783#endif
2784
2785#ifdef MS_WINDOWS
2786 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002787 attr = GetFileAttributesW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002788 Py_END_ALLOW_THREADS
2789
2790 /*
Georg Brandlf7875592012-06-24 13:58:31 +02002791 * Access is possible if
Larry Hastings9cf065c2012-06-22 16:30:09 -07002792 * * we didn't get a -1, and
2793 * * write access wasn't requested,
2794 * * or the file isn't read-only,
2795 * * or it's a directory.
2796 * (Directories cannot be read-only on Windows.)
2797 */
Larry Hastings2f936352014-08-05 14:04:04 +10002798 return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
Georg Brandl5bb7aa92012-06-23 12:48:40 +02002799 (!(mode & 2) ||
Larry Hastings9cf065c2012-06-22 16:30:09 -07002800 !(attr & FILE_ATTRIBUTE_READONLY) ||
Larry Hastings2f936352014-08-05 14:04:04 +10002801 (attr & FILE_ATTRIBUTE_DIRECTORY));
Larry Hastings9cf065c2012-06-22 16:30:09 -07002802#else
2803
2804 Py_BEGIN_ALLOW_THREADS
2805#ifdef HAVE_FACCESSAT
2806 if ((dir_fd != DEFAULT_DIR_FD) ||
2807 effective_ids ||
2808 !follow_symlinks) {
2809 int flags = 0;
2810 if (!follow_symlinks)
2811 flags |= AT_SYMLINK_NOFOLLOW;
2812 if (effective_ids)
2813 flags |= AT_EACCESS;
Larry Hastings31826802013-10-19 00:09:25 -07002814 result = faccessat(dir_fd, path->narrow, mode, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002815 }
2816 else
2817#endif
Larry Hastings31826802013-10-19 00:09:25 -07002818 result = access(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002819 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10002820 return_value = !result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002821#endif
2822
Larry Hastings9cf065c2012-06-22 16:30:09 -07002823 return return_value;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002824}
2825
Guido van Rossumd371ff11999-01-25 16:12:23 +00002826#ifndef F_OK
2827#define F_OK 0
2828#endif
2829#ifndef R_OK
2830#define R_OK 4
2831#endif
2832#ifndef W_OK
2833#define W_OK 2
2834#endif
2835#ifndef X_OK
2836#define X_OK 1
2837#endif
2838
Larry Hastings31826802013-10-19 00:09:25 -07002839
Guido van Rossumd371ff11999-01-25 16:12:23 +00002840#ifdef HAVE_TTYNAME
Larry Hastings61272b72014-01-07 12:41:53 -08002841/*[clinic input]
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002842os.ttyname
Larry Hastings31826802013-10-19 00:09:25 -07002843
2844 fd: int
2845 Integer file descriptor handle.
2846
2847 /
2848
2849Return the name of the terminal device connected to 'fd'.
Larry Hastings61272b72014-01-07 12:41:53 -08002850[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002851
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002852static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002853os_ttyname_impl(PyObject *module, int fd)
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002854/*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
Larry Hastings31826802013-10-19 00:09:25 -07002855{
Guido van Rossum94f6f721999-01-06 18:42:14 +00002856
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002857 long size = sysconf(_SC_TTY_NAME_MAX);
2858 if (size == -1) {
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002859 return posix_error();
2860 }
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002861 char *buffer = (char *)PyMem_RawMalloc(size);
2862 if (buffer == NULL) {
2863 return PyErr_NoMemory();
2864 }
2865 int ret = ttyname_r(fd, buffer, size);
2866 if (ret != 0) {
2867 PyMem_RawFree(buffer);
2868 errno = ret;
2869 return posix_error();
2870 }
2871 PyObject *res = PyUnicode_DecodeFSDefault(buffer);
2872 PyMem_RawFree(buffer);
2873 return res;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002874}
Guido van Rossumd371ff11999-01-25 16:12:23 +00002875#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +00002876
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002877#ifdef HAVE_CTERMID
Larry Hastings2f936352014-08-05 14:04:04 +10002878/*[clinic input]
2879os.ctermid
2880
2881Return the name of the controlling terminal for this process.
2882[clinic start generated code]*/
2883
Larry Hastings2f936352014-08-05 14:04:04 +10002884static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002885os_ctermid_impl(PyObject *module)
2886/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002887{
Victor Stinner8c62be82010-05-06 00:08:46 +00002888 char *ret;
2889 char buffer[L_ctermid];
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002890
Greg Wardb48bc172000-03-01 21:51:56 +00002891#ifdef USE_CTERMID_R
Victor Stinner8c62be82010-05-06 00:08:46 +00002892 ret = ctermid_r(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002893#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002894 ret = ctermid(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002895#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002896 if (ret == NULL)
2897 return posix_error();
Victor Stinner5fe6de82010-08-15 09:12:51 +00002898 return PyUnicode_DecodeFSDefault(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002899}
Larry Hastings2f936352014-08-05 14:04:04 +10002900#endif /* HAVE_CTERMID */
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002901
Larry Hastings2f936352014-08-05 14:04:04 +10002902
2903/*[clinic input]
2904os.chdir
2905
2906 path: path_t(allow_fd='PATH_HAVE_FCHDIR')
2907
2908Change the current working directory to the specified path.
2909
2910path may always be specified as a string.
2911On some platforms, path may also be specified as an open file descriptor.
2912 If this functionality is unavailable, using it raises an exception.
2913[clinic start generated code]*/
2914
Larry Hastings2f936352014-08-05 14:04:04 +10002915static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002916os_chdir_impl(PyObject *module, path_t *path)
2917/*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002918{
2919 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002920
Saiyang Gou7514f4f2020-02-12 23:47:42 -08002921 if (PySys_Audit("os.chdir", "(O)", path->object) < 0) {
2922 return NULL;
2923 }
2924
Larry Hastings9cf065c2012-06-22 16:30:09 -07002925 Py_BEGIN_ALLOW_THREADS
2926#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07002927 /* on unix, success = 0, on windows, success = !0 */
2928 result = !win32_wchdir(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002929#else
2930#ifdef HAVE_FCHDIR
Larry Hastings2f936352014-08-05 14:04:04 +10002931 if (path->fd != -1)
2932 result = fchdir(path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002933 else
2934#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002935 result = chdir(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002936#endif
2937 Py_END_ALLOW_THREADS
2938
2939 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002940 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002941 }
2942
Larry Hastings2f936352014-08-05 14:04:04 +10002943 Py_RETURN_NONE;
2944}
2945
2946
2947#ifdef HAVE_FCHDIR
2948/*[clinic input]
2949os.fchdir
2950
2951 fd: fildes
2952
2953Change to the directory of the given file descriptor.
2954
2955fd must be opened on a directory, not a file.
2956Equivalent to os.chdir(fd).
2957
2958[clinic start generated code]*/
2959
Fred Drake4d1e64b2002-04-15 19:40:07 +00002960static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002961os_fchdir_impl(PyObject *module, int fd)
2962/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
Fred Drake4d1e64b2002-04-15 19:40:07 +00002963{
Saiyang Gou7514f4f2020-02-12 23:47:42 -08002964 if (PySys_Audit("os.chdir", "(i)", fd) < 0) {
2965 return NULL;
2966 }
Larry Hastings2f936352014-08-05 14:04:04 +10002967 return posix_fildes_fd(fd, fchdir);
Fred Drake4d1e64b2002-04-15 19:40:07 +00002968}
2969#endif /* HAVE_FCHDIR */
2970
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00002971
Larry Hastings2f936352014-08-05 14:04:04 +10002972/*[clinic input]
2973os.chmod
2974
2975 path: path_t(allow_fd='PATH_HAVE_FCHMOD')
BNMetricsb9427072018-11-02 15:20:19 +00002976 Path to be modified. May always be specified as a str, bytes, or a path-like object.
Larry Hastings2f936352014-08-05 14:04:04 +10002977 On some platforms, path may also be specified as an open file descriptor.
2978 If this functionality is unavailable, using it raises an exception.
2979
2980 mode: int
2981 Operating-system mode bitfield.
2982
2983 *
2984
2985 dir_fd : dir_fd(requires='fchmodat') = None
2986 If not None, it should be a file descriptor open to a directory,
2987 and path should be relative; path will then be relative to that
2988 directory.
2989
2990 follow_symlinks: bool = True
2991 If False, and the last element of the path is a symbolic link,
2992 chmod will modify the symbolic link itself instead of the file
2993 the link points to.
2994
2995Change the access permissions of a file.
2996
2997It is an error to use dir_fd or follow_symlinks when specifying path as
2998 an open file descriptor.
2999dir_fd and follow_symlinks may not be implemented on your platform.
3000 If they are unavailable, using them will raise a NotImplementedError.
3001
3002[clinic start generated code]*/
3003
Larry Hastings2f936352014-08-05 14:04:04 +10003004static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003005os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003006 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003007/*[clinic end generated code: output=5cf6a94915cc7bff input=989081551c00293b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003008{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003009 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003010
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003011#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003012 DWORD attr;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003013#endif
Hirokazu Yamamoto892a37a2009-06-28 11:07:03 +00003014
Larry Hastings9cf065c2012-06-22 16:30:09 -07003015#ifdef HAVE_FCHMODAT
3016 int fchmodat_nofollow_unsupported = 0;
3017#endif
3018
Larry Hastings9cf065c2012-06-22 16:30:09 -07003019#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
3020 if (follow_symlinks_specified("chmod", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003021 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003022#endif
3023
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003024 if (PySys_Audit("os.chmod", "Oii", path->object, mode,
3025 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
3026 return NULL;
3027 }
3028
Larry Hastings9cf065c2012-06-22 16:30:09 -07003029#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003030 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003031 attr = GetFileAttributesW(path->wide);
Tim Golden23005082013-10-25 11:22:37 +01003032 if (attr == INVALID_FILE_ATTRIBUTES)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003033 result = 0;
3034 else {
3035 if (mode & _S_IWRITE)
Victor Stinner8c62be82010-05-06 00:08:46 +00003036 attr &= ~FILE_ATTRIBUTE_READONLY;
3037 else
3038 attr |= FILE_ATTRIBUTE_READONLY;
Steve Dowercc16be82016-09-08 10:35:16 -07003039 result = SetFileAttributesW(path->wide, attr);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003040 }
3041 Py_END_ALLOW_THREADS
3042
3043 if (!result) {
Larry Hastings2f936352014-08-05 14:04:04 +10003044 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003045 }
3046#else /* MS_WINDOWS */
3047 Py_BEGIN_ALLOW_THREADS
3048#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003049 if (path->fd != -1)
3050 result = fchmod(path->fd, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003051 else
3052#endif
3053#ifdef HAVE_LCHMOD
3054 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003055 result = lchmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003056 else
3057#endif
3058#ifdef HAVE_FCHMODAT
3059 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
3060 /*
3061 * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
3062 * The documentation specifically shows how to use it,
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003063 * and then says it isn't implemented yet.
3064 * (true on linux with glibc 2.15, and openindiana 3.x)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003065 *
3066 * Once it is supported, os.chmod will automatically
3067 * support dir_fd and follow_symlinks=False. (Hopefully.)
3068 * Until then, we need to be careful what exception we raise.
3069 */
Larry Hastings2f936352014-08-05 14:04:04 +10003070 result = fchmodat(dir_fd, path->narrow, mode,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003071 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3072 /*
3073 * But wait! We can't throw the exception without allowing threads,
3074 * and we can't do that in this nested scope. (Macro trickery, sigh.)
3075 */
3076 fchmodat_nofollow_unsupported =
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003077 result &&
3078 ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
3079 !follow_symlinks;
Victor Stinner8c62be82010-05-06 00:08:46 +00003080 }
3081 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00003082#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003083 result = chmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003084 Py_END_ALLOW_THREADS
3085
3086 if (result) {
3087#ifdef HAVE_FCHMODAT
3088 if (fchmodat_nofollow_unsupported) {
3089 if (dir_fd != DEFAULT_DIR_FD)
3090 dir_fd_and_follow_symlinks_invalid("chmod",
3091 dir_fd, follow_symlinks);
3092 else
3093 follow_symlinks_specified("chmod", follow_symlinks);
Anthony Sottile233ef242017-12-14 08:57:55 -08003094 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003095 }
3096 else
3097#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003098 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003099 }
3100#endif
3101
Larry Hastings2f936352014-08-05 14:04:04 +10003102 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003103}
3104
Larry Hastings9cf065c2012-06-22 16:30:09 -07003105
Christian Heimes4e30a842007-11-30 22:12:06 +00003106#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003107/*[clinic input]
3108os.fchmod
3109
3110 fd: int
3111 mode: int
3112
3113Change the access permissions of the file given by file descriptor fd.
3114
3115Equivalent to os.chmod(fd, mode).
3116[clinic start generated code]*/
3117
Larry Hastings2f936352014-08-05 14:04:04 +10003118static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003119os_fchmod_impl(PyObject *module, int fd, int mode)
3120/*[clinic end generated code: output=afd9bc05b4e426b3 input=8ab11975ca01ee5b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003121{
3122 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003123 int async_err = 0;
3124
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003125 if (PySys_Audit("os.chmod", "iii", fd, mode, -1) < 0) {
3126 return NULL;
3127 }
3128
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003129 do {
3130 Py_BEGIN_ALLOW_THREADS
3131 res = fchmod(fd, mode);
3132 Py_END_ALLOW_THREADS
3133 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3134 if (res != 0)
3135 return (!async_err) ? posix_error() : NULL;
3136
Victor Stinner8c62be82010-05-06 00:08:46 +00003137 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003138}
3139#endif /* HAVE_FCHMOD */
3140
Larry Hastings2f936352014-08-05 14:04:04 +10003141
Christian Heimes4e30a842007-11-30 22:12:06 +00003142#ifdef HAVE_LCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003143/*[clinic input]
3144os.lchmod
3145
3146 path: path_t
3147 mode: int
3148
3149Change the access permissions of a file, without following symbolic links.
3150
3151If path is a symlink, this affects the link itself rather than the target.
3152Equivalent to chmod(path, mode, follow_symlinks=False)."
3153[clinic start generated code]*/
3154
Larry Hastings2f936352014-08-05 14:04:04 +10003155static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003156os_lchmod_impl(PyObject *module, path_t *path, int mode)
3157/*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003158{
Victor Stinner8c62be82010-05-06 00:08:46 +00003159 int res;
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003160 if (PySys_Audit("os.chmod", "Oii", path->object, mode, -1) < 0) {
3161 return NULL;
3162 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003163 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003164 res = lchmod(path->narrow, mode);
Victor Stinner8c62be82010-05-06 00:08:46 +00003165 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003166 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003167 path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003168 return NULL;
3169 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003170 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003171}
3172#endif /* HAVE_LCHMOD */
3173
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003174
Thomas Wouterscf297e42007-02-23 15:07:44 +00003175#ifdef HAVE_CHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003176/*[clinic input]
3177os.chflags
3178
3179 path: path_t
3180 flags: unsigned_long(bitwise=True)
3181 follow_symlinks: bool=True
3182
3183Set file flags.
3184
3185If follow_symlinks is False, and the last element of the path is a symbolic
3186 link, chflags will change flags on the symbolic link itself instead of the
3187 file the link points to.
3188follow_symlinks may not be implemented on your platform. If it is
3189unavailable, using it will raise a NotImplementedError.
3190
3191[clinic start generated code]*/
3192
Larry Hastings2f936352014-08-05 14:04:04 +10003193static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003194os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
Larry Hastings89964c42015-04-14 18:07:59 -04003195 int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003196/*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003197{
3198 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003199
3200#ifndef HAVE_LCHFLAGS
3201 if (follow_symlinks_specified("chflags", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003202 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003203#endif
3204
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003205 if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
3206 return NULL;
3207 }
3208
Victor Stinner8c62be82010-05-06 00:08:46 +00003209 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003210#ifdef HAVE_LCHFLAGS
3211 if (!follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +10003212 result = lchflags(path->narrow, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003213 else
3214#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003215 result = chflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003216 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003217
Larry Hastings2f936352014-08-05 14:04:04 +10003218 if (result)
3219 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003220
Larry Hastings2f936352014-08-05 14:04:04 +10003221 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003222}
3223#endif /* HAVE_CHFLAGS */
3224
Larry Hastings2f936352014-08-05 14:04:04 +10003225
Thomas Wouterscf297e42007-02-23 15:07:44 +00003226#ifdef HAVE_LCHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003227/*[clinic input]
3228os.lchflags
3229
3230 path: path_t
3231 flags: unsigned_long(bitwise=True)
3232
3233Set file flags.
3234
3235This function will not follow symbolic links.
3236Equivalent to chflags(path, flags, follow_symlinks=False).
3237[clinic start generated code]*/
3238
Larry Hastings2f936352014-08-05 14:04:04 +10003239static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003240os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
3241/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003242{
Victor Stinner8c62be82010-05-06 00:08:46 +00003243 int res;
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003244 if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
3245 return NULL;
3246 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003247 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003248 res = lchflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003249 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003250 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003251 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003252 }
Victor Stinner292c8352012-10-30 02:17:38 +01003253 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003254}
3255#endif /* HAVE_LCHFLAGS */
3256
Larry Hastings2f936352014-08-05 14:04:04 +10003257
Martin v. Löwis244edc82001-10-04 22:44:26 +00003258#ifdef HAVE_CHROOT
Larry Hastings2f936352014-08-05 14:04:04 +10003259/*[clinic input]
3260os.chroot
3261 path: path_t
3262
3263Change root directory to path.
3264
3265[clinic start generated code]*/
3266
Larry Hastings2f936352014-08-05 14:04:04 +10003267static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003268os_chroot_impl(PyObject *module, path_t *path)
3269/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003270{
3271 int res;
3272 Py_BEGIN_ALLOW_THREADS
3273 res = chroot(path->narrow);
3274 Py_END_ALLOW_THREADS
3275 if (res < 0)
3276 return path_error(path);
3277 Py_RETURN_NONE;
3278}
3279#endif /* HAVE_CHROOT */
3280
Martin v. Löwis244edc82001-10-04 22:44:26 +00003281
Guido van Rossum21142a01999-01-08 21:05:37 +00003282#ifdef HAVE_FSYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003283/*[clinic input]
3284os.fsync
3285
3286 fd: fildes
3287
3288Force write of fd to disk.
3289[clinic start generated code]*/
3290
Larry Hastings2f936352014-08-05 14:04:04 +10003291static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003292os_fsync_impl(PyObject *module, int fd)
3293/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003294{
3295 return posix_fildes_fd(fd, fsync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003296}
3297#endif /* HAVE_FSYNC */
3298
Larry Hastings2f936352014-08-05 14:04:04 +10003299
Ross Lagerwall7807c352011-03-17 20:20:30 +02003300#ifdef HAVE_SYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003301/*[clinic input]
3302os.sync
3303
3304Force write of everything to disk.
3305[clinic start generated code]*/
3306
Larry Hastings2f936352014-08-05 14:04:04 +10003307static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003308os_sync_impl(PyObject *module)
3309/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
Ross Lagerwall7807c352011-03-17 20:20:30 +02003310{
3311 Py_BEGIN_ALLOW_THREADS
3312 sync();
3313 Py_END_ALLOW_THREADS
3314 Py_RETURN_NONE;
3315}
Larry Hastings2f936352014-08-05 14:04:04 +10003316#endif /* HAVE_SYNC */
3317
Ross Lagerwall7807c352011-03-17 20:20:30 +02003318
Guido van Rossum21142a01999-01-08 21:05:37 +00003319#ifdef HAVE_FDATASYNC
Guido van Rossum7f58e2e2000-09-22 17:26:14 +00003320#ifdef __hpux
Guido van Rossumecc23b02000-09-22 16:01:05 +00003321extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
3322#endif
3323
Larry Hastings2f936352014-08-05 14:04:04 +10003324/*[clinic input]
3325os.fdatasync
3326
3327 fd: fildes
3328
3329Force write of fd to disk without forcing update of metadata.
3330[clinic start generated code]*/
3331
Larry Hastings2f936352014-08-05 14:04:04 +10003332static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003333os_fdatasync_impl(PyObject *module, int fd)
3334/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003335{
3336 return posix_fildes_fd(fd, fdatasync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003337}
3338#endif /* HAVE_FDATASYNC */
3339
3340
Fredrik Lundh10723342000-07-10 16:38:09 +00003341#ifdef HAVE_CHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003342/*[clinic input]
3343os.chown
3344
3345 path : path_t(allow_fd='PATH_HAVE_FCHOWN')
BNMetricsb9427072018-11-02 15:20:19 +00003346 Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
Larry Hastings2f936352014-08-05 14:04:04 +10003347
3348 uid: uid_t
3349
3350 gid: gid_t
3351
3352 *
3353
3354 dir_fd : dir_fd(requires='fchownat') = None
3355 If not None, it should be a file descriptor open to a directory,
3356 and path should be relative; path will then be relative to that
3357 directory.
3358
3359 follow_symlinks: bool = True
3360 If False, and the last element of the path is a symbolic link,
3361 stat will examine the symbolic link itself instead of the file
3362 the link points to.
3363
3364Change the owner and group id of path to the numeric uid and gid.\
3365
3366path may always be specified as a string.
3367On some platforms, path may also be specified as an open file descriptor.
3368 If this functionality is unavailable, using it raises an exception.
3369If dir_fd is not None, it should be a file descriptor open to a directory,
3370 and path should be relative; path will then be relative to that directory.
3371If follow_symlinks is False, and the last element of the path is a symbolic
3372 link, chown will modify the symbolic link itself instead of the file the
3373 link points to.
3374It is an error to use dir_fd or follow_symlinks when specifying path as
3375 an open file descriptor.
3376dir_fd and follow_symlinks may not be implemented on your platform.
3377 If they are unavailable, using them will raise a NotImplementedError.
3378
3379[clinic start generated code]*/
3380
Larry Hastings2f936352014-08-05 14:04:04 +10003381static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003382os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
Larry Hastings89964c42015-04-14 18:07:59 -04003383 int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003384/*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003385{
3386 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003387
3388#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
3389 if (follow_symlinks_specified("chown", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003390 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003391#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003392 if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
3393 fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
3394 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003395
3396#ifdef __APPLE__
3397 /*
3398 * This is for Mac OS X 10.3, which doesn't have lchown.
3399 * (But we still have an lchown symbol because of weak-linking.)
3400 * It doesn't have fchownat either. So there's no possibility
3401 * of a graceful failover.
Georg Brandlf7875592012-06-24 13:58:31 +02003402 */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003403 if ((!follow_symlinks) && (lchown == NULL)) {
3404 follow_symlinks_specified("chown", follow_symlinks);
Larry Hastings2f936352014-08-05 14:04:04 +10003405 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003406 }
3407#endif
3408
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003409 if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid,
3410 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
3411 return NULL;
3412 }
3413
Victor Stinner8c62be82010-05-06 00:08:46 +00003414 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003415#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003416 if (path->fd != -1)
3417 result = fchown(path->fd, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003418 else
3419#endif
3420#ifdef HAVE_LCHOWN
3421 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003422 result = lchown(path->narrow, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003423 else
3424#endif
3425#ifdef HAVE_FCHOWNAT
3426 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003427 result = fchownat(dir_fd, path->narrow, uid, gid,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003428 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3429 else
3430#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003431 result = chown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003432 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003433
Larry Hastings2f936352014-08-05 14:04:04 +10003434 if (result)
3435 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003436
Larry Hastings2f936352014-08-05 14:04:04 +10003437 Py_RETURN_NONE;
Guido van Rossumb6775db1994-08-01 11:34:53 +00003438}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003439#endif /* HAVE_CHOWN */
Guido van Rossumb6775db1994-08-01 11:34:53 +00003440
Larry Hastings2f936352014-08-05 14:04:04 +10003441
Christian Heimes4e30a842007-11-30 22:12:06 +00003442#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003443/*[clinic input]
3444os.fchown
3445
3446 fd: int
3447 uid: uid_t
3448 gid: gid_t
3449
3450Change the owner and group id of the file specified by file descriptor.
3451
3452Equivalent to os.chown(fd, uid, gid).
3453
3454[clinic start generated code]*/
3455
Larry Hastings2f936352014-08-05 14:04:04 +10003456static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003457os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
3458/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003459{
Victor Stinner8c62be82010-05-06 00:08:46 +00003460 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003461 int async_err = 0;
3462
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003463 if (PySys_Audit("os.chown", "iIIi", fd, uid, gid, -1) < 0) {
3464 return NULL;
3465 }
3466
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003467 do {
3468 Py_BEGIN_ALLOW_THREADS
3469 res = fchown(fd, uid, gid);
3470 Py_END_ALLOW_THREADS
3471 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3472 if (res != 0)
3473 return (!async_err) ? posix_error() : NULL;
3474
Victor Stinner8c62be82010-05-06 00:08:46 +00003475 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003476}
3477#endif /* HAVE_FCHOWN */
3478
Larry Hastings2f936352014-08-05 14:04:04 +10003479
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003480#ifdef HAVE_LCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003481/*[clinic input]
3482os.lchown
3483
3484 path : path_t
3485 uid: uid_t
3486 gid: gid_t
3487
3488Change the owner and group id of path to the numeric uid and gid.
3489
3490This function will not follow symbolic links.
3491Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
3492[clinic start generated code]*/
3493
Larry Hastings2f936352014-08-05 14:04:04 +10003494static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003495os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
3496/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003497{
Victor Stinner8c62be82010-05-06 00:08:46 +00003498 int res;
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003499 if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid, -1) < 0) {
3500 return NULL;
3501 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003502 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10003503 res = lchown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003504 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003505 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003506 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003507 }
Larry Hastings2f936352014-08-05 14:04:04 +10003508 Py_RETURN_NONE;
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003509}
3510#endif /* HAVE_LCHOWN */
3511
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003512
Barry Warsaw53699e91996-12-10 23:23:01 +00003513static PyObject *
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003514posix_getcwd(int use_bytes)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003515{
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003516#ifdef MS_WINDOWS
Victor Stinner689830e2019-06-26 17:31:12 +02003517 wchar_t wbuf[MAXPATHLEN];
3518 wchar_t *wbuf2 = wbuf;
3519 DWORD len;
3520
3521 Py_BEGIN_ALLOW_THREADS
3522 len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
3523 /* If the buffer is large enough, len does not include the
3524 terminating \0. If the buffer is too small, len includes
3525 the space needed for the terminator. */
3526 if (len >= Py_ARRAY_LENGTH(wbuf)) {
Victor Stinnerec3e20a2019-06-28 18:01:59 +02003527 if (len <= PY_SSIZE_T_MAX / sizeof(wchar_t)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02003528 wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00003529 }
Victor Stinner689830e2019-06-26 17:31:12 +02003530 else {
3531 wbuf2 = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003532 }
Victor Stinner689830e2019-06-26 17:31:12 +02003533 if (wbuf2) {
3534 len = GetCurrentDirectoryW(len, wbuf2);
Victor Stinner8c62be82010-05-06 00:08:46 +00003535 }
Victor Stinner689830e2019-06-26 17:31:12 +02003536 }
3537 Py_END_ALLOW_THREADS
3538
3539 if (!wbuf2) {
3540 PyErr_NoMemory();
3541 return NULL;
3542 }
3543 if (!len) {
Victor Stinnerb024e842012-10-31 22:24:06 +01003544 if (wbuf2 != wbuf)
Victor Stinnerb6404912013-07-07 16:21:41 +02003545 PyMem_RawFree(wbuf2);
Victor Stinner689830e2019-06-26 17:31:12 +02003546 return PyErr_SetFromWindowsErr(0);
Victor Stinner8c62be82010-05-06 00:08:46 +00003547 }
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01003548
Victor Stinner689830e2019-06-26 17:31:12 +02003549 PyObject *resobj = PyUnicode_FromWideChar(wbuf2, len);
3550 if (wbuf2 != wbuf) {
3551 PyMem_RawFree(wbuf2);
3552 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003553
Victor Stinner689830e2019-06-26 17:31:12 +02003554 if (use_bytes) {
3555 if (resobj == NULL) {
3556 return NULL;
3557 }
3558 Py_SETREF(resobj, PyUnicode_EncodeFSDefault(resobj));
3559 }
3560
3561 return resobj;
3562#else
3563 const size_t chunk = 1024;
3564
3565 char *buf = NULL;
3566 char *cwd = NULL;
3567 size_t buflen = 0;
3568
Victor Stinner8c62be82010-05-06 00:08:46 +00003569 Py_BEGIN_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003570 do {
Victor Stinner689830e2019-06-26 17:31:12 +02003571 char *newbuf;
3572 if (buflen <= PY_SSIZE_T_MAX - chunk) {
3573 buflen += chunk;
3574 newbuf = PyMem_RawRealloc(buf, buflen);
3575 }
3576 else {
3577 newbuf = NULL;
3578 }
3579 if (newbuf == NULL) {
3580 PyMem_RawFree(buf);
3581 buf = NULL;
Victor Stinnerc44f7072016-03-14 18:07:53 +01003582 break;
3583 }
Victor Stinner689830e2019-06-26 17:31:12 +02003584 buf = newbuf;
Victor Stinner4403d7d2015-04-25 00:16:10 +02003585
Victor Stinner4403d7d2015-04-25 00:16:10 +02003586 cwd = getcwd(buf, buflen);
3587 } while (cwd == NULL && errno == ERANGE);
Victor Stinner8c62be82010-05-06 00:08:46 +00003588 Py_END_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003589
Victor Stinner689830e2019-06-26 17:31:12 +02003590 if (buf == NULL) {
3591 return PyErr_NoMemory();
3592 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003593 if (cwd == NULL) {
3594 PyMem_RawFree(buf);
Victor Stinner8c62be82010-05-06 00:08:46 +00003595 return posix_error();
Victor Stinner4403d7d2015-04-25 00:16:10 +02003596 }
3597
Victor Stinner689830e2019-06-26 17:31:12 +02003598 PyObject *obj;
3599 if (use_bytes) {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003600 obj = PyBytes_FromStringAndSize(buf, strlen(buf));
Victor Stinner689830e2019-06-26 17:31:12 +02003601 }
3602 else {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003603 obj = PyUnicode_DecodeFSDefault(buf);
Victor Stinner689830e2019-06-26 17:31:12 +02003604 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003605 PyMem_RawFree(buf);
3606
3607 return obj;
Victor Stinner689830e2019-06-26 17:31:12 +02003608#endif /* !MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003609}
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003610
Larry Hastings2f936352014-08-05 14:04:04 +10003611
3612/*[clinic input]
3613os.getcwd
3614
3615Return a unicode string representing the current working directory.
3616[clinic start generated code]*/
3617
Larry Hastings2f936352014-08-05 14:04:04 +10003618static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003619os_getcwd_impl(PyObject *module)
3620/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003621{
3622 return posix_getcwd(0);
3623}
3624
Larry Hastings2f936352014-08-05 14:04:04 +10003625
3626/*[clinic input]
3627os.getcwdb
3628
3629Return a bytes string representing the current working directory.
3630[clinic start generated code]*/
3631
Larry Hastings2f936352014-08-05 14:04:04 +10003632static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003633os_getcwdb_impl(PyObject *module)
3634/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003635{
3636 return posix_getcwd(1);
3637}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003638
Larry Hastings2f936352014-08-05 14:04:04 +10003639
Larry Hastings9cf065c2012-06-22 16:30:09 -07003640#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
3641#define HAVE_LINK 1
3642#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003643
Guido van Rossumb6775db1994-08-01 11:34:53 +00003644#ifdef HAVE_LINK
Larry Hastings2f936352014-08-05 14:04:04 +10003645/*[clinic input]
3646
3647os.link
3648
3649 src : path_t
3650 dst : path_t
3651 *
3652 src_dir_fd : dir_fd = None
3653 dst_dir_fd : dir_fd = None
3654 follow_symlinks: bool = True
3655
3656Create a hard link to a file.
3657
3658If either src_dir_fd or dst_dir_fd is not None, it should be a file
3659 descriptor open to a directory, and the respective path string (src or dst)
3660 should be relative; the path will then be relative to that directory.
3661If follow_symlinks is False, and the last element of src is a symbolic
3662 link, link will create a link to the symbolic link itself instead of the
3663 file the link points to.
3664src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
3665 platform. If they are unavailable, using them will raise a
3666 NotImplementedError.
3667[clinic start generated code]*/
3668
Larry Hastings2f936352014-08-05 14:04:04 +10003669static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003670os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003671 int dst_dir_fd, int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003672/*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003673{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003674#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07003675 BOOL result = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003676#else
3677 int result;
3678#endif
3679
Larry Hastings9cf065c2012-06-22 16:30:09 -07003680#ifndef HAVE_LINKAT
3681 if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
3682 argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10003683 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003684 }
3685#endif
3686
Steve Dowercc16be82016-09-08 10:35:16 -07003687#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10003688 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003689 PyErr_SetString(PyExc_NotImplementedError,
3690 "link: src and dst must be the same type");
Larry Hastings2f936352014-08-05 14:04:04 +10003691 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003692 }
Steve Dowercc16be82016-09-08 10:35:16 -07003693#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003694
Saiyang Gou7514f4f2020-02-12 23:47:42 -08003695 if (PySys_Audit("os.link", "OOii", src->object, dst->object,
3696 src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
3697 dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
3698 return NULL;
3699 }
3700
Brian Curtin1b9df392010-11-24 20:24:31 +00003701#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003702 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08003703 result = CreateHardLinkW(dst->wide, src->wide, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003704 Py_END_ALLOW_THREADS
Brian Curtin1b9df392010-11-24 20:24:31 +00003705
Larry Hastings2f936352014-08-05 14:04:04 +10003706 if (!result)
3707 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003708#else
3709 Py_BEGIN_ALLOW_THREADS
Larry Hastings67cbf7b2012-06-22 17:06:48 -07003710#ifdef HAVE_LINKAT
Larry Hastings9cf065c2012-06-22 16:30:09 -07003711 if ((src_dir_fd != DEFAULT_DIR_FD) ||
3712 (dst_dir_fd != DEFAULT_DIR_FD) ||
3713 (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003714 result = linkat(src_dir_fd, src->narrow,
3715 dst_dir_fd, dst->narrow,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003716 follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
3717 else
Steve Dowercc16be82016-09-08 10:35:16 -07003718#endif /* HAVE_LINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10003719 result = link(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003720 Py_END_ALLOW_THREADS
Brian Curtinfc889c42010-11-28 23:59:46 +00003721
Larry Hastings2f936352014-08-05 14:04:04 +10003722 if (result)
3723 return path_error2(src, dst);
Steve Dowercc16be82016-09-08 10:35:16 -07003724#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003725
Larry Hastings2f936352014-08-05 14:04:04 +10003726 Py_RETURN_NONE;
Brian Curtin1b9df392010-11-24 20:24:31 +00003727}
Larry Hastings9cf065c2012-06-22 16:30:09 -07003728#endif
3729
Brian Curtin1b9df392010-11-24 20:24:31 +00003730
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003731#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
Barry Warsaw53699e91996-12-10 23:23:01 +00003732static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003733_listdir_windows_no_opendir(path_t *path, PyObject *list)
Guido van Rossumb6775db1994-08-01 11:34:53 +00003734{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003735 PyObject *v;
3736 HANDLE hFindFile = INVALID_HANDLE_VALUE;
3737 BOOL result;
Steve Dowercc16be82016-09-08 10:35:16 -07003738 wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003739 /* only claim to have space for MAX_PATH */
Victor Stinner75875072013-11-24 19:23:25 +01003740 Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003741 wchar_t *wnamebuf = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003742
Steve Dowercc16be82016-09-08 10:35:16 -07003743 WIN32_FIND_DATAW wFileData;
3744 const wchar_t *po_wchars;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003745
Steve Dowercc16be82016-09-08 10:35:16 -07003746 if (!path->wide) { /* Default arg: "." */
3747 po_wchars = L".";
3748 len = 1;
3749 } else {
3750 po_wchars = path->wide;
3751 len = wcslen(path->wide);
3752 }
3753 /* The +5 is so we can append "\\*.*\0" */
3754 wnamebuf = PyMem_New(wchar_t, len + 5);
3755 if (!wnamebuf) {
3756 PyErr_NoMemory();
Larry Hastings9cf065c2012-06-22 16:30:09 -07003757 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003758 }
Steve Dowercc16be82016-09-08 10:35:16 -07003759 wcscpy(wnamebuf, po_wchars);
Victor Stinner8c62be82010-05-06 00:08:46 +00003760 if (len > 0) {
Steve Dowercc16be82016-09-08 10:35:16 -07003761 wchar_t wch = wnamebuf[len-1];
3762 if (wch != SEP && wch != ALTSEP && wch != L':')
3763 wnamebuf[len++] = SEP;
3764 wcscpy(wnamebuf + len, L"*.*");
Victor Stinner8c62be82010-05-06 00:08:46 +00003765 }
Steve Dowercc16be82016-09-08 10:35:16 -07003766 if ((list = PyList_New(0)) == NULL) {
3767 goto exit;
3768 }
Antoine Pitroub73caab2010-08-09 23:39:31 +00003769 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003770 hFindFile = FindFirstFileW(wnamebuf, &wFileData);
Antoine Pitroub73caab2010-08-09 23:39:31 +00003771 Py_END_ALLOW_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +00003772 if (hFindFile == INVALID_HANDLE_VALUE) {
3773 int error = GetLastError();
3774 if (error == ERROR_FILE_NOT_FOUND)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003775 goto exit;
3776 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003777 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003778 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003779 }
3780 do {
3781 /* Skip over . and .. */
Steve Dowercc16be82016-09-08 10:35:16 -07003782 if (wcscmp(wFileData.cFileName, L".") != 0 &&
3783 wcscmp(wFileData.cFileName, L"..") != 0) {
3784 v = PyUnicode_FromWideChar(wFileData.cFileName,
3785 wcslen(wFileData.cFileName));
3786 if (path->narrow && v) {
3787 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3788 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003789 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003790 Py_DECREF(list);
3791 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003792 break;
3793 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003794 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003795 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003796 Py_DECREF(list);
3797 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003798 break;
3799 }
3800 Py_DECREF(v);
3801 }
3802 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003803 result = FindNextFileW(hFindFile, &wFileData);
Victor Stinner8c62be82010-05-06 00:08:46 +00003804 Py_END_ALLOW_THREADS
3805 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
3806 it got to the end of the directory. */
3807 if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003808 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003809 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003810 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003811 }
3812 } while (result == TRUE);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003813
Larry Hastings9cf065c2012-06-22 16:30:09 -07003814exit:
3815 if (hFindFile != INVALID_HANDLE_VALUE) {
3816 if (FindClose(hFindFile) == FALSE) {
3817 if (list != NULL) {
3818 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003819 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003820 }
3821 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003822 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003823 PyMem_Free(wnamebuf);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003824
Larry Hastings9cf065c2012-06-22 16:30:09 -07003825 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003826} /* end of _listdir_windows_no_opendir */
3827
3828#else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
3829
3830static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003831_posix_listdir(path_t *path, PyObject *list)
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003832{
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003833 PyObject *v;
3834 DIR *dirp = NULL;
3835 struct dirent *ep;
3836 int return_str; /* if false, return bytes */
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003837#ifdef HAVE_FDOPENDIR
3838 int fd = -1;
3839#endif
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003840
Victor Stinner8c62be82010-05-06 00:08:46 +00003841 errno = 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003842#ifdef HAVE_FDOPENDIR
Gregory P. Smith40a21602013-03-20 20:52:50 -07003843 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003844 /* closedir() closes the FD, so we duplicate it */
Victor Stinnerdaf45552013-08-28 00:53:59 +02003845 fd = _Py_dup(path->fd);
Victor Stinnerf3266652013-12-19 13:24:49 +01003846 if (fd == -1)
3847 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003848
Larry Hastingsfdaea062012-06-25 04:42:23 -07003849 return_str = 1;
3850
Larry Hastings9cf065c2012-06-22 16:30:09 -07003851 Py_BEGIN_ALLOW_THREADS
3852 dirp = fdopendir(fd);
3853 Py_END_ALLOW_THREADS
3854 }
3855 else
3856#endif
3857 {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003858 const char *name;
Gregory P. Smith40a21602013-03-20 20:52:50 -07003859 if (path->narrow) {
3860 name = path->narrow;
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03003861 /* only return bytes if they specified a bytes-like object */
3862 return_str = !PyObject_CheckBuffer(path->object);
Larry Hastingsfdaea062012-06-25 04:42:23 -07003863 }
3864 else {
3865 name = ".";
3866 return_str = 1;
3867 }
3868
Larry Hastings9cf065c2012-06-22 16:30:09 -07003869 Py_BEGIN_ALLOW_THREADS
3870 dirp = opendir(name);
3871 Py_END_ALLOW_THREADS
3872 }
3873
3874 if (dirp == NULL) {
Gregory P. Smith40a21602013-03-20 20:52:50 -07003875 list = path_error(path);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003876#ifdef HAVE_FDOPENDIR
3877 if (fd != -1) {
3878 Py_BEGIN_ALLOW_THREADS
3879 close(fd);
3880 Py_END_ALLOW_THREADS
3881 }
3882#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003883 goto exit;
3884 }
3885 if ((list = PyList_New(0)) == NULL) {
3886 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003887 }
3888 for (;;) {
3889 errno = 0;
3890 Py_BEGIN_ALLOW_THREADS
3891 ep = readdir(dirp);
3892 Py_END_ALLOW_THREADS
3893 if (ep == NULL) {
3894 if (errno == 0) {
3895 break;
3896 } else {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003897 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003898 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003899 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003900 }
3901 }
3902 if (ep->d_name[0] == '.' &&
3903 (NAMLEN(ep) == 1 ||
3904 (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
3905 continue;
Larry Hastingsfdaea062012-06-25 04:42:23 -07003906 if (return_str)
Victor Stinnera45598a2010-05-14 16:35:39 +00003907 v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
3908 else
3909 v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
Victor Stinner8c62be82010-05-06 00:08:46 +00003910 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003911 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003912 break;
3913 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003914 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003915 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003916 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003917 break;
3918 }
3919 Py_DECREF(v);
3920 }
Guido van Rossum0ee42cd1991-04-08 21:01:03 +00003921
Larry Hastings9cf065c2012-06-22 16:30:09 -07003922exit:
3923 if (dirp != NULL) {
3924 Py_BEGIN_ALLOW_THREADS
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003925#ifdef HAVE_FDOPENDIR
Larry Hastings9cf065c2012-06-22 16:30:09 -07003926 if (fd > -1)
3927 rewinddir(dirp);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003928#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003929 closedir(dirp);
3930 Py_END_ALLOW_THREADS
3931 }
3932
Larry Hastings9cf065c2012-06-22 16:30:09 -07003933 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003934} /* end of _posix_listdir */
3935#endif /* which OS */
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003936
Larry Hastings2f936352014-08-05 14:04:04 +10003937
3938/*[clinic input]
3939os.listdir
3940
3941 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
3942
3943Return a list containing the names of the files in the directory.
3944
BNMetricsb9427072018-11-02 15:20:19 +00003945path can be specified as either str, bytes, or a path-like object. If path is bytes,
Larry Hastings2f936352014-08-05 14:04:04 +10003946 the filenames returned will also be bytes; in all other circumstances
3947 the filenames returned will be str.
3948If path is None, uses the path='.'.
3949On some platforms, path may also be specified as an open file descriptor;\
3950 the file descriptor must refer to a directory.
3951 If this functionality is unavailable, using it raises NotImplementedError.
3952
3953The list is in arbitrary order. It does not include the special
3954entries '.' and '..' even if they are present in the directory.
3955
3956
3957[clinic start generated code]*/
3958
Larry Hastings2f936352014-08-05 14:04:04 +10003959static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003960os_listdir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +00003961/*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003962{
Steve Dower60419a72019-06-24 08:42:54 -07003963 if (PySys_Audit("os.listdir", "O",
3964 path->object ? path->object : Py_None) < 0) {
3965 return NULL;
3966 }
Larry Hastings2f936352014-08-05 14:04:04 +10003967#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
3968 return _listdir_windows_no_opendir(path, NULL);
3969#else
3970 return _posix_listdir(path, NULL);
3971#endif
3972}
3973
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00003974#ifdef MS_WINDOWS
Mark Hammondef8b6542001-05-13 08:04:26 +00003975/* A helper function for abspath on win32 */
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003976/*[clinic input]
3977os._getfullpathname
Victor Stinnereb5657a2011-09-30 01:44:27 +02003978
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003979 path: path_t
3980 /
3981
3982[clinic start generated code]*/
3983
3984static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003985os__getfullpathname_impl(PyObject *module, path_t *path)
3986/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003987{
Victor Stinner3939c322019-06-25 15:02:43 +02003988 wchar_t *abspath;
Victor Stinnereb5657a2011-09-30 01:44:27 +02003989
Victor Stinner3939c322019-06-25 15:02:43 +02003990 /* _Py_abspath() is implemented with GetFullPathNameW() on Windows */
3991 if (_Py_abspath(path->wide, &abspath) < 0) {
3992 return win32_error_object("GetFullPathNameW", path->object);
Victor Stinner8c62be82010-05-06 00:08:46 +00003993 }
Victor Stinner3939c322019-06-25 15:02:43 +02003994 if (abspath == NULL) {
3995 return PyErr_NoMemory();
3996 }
3997
3998 PyObject *str = PyUnicode_FromWideChar(abspath, wcslen(abspath));
3999 PyMem_RawFree(abspath);
4000 if (str == NULL) {
4001 return NULL;
4002 }
4003 if (path->narrow) {
4004 Py_SETREF(str, PyUnicode_EncodeFSDefault(str));
4005 }
4006 return str;
Larry Hastings2f936352014-08-05 14:04:04 +10004007}
Brian Curtind40e6f72010-07-08 21:39:08 +00004008
Brian Curtind25aef52011-06-13 15:16:04 -05004009
Larry Hastings2f936352014-08-05 14:04:04 +10004010/*[clinic input]
4011os._getfinalpathname
Brian Curtinf5e76d02010-11-24 13:14:05 +00004012
Steve Dower23ad6d02018-02-22 10:39:10 -08004013 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10004014 /
4015
4016A helper function for samepath on windows.
4017[clinic start generated code]*/
4018
Larry Hastings2f936352014-08-05 14:04:04 +10004019static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08004020os__getfinalpathname_impl(PyObject *module, path_t *path)
4021/*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
Brian Curtind40e6f72010-07-08 21:39:08 +00004022{
4023 HANDLE hFile;
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004024 wchar_t buf[MAXPATHLEN], *target_path = buf;
4025 int buf_size = Py_ARRAY_LENGTH(buf);
Brian Curtind40e6f72010-07-08 21:39:08 +00004026 int result_length;
Larry Hastings2f936352014-08-05 14:04:04 +10004027 PyObject *result;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004028
Steve Dower23ad6d02018-02-22 10:39:10 -08004029 Py_BEGIN_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00004030 hFile = CreateFileW(
Steve Dower23ad6d02018-02-22 10:39:10 -08004031 path->wide,
Brian Curtind40e6f72010-07-08 21:39:08 +00004032 0, /* desired access */
4033 0, /* share mode */
4034 NULL, /* security attributes */
4035 OPEN_EXISTING,
4036 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
4037 FILE_FLAG_BACKUP_SEMANTICS,
4038 NULL);
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004039 Py_END_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004040
Steve Dower23ad6d02018-02-22 10:39:10 -08004041 if (hFile == INVALID_HANDLE_VALUE) {
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004042 return win32_error_object("CreateFileW", path->object);
Steve Dower23ad6d02018-02-22 10:39:10 -08004043 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004044
4045 /* We have a good handle to the target, use it to determine the
4046 target path name. */
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004047 while (1) {
4048 Py_BEGIN_ALLOW_THREADS
4049 result_length = GetFinalPathNameByHandleW(hFile, target_path,
4050 buf_size, VOLUME_NAME_DOS);
4051 Py_END_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00004052
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004053 if (!result_length) {
4054 result = win32_error_object("GetFinalPathNameByHandleW",
4055 path->object);
4056 goto cleanup;
4057 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004058
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004059 if (result_length < buf_size) {
4060 break;
4061 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004062
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004063 wchar_t *tmp;
4064 tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
4065 result_length * sizeof(*tmp));
4066 if (!tmp) {
4067 result = PyErr_NoMemory();
4068 goto cleanup;
4069 }
4070
4071 buf_size = result_length;
4072 target_path = tmp;
Steve Dower23ad6d02018-02-22 10:39:10 -08004073 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004074
Victor Stinner9d3b93b2011-11-22 02:27:30 +01004075 result = PyUnicode_FromWideChar(target_path, result_length);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004076 if (result && path->narrow) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004077 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004078 }
Steve Dower23ad6d02018-02-22 10:39:10 -08004079
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004080cleanup:
4081 if (target_path != buf) {
4082 PyMem_Free(target_path);
4083 }
4084 CloseHandle(hFile);
4085 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10004086}
Brian Curtin62857742010-09-06 17:07:27 +00004087
Tim Golden6b528062013-08-01 12:44:00 +01004088
Larry Hastings2f936352014-08-05 14:04:04 +10004089/*[clinic input]
4090os._getvolumepathname
4091
Steve Dower23ad6d02018-02-22 10:39:10 -08004092 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10004093
4094A helper function for ismount on Win32.
4095[clinic start generated code]*/
4096
Larry Hastings2f936352014-08-05 14:04:04 +10004097static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08004098os__getvolumepathname_impl(PyObject *module, path_t *path)
4099/*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004100{
4101 PyObject *result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004102 wchar_t *mountpath=NULL;
Victor Stinner6edddfa2013-11-24 19:22:57 +01004103 size_t buflen;
Tim Golden6b528062013-08-01 12:44:00 +01004104 BOOL ret;
4105
Tim Golden6b528062013-08-01 12:44:00 +01004106 /* Volume path should be shorter than entire path */
Steve Dower23ad6d02018-02-22 10:39:10 -08004107 buflen = Py_MAX(path->length, MAX_PATH);
Victor Stinner6edddfa2013-11-24 19:22:57 +01004108
Victor Stinner850a18e2017-10-24 16:53:32 -07004109 if (buflen > PY_DWORD_MAX) {
Victor Stinner6edddfa2013-11-24 19:22:57 +01004110 PyErr_SetString(PyExc_OverflowError, "path too long");
4111 return NULL;
4112 }
4113
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004114 mountpath = PyMem_New(wchar_t, buflen);
Tim Golden6b528062013-08-01 12:44:00 +01004115 if (mountpath == NULL)
4116 return PyErr_NoMemory();
4117
4118 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -08004119 ret = GetVolumePathNameW(path->wide, mountpath,
Victor Stinner6edddfa2013-11-24 19:22:57 +01004120 Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
Tim Golden6b528062013-08-01 12:44:00 +01004121 Py_END_ALLOW_THREADS
4122
4123 if (!ret) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004124 result = win32_error_object("_getvolumepathname", path->object);
Tim Golden6b528062013-08-01 12:44:00 +01004125 goto exit;
4126 }
4127 result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
Steve Dower23ad6d02018-02-22 10:39:10 -08004128 if (path->narrow)
4129 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Tim Golden6b528062013-08-01 12:44:00 +01004130
4131exit:
4132 PyMem_Free(mountpath);
4133 return result;
4134}
Tim Golden6b528062013-08-01 12:44:00 +01004135
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004136#endif /* MS_WINDOWS */
Mark Hammondef8b6542001-05-13 08:04:26 +00004137
Larry Hastings2f936352014-08-05 14:04:04 +10004138
4139/*[clinic input]
4140os.mkdir
4141
4142 path : path_t
4143
4144 mode: int = 0o777
4145
4146 *
4147
4148 dir_fd : dir_fd(requires='mkdirat') = None
4149
4150# "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
4151
4152Create a directory.
4153
4154If dir_fd is not None, it should be a file descriptor open to a directory,
4155 and path should be relative; path will then be relative to that directory.
4156dir_fd may not be implemented on your platform.
4157 If it is unavailable, using it will raise a NotImplementedError.
4158
4159The mode argument is ignored on Windows.
4160[clinic start generated code]*/
4161
Larry Hastings2f936352014-08-05 14:04:04 +10004162static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004163os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
4164/*[clinic end generated code: output=a70446903abe821f input=e965f68377e9b1ce]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004165{
4166 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004167
Saiyang Gou7514f4f2020-02-12 23:47:42 -08004168 if (PySys_Audit("os.mkdir", "Oii", path->object, mode,
4169 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4170 return NULL;
4171 }
4172
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004173#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004174 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004175 result = CreateDirectoryW(path->wide, NULL);
Victor Stinner8c62be82010-05-06 00:08:46 +00004176 Py_END_ALLOW_THREADS
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004177
Larry Hastings2f936352014-08-05 14:04:04 +10004178 if (!result)
4179 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004180#else
Victor Stinner8c62be82010-05-06 00:08:46 +00004181 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004182#if HAVE_MKDIRAT
4183 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004184 result = mkdirat(dir_fd, path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004185 else
4186#endif
Erik Bray03eb11f2017-10-27 14:27:06 +02004187#if defined(__WATCOMC__) && !defined(__QNX__)
Larry Hastings2f936352014-08-05 14:04:04 +10004188 result = mkdir(path->narrow);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004189#else
Larry Hastings2f936352014-08-05 14:04:04 +10004190 result = mkdir(path->narrow, mode);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004191#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004192 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004193 if (result < 0)
4194 return path_error(path);
Steve Dowercc16be82016-09-08 10:35:16 -07004195#endif /* MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10004196 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004197}
4198
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004199
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004200/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
4201#if defined(HAVE_SYS_RESOURCE_H)
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004202#include <sys/resource.h>
4203#endif
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004204
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004205
4206#ifdef HAVE_NICE
Larry Hastings2f936352014-08-05 14:04:04 +10004207/*[clinic input]
4208os.nice
4209
4210 increment: int
4211 /
4212
4213Add increment to the priority of process and return the new priority.
4214[clinic start generated code]*/
4215
Larry Hastings2f936352014-08-05 14:04:04 +10004216static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004217os_nice_impl(PyObject *module, int increment)
4218/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004219{
4220 int value;
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004221
Victor Stinner8c62be82010-05-06 00:08:46 +00004222 /* There are two flavours of 'nice': one that returns the new
4223 priority (as required by almost all standards out there) and the
Benjamin Peterson288d1da2017-09-28 22:44:27 -07004224 Linux/FreeBSD one, which returns '0' on success and advices
Victor Stinner8c62be82010-05-06 00:08:46 +00004225 the use of getpriority() to get the new priority.
Tim Peters5aa91602002-01-30 05:46:57 +00004226
Victor Stinner8c62be82010-05-06 00:08:46 +00004227 If we are of the nice family that returns the new priority, we
4228 need to clear errno before the call, and check if errno is filled
4229 before calling posix_error() on a returnvalue of -1, because the
4230 -1 may be the actual new priority! */
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004231
Victor Stinner8c62be82010-05-06 00:08:46 +00004232 errno = 0;
4233 value = nice(increment);
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004234#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
Victor Stinner8c62be82010-05-06 00:08:46 +00004235 if (value == 0)
4236 value = getpriority(PRIO_PROCESS, 0);
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004237#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004238 if (value == -1 && errno != 0)
4239 /* either nice() or getpriority() returned an error */
4240 return posix_error();
4241 return PyLong_FromLong((long) value);
Guido van Rossum775f4da1993-01-09 17:18:52 +00004242}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004243#endif /* HAVE_NICE */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004244
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004245
4246#ifdef HAVE_GETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004247/*[clinic input]
4248os.getpriority
4249
4250 which: int
4251 who: int
4252
4253Return program scheduling priority.
4254[clinic start generated code]*/
4255
Larry Hastings2f936352014-08-05 14:04:04 +10004256static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004257os_getpriority_impl(PyObject *module, int which, int who)
4258/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004259{
4260 int retval;
4261
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004262 errno = 0;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004263 retval = getpriority(which, who);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004264 if (errno != 0)
4265 return posix_error();
4266 return PyLong_FromLong((long)retval);
4267}
4268#endif /* HAVE_GETPRIORITY */
4269
4270
4271#ifdef HAVE_SETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004272/*[clinic input]
4273os.setpriority
4274
4275 which: int
4276 who: int
4277 priority: int
4278
4279Set program scheduling priority.
4280[clinic start generated code]*/
4281
Larry Hastings2f936352014-08-05 14:04:04 +10004282static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004283os_setpriority_impl(PyObject *module, int which, int who, int priority)
4284/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004285{
4286 int retval;
4287
4288 retval = setpriority(which, who, priority);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004289 if (retval == -1)
4290 return posix_error();
4291 Py_RETURN_NONE;
4292}
4293#endif /* HAVE_SETPRIORITY */
4294
4295
Barry Warsaw53699e91996-12-10 23:23:01 +00004296static PyObject *
Larry Hastings2f936352014-08-05 14:04:04 +10004297internal_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 +00004298{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004299 const char *function_name = is_replace ? "replace" : "rename";
Larry Hastings9cf065c2012-06-22 16:30:09 -07004300 int dir_fd_specified;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004301
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004302#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004303 BOOL result;
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004304 int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004305#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004306 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004307#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004308
Larry Hastings9cf065c2012-06-22 16:30:09 -07004309 dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
4310 (dst_dir_fd != DEFAULT_DIR_FD);
4311#ifndef HAVE_RENAMEAT
4312 if (dir_fd_specified) {
4313 argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10004314 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004315 }
4316#endif
4317
Saiyang Gou7514f4f2020-02-12 23:47:42 -08004318 if (PySys_Audit("os.rename", "OOii", src->object, dst->object,
4319 src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
4320 dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
4321 return NULL;
4322 }
4323
Larry Hastings9cf065c2012-06-22 16:30:09 -07004324#ifdef MS_WINDOWS
4325 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004326 result = MoveFileExW(src->wide, dst->wide, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004327 Py_END_ALLOW_THREADS
4328
Larry Hastings2f936352014-08-05 14:04:04 +10004329 if (!result)
4330 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004331
4332#else
Steve Dowercc16be82016-09-08 10:35:16 -07004333 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
4334 PyErr_Format(PyExc_ValueError,
4335 "%s: src and dst must be the same type", function_name);
4336 return NULL;
4337 }
4338
Larry Hastings9cf065c2012-06-22 16:30:09 -07004339 Py_BEGIN_ALLOW_THREADS
4340#ifdef HAVE_RENAMEAT
4341 if (dir_fd_specified)
Larry Hastings2f936352014-08-05 14:04:04 +10004342 result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004343 else
4344#endif
Steve Dowercc16be82016-09-08 10:35:16 -07004345 result = rename(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004346 Py_END_ALLOW_THREADS
4347
Larry Hastings2f936352014-08-05 14:04:04 +10004348 if (result)
4349 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004350#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004351 Py_RETURN_NONE;
4352}
Larry Hastings9cf065c2012-06-22 16:30:09 -07004353
Larry Hastings2f936352014-08-05 14:04:04 +10004354
4355/*[clinic input]
4356os.rename
4357
4358 src : path_t
4359 dst : path_t
4360 *
4361 src_dir_fd : dir_fd = None
4362 dst_dir_fd : dir_fd = None
4363
4364Rename a file or directory.
4365
4366If either src_dir_fd or dst_dir_fd is not None, it should be a file
4367 descriptor open to a directory, and the respective path string (src or dst)
4368 should be relative; the path will then be relative to that directory.
4369src_dir_fd and dst_dir_fd, may not be implemented on your platform.
4370 If they are unavailable, using them will raise a NotImplementedError.
4371[clinic start generated code]*/
4372
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004373static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004374os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04004375 int dst_dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004376/*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004377{
Larry Hastings2f936352014-08-05 14:04:04 +10004378 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004379}
4380
Larry Hastings2f936352014-08-05 14:04:04 +10004381
4382/*[clinic input]
4383os.replace = os.rename
4384
4385Rename a file or directory, overwriting the destination.
4386
4387If either src_dir_fd or dst_dir_fd is not None, it should be a file
4388 descriptor open to a directory, and the respective path string (src or dst)
4389 should be relative; the path will then be relative to that directory.
4390src_dir_fd and dst_dir_fd, may not be implemented on your platform.
Anthony Sottile73d60022019-02-12 23:15:54 -05004391 If they are unavailable, using them will raise a NotImplementedError.
Larry Hastings2f936352014-08-05 14:04:04 +10004392[clinic start generated code]*/
4393
Larry Hastings2f936352014-08-05 14:04:04 +10004394static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004395os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
4396 int dst_dir_fd)
Anthony Sottile73d60022019-02-12 23:15:54 -05004397/*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004398{
4399 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
4400}
4401
4402
4403/*[clinic input]
4404os.rmdir
4405
4406 path: path_t
4407 *
4408 dir_fd: dir_fd(requires='unlinkat') = None
4409
4410Remove a directory.
4411
4412If dir_fd is not None, it should be a file descriptor open to a directory,
4413 and path should be relative; path will then be relative to that directory.
4414dir_fd may not be implemented on your platform.
4415 If it is unavailable, using it will raise a NotImplementedError.
4416[clinic start generated code]*/
4417
Larry Hastings2f936352014-08-05 14:04:04 +10004418static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004419os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
4420/*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004421{
4422 int result;
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004423
Saiyang Gou7514f4f2020-02-12 23:47:42 -08004424 if (PySys_Audit("os.rmdir", "Oi", path->object,
4425 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4426 return NULL;
4427 }
4428
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004429 Py_BEGIN_ALLOW_THREADS
4430#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004431 /* Windows, success=1, UNIX, success=0 */
4432 result = !RemoveDirectoryW(path->wide);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004433#else
4434#ifdef HAVE_UNLINKAT
4435 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004436 result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004437 else
4438#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004439 result = rmdir(path->narrow);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004440#endif
4441 Py_END_ALLOW_THREADS
4442
Larry Hastings2f936352014-08-05 14:04:04 +10004443 if (result)
4444 return path_error(path);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004445
Larry Hastings2f936352014-08-05 14:04:04 +10004446 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004447}
4448
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004449
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004450#ifdef HAVE_SYSTEM
Larry Hastings2f936352014-08-05 14:04:04 +10004451#ifdef MS_WINDOWS
4452/*[clinic input]
4453os.system -> long
4454
4455 command: Py_UNICODE
4456
4457Execute the command in a subshell.
4458[clinic start generated code]*/
4459
Larry Hastings2f936352014-08-05 14:04:04 +10004460static long
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02004461os_system_impl(PyObject *module, const Py_UNICODE *command)
4462/*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004463{
4464 long result;
Steve Dowerb82e17e2019-05-23 08:45:22 -07004465
Steve Dowerfbe3c762019-10-18 00:52:15 -07004466 if (PySys_Audit("os.system", "(u)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004467 return -1;
4468 }
4469
Victor Stinner8c62be82010-05-06 00:08:46 +00004470 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08004471 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10004472 result = _wsystem(command);
Steve Dowerc3630612016-11-19 18:41:16 -08004473 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00004474 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004475 return result;
4476}
4477#else /* MS_WINDOWS */
4478/*[clinic input]
4479os.system -> long
4480
4481 command: FSConverter
4482
4483Execute the command in a subshell.
4484[clinic start generated code]*/
4485
Larry Hastings2f936352014-08-05 14:04:04 +10004486static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004487os_system_impl(PyObject *module, PyObject *command)
4488/*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004489{
4490 long result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004491 const char *bytes = PyBytes_AsString(command);
Steve Dowerb82e17e2019-05-23 08:45:22 -07004492
Steve Dowerfbe3c762019-10-18 00:52:15 -07004493 if (PySys_Audit("os.system", "(O)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004494 return -1;
4495 }
4496
Larry Hastings2f936352014-08-05 14:04:04 +10004497 Py_BEGIN_ALLOW_THREADS
4498 result = system(bytes);
4499 Py_END_ALLOW_THREADS
4500 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004501}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004502#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004503#endif /* HAVE_SYSTEM */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004504
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004505
Larry Hastings2f936352014-08-05 14:04:04 +10004506/*[clinic input]
4507os.umask
4508
4509 mask: int
4510 /
4511
4512Set the current numeric umask and return the previous umask.
4513[clinic start generated code]*/
4514
Larry Hastings2f936352014-08-05 14:04:04 +10004515static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004516os_umask_impl(PyObject *module, int mask)
4517/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004518{
4519 int i = (int)umask(mask);
Victor Stinner8c62be82010-05-06 00:08:46 +00004520 if (i < 0)
4521 return posix_error();
4522 return PyLong_FromLong((long)i);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004523}
4524
Brian Curtind40e6f72010-07-08 21:39:08 +00004525#ifdef MS_WINDOWS
4526
4527/* override the default DeleteFileW behavior so that directory
4528symlinks can be removed with this function, the same as with
4529Unix symlinks */
4530BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
4531{
4532 WIN32_FILE_ATTRIBUTE_DATA info;
4533 WIN32_FIND_DATAW find_data;
4534 HANDLE find_data_handle;
4535 int is_directory = 0;
4536 int is_link = 0;
4537
4538 if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
4539 is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004540
Brian Curtind40e6f72010-07-08 21:39:08 +00004541 /* Get WIN32_FIND_DATA structure for the path to determine if
4542 it is a symlink */
4543 if(is_directory &&
4544 info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
4545 find_data_handle = FindFirstFileW(lpFileName, &find_data);
4546
4547 if(find_data_handle != INVALID_HANDLE_VALUE) {
Tim Golden0321cf22014-05-05 19:46:17 +01004548 /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
4549 IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
4550 is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
4551 find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
Brian Curtind40e6f72010-07-08 21:39:08 +00004552 FindClose(find_data_handle);
4553 }
4554 }
4555 }
4556
4557 if (is_directory && is_link)
4558 return RemoveDirectoryW(lpFileName);
4559
4560 return DeleteFileW(lpFileName);
4561}
4562#endif /* MS_WINDOWS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004563
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004564
Larry Hastings2f936352014-08-05 14:04:04 +10004565/*[clinic input]
4566os.unlink
4567
4568 path: path_t
4569 *
4570 dir_fd: dir_fd(requires='unlinkat')=None
4571
4572Remove a file (same as remove()).
4573
4574If dir_fd is not None, it should be a file descriptor open to a directory,
4575 and path should be relative; path will then be relative to that directory.
4576dir_fd may not be implemented on your platform.
4577 If it is unavailable, using it will raise a NotImplementedError.
4578
4579[clinic start generated code]*/
4580
Larry Hastings2f936352014-08-05 14:04:04 +10004581static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004582os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
4583/*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004584{
4585 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004586
Saiyang Gou7514f4f2020-02-12 23:47:42 -08004587 if (PySys_Audit("os.remove", "Oi", path->object,
4588 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4589 return NULL;
4590 }
4591
Larry Hastings9cf065c2012-06-22 16:30:09 -07004592 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04004593 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004594#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004595 /* Windows, success=1, UNIX, success=0 */
4596 result = !Py_DeleteFileW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004597#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004598#ifdef HAVE_UNLINKAT
4599 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004600 result = unlinkat(dir_fd, path->narrow, 0);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004601 else
4602#endif /* HAVE_UNLINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10004603 result = unlink(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004604#endif
Steve Dower8fc89802015-04-12 00:26:27 -04004605 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004606 Py_END_ALLOW_THREADS
4607
Larry Hastings2f936352014-08-05 14:04:04 +10004608 if (result)
4609 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004610
Larry Hastings2f936352014-08-05 14:04:04 +10004611 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004612}
4613
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004614
Larry Hastings2f936352014-08-05 14:04:04 +10004615/*[clinic input]
4616os.remove = os.unlink
4617
4618Remove a file (same as unlink()).
4619
4620If dir_fd is not None, it should be a file descriptor open to a directory,
4621 and path should be relative; path will then be relative to that directory.
4622dir_fd may not be implemented on your platform.
4623 If it is unavailable, using it will raise a NotImplementedError.
4624[clinic start generated code]*/
4625
Larry Hastings2f936352014-08-05 14:04:04 +10004626static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004627os_remove_impl(PyObject *module, path_t *path, int dir_fd)
4628/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004629{
4630 return os_unlink_impl(module, path, dir_fd);
4631}
4632
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004633
Larry Hastings605a62d2012-06-24 04:33:36 -07004634static PyStructSequence_Field uname_result_fields[] = {
4635 {"sysname", "operating system name"},
4636 {"nodename", "name of machine on network (implementation-defined)"},
4637 {"release", "operating system release"},
4638 {"version", "operating system version"},
4639 {"machine", "hardware identifier"},
4640 {NULL}
4641};
4642
4643PyDoc_STRVAR(uname_result__doc__,
4644"uname_result: Result from os.uname().\n\n\
4645This object may be accessed either as a tuple of\n\
4646 (sysname, nodename, release, version, machine),\n\
4647or via the attributes sysname, nodename, release, version, and machine.\n\
4648\n\
4649See os.uname for more information.");
4650
4651static PyStructSequence_Desc uname_result_desc = {
Eddie Elizondob3966632019-11-05 07:16:14 -08004652 MODNAME ".uname_result", /* name */
Larry Hastings605a62d2012-06-24 04:33:36 -07004653 uname_result__doc__, /* doc */
4654 uname_result_fields,
4655 5
4656};
4657
Larry Hastings605a62d2012-06-24 04:33:36 -07004658#ifdef HAVE_UNAME
Larry Hastings2f936352014-08-05 14:04:04 +10004659/*[clinic input]
4660os.uname
4661
4662Return an object identifying the current operating system.
4663
4664The object behaves like a named tuple with the following fields:
4665 (sysname, nodename, release, version, machine)
4666
4667[clinic start generated code]*/
4668
Larry Hastings2f936352014-08-05 14:04:04 +10004669static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004670os_uname_impl(PyObject *module)
4671/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004672{
Victor Stinner8c62be82010-05-06 00:08:46 +00004673 struct utsname u;
4674 int res;
Larry Hastings605a62d2012-06-24 04:33:36 -07004675 PyObject *value;
Neal Norwitze241ce82003-02-17 18:17:05 +00004676
Victor Stinner8c62be82010-05-06 00:08:46 +00004677 Py_BEGIN_ALLOW_THREADS
4678 res = uname(&u);
4679 Py_END_ALLOW_THREADS
4680 if (res < 0)
4681 return posix_error();
Larry Hastings605a62d2012-06-24 04:33:36 -07004682
Hai Shif707d942020-03-16 21:15:01 +08004683 PyObject *UnameResultType = get_posix_state(module)->UnameResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -08004684 value = PyStructSequence_New((PyTypeObject *)UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07004685 if (value == NULL)
4686 return NULL;
4687
4688#define SET(i, field) \
4689 { \
Victor Stinnera534fc42013-06-03 22:07:27 +02004690 PyObject *o = PyUnicode_DecodeFSDefault(field); \
Larry Hastings605a62d2012-06-24 04:33:36 -07004691 if (!o) { \
4692 Py_DECREF(value); \
4693 return NULL; \
4694 } \
4695 PyStructSequence_SET_ITEM(value, i, o); \
4696 } \
4697
4698 SET(0, u.sysname);
4699 SET(1, u.nodename);
4700 SET(2, u.release);
4701 SET(3, u.version);
4702 SET(4, u.machine);
4703
4704#undef SET
4705
4706 return value;
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004707}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004708#endif /* HAVE_UNAME */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004709
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004710
Larry Hastings9cf065c2012-06-22 16:30:09 -07004711
4712typedef struct {
4713 int now;
4714 time_t atime_s;
4715 long atime_ns;
4716 time_t mtime_s;
4717 long mtime_ns;
4718} utime_t;
4719
4720/*
Victor Stinner484df002014-10-09 13:52:31 +02004721 * these macros assume that "ut" is a pointer to a utime_t
Larry Hastings9cf065c2012-06-22 16:30:09 -07004722 * they also intentionally leak the declaration of a pointer named "time"
4723 */
4724#define UTIME_TO_TIMESPEC \
4725 struct timespec ts[2]; \
4726 struct timespec *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004727 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004728 time = NULL; \
4729 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004730 ts[0].tv_sec = ut->atime_s; \
4731 ts[0].tv_nsec = ut->atime_ns; \
4732 ts[1].tv_sec = ut->mtime_s; \
4733 ts[1].tv_nsec = ut->mtime_ns; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004734 time = ts; \
4735 } \
4736
4737#define UTIME_TO_TIMEVAL \
4738 struct timeval tv[2]; \
4739 struct timeval *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004740 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004741 time = NULL; \
4742 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004743 tv[0].tv_sec = ut->atime_s; \
4744 tv[0].tv_usec = ut->atime_ns / 1000; \
4745 tv[1].tv_sec = ut->mtime_s; \
4746 tv[1].tv_usec = ut->mtime_ns / 1000; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004747 time = tv; \
4748 } \
4749
4750#define UTIME_TO_UTIMBUF \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004751 struct utimbuf u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004752 struct utimbuf *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004753 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004754 time = NULL; \
4755 else { \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004756 u.actime = ut->atime_s; \
4757 u.modtime = ut->mtime_s; \
4758 time = &u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004759 }
4760
4761#define UTIME_TO_TIME_T \
4762 time_t timet[2]; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004763 time_t *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004764 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004765 time = NULL; \
4766 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004767 timet[0] = ut->atime_s; \
4768 timet[1] = ut->mtime_s; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004769 time = timet; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004770 } \
4771
4772
Victor Stinner528a9ab2015-09-03 21:30:26 +02004773#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004774
4775static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004776utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004777{
4778#ifdef HAVE_UTIMENSAT
4779 int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
4780 UTIME_TO_TIMESPEC;
4781 return utimensat(dir_fd, path, time, flags);
4782#elif defined(HAVE_FUTIMESAT)
4783 UTIME_TO_TIMEVAL;
4784 /*
4785 * follow_symlinks will never be false here;
4786 * we only allow !follow_symlinks and dir_fd together
4787 * if we have utimensat()
4788 */
4789 assert(follow_symlinks);
4790 return futimesat(dir_fd, path, time);
4791#endif
4792}
4793
Larry Hastings2f936352014-08-05 14:04:04 +10004794 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
4795#else
4796 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings9cf065c2012-06-22 16:30:09 -07004797#endif
4798
Victor Stinner528a9ab2015-09-03 21:30:26 +02004799#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004800
4801static int
Victor Stinner484df002014-10-09 13:52:31 +02004802utime_fd(utime_t *ut, int fd)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004803{
4804#ifdef HAVE_FUTIMENS
4805 UTIME_TO_TIMESPEC;
4806 return futimens(fd, time);
4807#else
4808 UTIME_TO_TIMEVAL;
4809 return futimes(fd, time);
4810#endif
4811}
4812
Larry Hastings2f936352014-08-05 14:04:04 +10004813 #define PATH_UTIME_HAVE_FD 1
4814#else
4815 #define PATH_UTIME_HAVE_FD 0
Larry Hastings9cf065c2012-06-22 16:30:09 -07004816#endif
4817
Victor Stinner5ebae872015-09-22 01:29:33 +02004818#if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
4819# define UTIME_HAVE_NOFOLLOW_SYMLINKS
4820#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004821
Victor Stinner4552ced2015-09-21 22:37:15 +02004822#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004823
4824static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004825utime_nofollow_symlinks(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004826{
4827#ifdef HAVE_UTIMENSAT
4828 UTIME_TO_TIMESPEC;
4829 return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
4830#else
4831 UTIME_TO_TIMEVAL;
4832 return lutimes(path, time);
4833#endif
4834}
4835
4836#endif
4837
4838#ifndef MS_WINDOWS
4839
4840static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004841utime_default(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004842{
4843#ifdef HAVE_UTIMENSAT
4844 UTIME_TO_TIMESPEC;
4845 return utimensat(DEFAULT_DIR_FD, path, time, 0);
4846#elif defined(HAVE_UTIMES)
4847 UTIME_TO_TIMEVAL;
4848 return utimes(path, time);
4849#elif defined(HAVE_UTIME_H)
4850 UTIME_TO_UTIMBUF;
4851 return utime(path, time);
4852#else
4853 UTIME_TO_TIME_T;
4854 return utime(path, time);
4855#endif
4856}
4857
4858#endif
4859
Larry Hastings76ad59b2012-05-03 00:30:07 -07004860static int
4861split_py_long_to_s_and_ns(PyObject *py_long, time_t *s, long *ns)
4862{
4863 int result = 0;
Benjamin Petersonfbd85a02012-05-04 11:06:09 -04004864 PyObject *divmod;
Eddie Elizondob3966632019-11-05 07:16:14 -08004865 divmod = PyNumber_Divmod(py_long, _posixstate_global->billion);
Larry Hastings76ad59b2012-05-03 00:30:07 -07004866 if (!divmod)
4867 goto exit;
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004868 if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
4869 PyErr_Format(PyExc_TypeError,
4870 "%.200s.__divmod__() must return a 2-tuple, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -08004871 _PyType_Name(Py_TYPE(py_long)), _PyType_Name(Py_TYPE(divmod)));
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004872 goto exit;
4873 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004874 *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
4875 if ((*s == -1) && PyErr_Occurred())
4876 goto exit;
4877 *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
Benjamin Peterson35a8f0d2012-05-04 01:10:59 -04004878 if ((*ns == -1) && PyErr_Occurred())
Larry Hastings76ad59b2012-05-03 00:30:07 -07004879 goto exit;
4880
4881 result = 1;
4882exit:
4883 Py_XDECREF(divmod);
4884 return result;
4885}
4886
Larry Hastings2f936352014-08-05 14:04:04 +10004887
4888/*[clinic input]
4889os.utime
4890
4891 path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004892 times: object = None
Larry Hastings2f936352014-08-05 14:04:04 +10004893 *
4894 ns: object = NULL
4895 dir_fd: dir_fd(requires='futimensat') = None
4896 follow_symlinks: bool=True
4897
Martin Panter0ff89092015-09-09 01:56:53 +00004898# "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
Larry Hastings2f936352014-08-05 14:04:04 +10004899
4900Set the access and modified time of path.
4901
4902path may always be specified as a string.
4903On some platforms, path may also be specified as an open file descriptor.
4904 If this functionality is unavailable, using it raises an exception.
4905
4906If times is not None, it must be a tuple (atime, mtime);
4907 atime and mtime should be expressed as float seconds since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004908If ns is specified, it must be a tuple (atime_ns, mtime_ns);
Larry Hastings2f936352014-08-05 14:04:04 +10004909 atime_ns and mtime_ns should be expressed as integer nanoseconds
4910 since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004911If times is None and ns is unspecified, utime uses the current time.
Larry Hastings2f936352014-08-05 14:04:04 +10004912Specifying tuples for both times and ns is an error.
4913
4914If dir_fd is not None, it should be a file descriptor open to a directory,
4915 and path should be relative; path will then be relative to that directory.
4916If follow_symlinks is False, and the last element of the path is a symbolic
4917 link, utime will modify the symbolic link itself instead of the file the
4918 link points to.
4919It is an error to use dir_fd or follow_symlinks when specifying path
4920 as an open file descriptor.
4921dir_fd and follow_symlinks may not be available on your platform.
4922 If they are unavailable, using them will raise a NotImplementedError.
4923
4924[clinic start generated code]*/
4925
Larry Hastings2f936352014-08-05 14:04:04 +10004926static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004927os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
4928 int dir_fd, int follow_symlinks)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004929/*[clinic end generated code: output=cfcac69d027b82cf input=2fbd62a2f228f8f4]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004930{
Larry Hastings9cf065c2012-06-22 16:30:09 -07004931#ifdef MS_WINDOWS
4932 HANDLE hFile;
4933 FILETIME atime, mtime;
4934#else
4935 int result;
4936#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004937
Larry Hastings2f936352014-08-05 14:04:04 +10004938 utime_t utime;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004939
Christian Heimesb3c87242013-08-01 00:08:16 +02004940 memset(&utime, 0, sizeof(utime_t));
Larry Hastings76ad59b2012-05-03 00:30:07 -07004941
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004942 if (times != Py_None && ns) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004943 PyErr_SetString(PyExc_ValueError,
4944 "utime: you may specify either 'times'"
4945 " or 'ns' but not both");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004946 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004947 }
4948
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004949 if (times != Py_None) {
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004950 time_t a_sec, m_sec;
4951 long a_nsec, m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004952 if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004953 PyErr_SetString(PyExc_TypeError,
4954 "utime: 'times' must be either"
4955 " a tuple of two ints or None");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004956 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004957 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004958 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004959 if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004960 &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004961 _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004962 &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004963 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004964 }
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004965 utime.atime_s = a_sec;
4966 utime.atime_ns = a_nsec;
4967 utime.mtime_s = m_sec;
4968 utime.mtime_ns = m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004969 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004970 else if (ns) {
Larry Hastings76ad59b2012-05-03 00:30:07 -07004971 if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004972 PyErr_SetString(PyExc_TypeError,
4973 "utime: 'ns' must be a tuple of two ints");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004974 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004975 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004976 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004977 if (!split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 0),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004978 &utime.atime_s, &utime.atime_ns) ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004979 !split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 1),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004980 &utime.mtime_s, &utime.mtime_ns)) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004981 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004982 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004983 }
4984 else {
4985 /* times and ns are both None/unspecified. use "now". */
4986 utime.now = 1;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004987 }
4988
Victor Stinner4552ced2015-09-21 22:37:15 +02004989#if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004990 if (follow_symlinks_specified("utime", follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004991 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004992#endif
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004993
Larry Hastings2f936352014-08-05 14:04:04 +10004994 if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
4995 dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
4996 fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004997 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004998
Larry Hastings9cf065c2012-06-22 16:30:09 -07004999#if !defined(HAVE_UTIMENSAT)
5000 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
Georg Brandl969288e2012-06-26 09:25:44 +02005001 PyErr_SetString(PyExc_ValueError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005002 "utime: cannot use dir_fd and follow_symlinks "
5003 "together on this platform");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005004 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07005005 }
5006#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07005007
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005008 if (PySys_Audit("os.utime", "OOOi", path->object, times, ns ? ns : Py_None,
5009 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
5010 return NULL;
5011 }
5012
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00005013#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07005014 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07005015 hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
5016 NULL, OPEN_EXISTING,
5017 FILE_FLAG_BACKUP_SEMANTICS, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005018 Py_END_ALLOW_THREADS
5019 if (hFile == INVALID_HANDLE_VALUE) {
Larry Hastings2f936352014-08-05 14:04:04 +10005020 path_error(path);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005021 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07005022 }
5023
Larry Hastings9cf065c2012-06-22 16:30:09 -07005024 if (utime.now) {
Antoine Pitrou91a7af32013-11-23 15:23:26 +01005025 GetSystemTimeAsFileTime(&mtime);
5026 atime = mtime;
Victor Stinner8c62be82010-05-06 00:08:46 +00005027 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005028 else {
Steve Dowerbf1f3762015-02-21 15:26:02 -08005029 _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
5030 _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
Victor Stinner8c62be82010-05-06 00:08:46 +00005031 }
5032 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
5033 /* Avoid putting the file name into the error here,
5034 as that may confuse the user into believing that
5035 something is wrong with the file, when it also
5036 could be the time stamp that gives a problem. */
Victor Stinnerb024e842012-10-31 22:24:06 +01005037 PyErr_SetFromWindowsErr(0);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005038 CloseHandle(hFile);
5039 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00005040 }
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005041 CloseHandle(hFile);
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00005042#else /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07005043 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00005044
Victor Stinner4552ced2015-09-21 22:37:15 +02005045#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07005046 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10005047 result = utime_nofollow_symlinks(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005048 else
Larry Hastings9e3e70b2011-09-08 19:29:07 -07005049#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07005050
Victor Stinner528a9ab2015-09-03 21:30:26 +02005051#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07005052 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10005053 result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005054 else
5055#endif
5056
Victor Stinner528a9ab2015-09-03 21:30:26 +02005057#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings2f936352014-08-05 14:04:04 +10005058 if (path->fd != -1)
5059 result = utime_fd(&utime, path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005060 else
5061#endif
5062
Larry Hastings2f936352014-08-05 14:04:04 +10005063 result = utime_default(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005064
5065 Py_END_ALLOW_THREADS
5066
5067 if (result < 0) {
5068 /* see previous comment about not putting filename in error here */
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005069 posix_error();
5070 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00005071 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07005072
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00005073#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07005074
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005075 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005076}
5077
Guido van Rossum3b066191991-06-04 19:40:25 +00005078/* Process operations */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005079
Larry Hastings2f936352014-08-05 14:04:04 +10005080
5081/*[clinic input]
5082os._exit
5083
5084 status: int
5085
5086Exit to the system with specified status, without normal exit processing.
5087[clinic start generated code]*/
5088
Larry Hastings2f936352014-08-05 14:04:04 +10005089static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005090os__exit_impl(PyObject *module, int status)
5091/*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005092{
5093 _exit(status);
Victor Stinner8c62be82010-05-06 00:08:46 +00005094 return NULL; /* Make gcc -Wall happy */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005095}
5096
Steve Dowercc16be82016-09-08 10:35:16 -07005097#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5098#define EXECV_CHAR wchar_t
5099#else
5100#define EXECV_CHAR char
5101#endif
5102
pxinwrf2d7ac72019-05-21 18:46:37 +08005103#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005104static void
Steve Dowercc16be82016-09-08 10:35:16 -07005105free_string_array(EXECV_CHAR **array, Py_ssize_t count)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005106{
Victor Stinner8c62be82010-05-06 00:08:46 +00005107 Py_ssize_t i;
5108 for (i = 0; i < count; i++)
5109 PyMem_Free(array[i]);
5110 PyMem_DEL(array);
Martin v. Löwis114619e2002-10-07 06:44:21 +00005111}
Martin v. Löwis011e8422009-05-05 04:43:17 +00005112
Berker Peksag81816462016-09-15 20:19:47 +03005113static int
5114fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
Martin v. Löwis011e8422009-05-05 04:43:17 +00005115{
Victor Stinner8c62be82010-05-06 00:08:46 +00005116 Py_ssize_t size;
Berker Peksag81816462016-09-15 20:19:47 +03005117 PyObject *ub;
5118 int result = 0;
Steve Dowercc16be82016-09-08 10:35:16 -07005119#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
Berker Peksag81816462016-09-15 20:19:47 +03005120 if (!PyUnicode_FSDecoder(o, &ub))
Steve Dowercc16be82016-09-08 10:35:16 -07005121 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005122 *out = PyUnicode_AsWideCharString(ub, &size);
5123 if (*out)
5124 result = 1;
Steve Dowercc16be82016-09-08 10:35:16 -07005125#else
Berker Peksag81816462016-09-15 20:19:47 +03005126 if (!PyUnicode_FSConverter(o, &ub))
Victor Stinner8c62be82010-05-06 00:08:46 +00005127 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005128 size = PyBytes_GET_SIZE(ub);
5129 *out = PyMem_Malloc(size + 1);
5130 if (*out) {
5131 memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
5132 result = 1;
5133 } else
Victor Stinner50abf222013-11-07 23:56:10 +01005134 PyErr_NoMemory();
Steve Dowercc16be82016-09-08 10:35:16 -07005135#endif
Berker Peksag81816462016-09-15 20:19:47 +03005136 Py_DECREF(ub);
5137 return result;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005138}
Martin v. Löwis114619e2002-10-07 06:44:21 +00005139#endif
5140
pxinwrf2d7ac72019-05-21 18:46:37 +08005141#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
Steve Dowercc16be82016-09-08 10:35:16 -07005142static EXECV_CHAR**
Victor Stinner13bb71c2010-04-23 21:41:56 +00005143parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
5144{
Victor Stinner8c62be82010-05-06 00:08:46 +00005145 Py_ssize_t i, pos, envc;
5146 PyObject *keys=NULL, *vals=NULL;
Berker Peksag81816462016-09-15 20:19:47 +03005147 PyObject *key, *val, *key2, *val2, *keyval;
Steve Dowercc16be82016-09-08 10:35:16 -07005148 EXECV_CHAR **envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005149
Victor Stinner8c62be82010-05-06 00:08:46 +00005150 i = PyMapping_Size(env);
5151 if (i < 0)
5152 return NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07005153 envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005154 if (envlist == NULL) {
5155 PyErr_NoMemory();
5156 return NULL;
5157 }
5158 envc = 0;
5159 keys = PyMapping_Keys(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005160 if (!keys)
5161 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00005162 vals = PyMapping_Values(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005163 if (!vals)
Victor Stinner8c62be82010-05-06 00:08:46 +00005164 goto error;
5165 if (!PyList_Check(keys) || !PyList_Check(vals)) {
5166 PyErr_Format(PyExc_TypeError,
5167 "env.keys() or env.values() is not a list");
5168 goto error;
5169 }
Victor Stinner13bb71c2010-04-23 21:41:56 +00005170
Victor Stinner8c62be82010-05-06 00:08:46 +00005171 for (pos = 0; pos < i; pos++) {
5172 key = PyList_GetItem(keys, pos);
5173 val = PyList_GetItem(vals, pos);
5174 if (!key || !val)
5175 goto error;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005176
Berker Peksag81816462016-09-15 20:19:47 +03005177#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5178 if (!PyUnicode_FSDecoder(key, &key2))
5179 goto error;
5180 if (!PyUnicode_FSDecoder(val, &val2)) {
5181 Py_DECREF(key2);
5182 goto error;
5183 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005184 /* Search from index 1 because on Windows starting '=' is allowed for
5185 defining hidden environment variables. */
5186 if (PyUnicode_GET_LENGTH(key2) == 0 ||
5187 PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
5188 {
5189 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005190 Py_DECREF(key2);
5191 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005192 goto error;
5193 }
Berker Peksag81816462016-09-15 20:19:47 +03005194 keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
5195#else
5196 if (!PyUnicode_FSConverter(key, &key2))
5197 goto error;
5198 if (!PyUnicode_FSConverter(val, &val2)) {
5199 Py_DECREF(key2);
5200 goto error;
5201 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005202 if (PyBytes_GET_SIZE(key2) == 0 ||
5203 strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
5204 {
5205 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005206 Py_DECREF(key2);
5207 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005208 goto error;
5209 }
Berker Peksag81816462016-09-15 20:19:47 +03005210 keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
5211 PyBytes_AS_STRING(val2));
5212#endif
5213 Py_DECREF(key2);
5214 Py_DECREF(val2);
Steve Dowercc16be82016-09-08 10:35:16 -07005215 if (!keyval)
Victor Stinner8c62be82010-05-06 00:08:46 +00005216 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -07005217
5218 if (!fsconvert_strdup(keyval, &envlist[envc++])) {
5219 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005220 goto error;
5221 }
Berker Peksag81816462016-09-15 20:19:47 +03005222
Steve Dowercc16be82016-09-08 10:35:16 -07005223 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005224 }
5225 Py_DECREF(vals);
5226 Py_DECREF(keys);
Victor Stinner13bb71c2010-04-23 21:41:56 +00005227
Victor Stinner8c62be82010-05-06 00:08:46 +00005228 envlist[envc] = 0;
5229 *envc_ptr = envc;
5230 return envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005231
5232error:
Victor Stinner8c62be82010-05-06 00:08:46 +00005233 Py_XDECREF(keys);
5234 Py_XDECREF(vals);
Steve Dowercc16be82016-09-08 10:35:16 -07005235 free_string_array(envlist, envc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005236 return NULL;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005237}
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005238
Steve Dowercc16be82016-09-08 10:35:16 -07005239static EXECV_CHAR**
Ross Lagerwall7807c352011-03-17 20:20:30 +02005240parse_arglist(PyObject* argv, Py_ssize_t *argc)
5241{
5242 int i;
Steve Dowercc16be82016-09-08 10:35:16 -07005243 EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005244 if (argvlist == NULL) {
5245 PyErr_NoMemory();
5246 return NULL;
5247 }
5248 for (i = 0; i < *argc; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005249 PyObject* item = PySequence_ITEM(argv, i);
5250 if (item == NULL)
5251 goto fail;
5252 if (!fsconvert_strdup(item, &argvlist[i])) {
5253 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005254 goto fail;
5255 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005256 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005257 }
5258 argvlist[*argc] = NULL;
5259 return argvlist;
5260fail:
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005261 *argc = i;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005262 free_string_array(argvlist, *argc);
5263 return NULL;
5264}
Steve Dowercc16be82016-09-08 10:35:16 -07005265
Ross Lagerwall7807c352011-03-17 20:20:30 +02005266#endif
5267
Larry Hastings2f936352014-08-05 14:04:04 +10005268
Ross Lagerwall7807c352011-03-17 20:20:30 +02005269#ifdef HAVE_EXECV
Larry Hastings2f936352014-08-05 14:04:04 +10005270/*[clinic input]
5271os.execv
5272
Steve Dowercc16be82016-09-08 10:35:16 -07005273 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005274 Path of executable file.
5275 argv: object
5276 Tuple or list of strings.
5277 /
5278
5279Execute an executable path with arguments, replacing current process.
5280[clinic start generated code]*/
5281
Larry Hastings2f936352014-08-05 14:04:04 +10005282static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005283os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
5284/*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005285{
Steve Dowercc16be82016-09-08 10:35:16 -07005286 EXECV_CHAR **argvlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005287 Py_ssize_t argc;
5288
5289 /* execv has two arguments: (path, argv), where
5290 argv is a list or tuple of strings. */
5291
Ross Lagerwall7807c352011-03-17 20:20:30 +02005292 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
5293 PyErr_SetString(PyExc_TypeError,
5294 "execv() arg 2 must be a tuple or list");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005295 return NULL;
5296 }
5297 argc = PySequence_Size(argv);
5298 if (argc < 1) {
5299 PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005300 return NULL;
5301 }
5302
5303 argvlist = parse_arglist(argv, &argc);
5304 if (argvlist == NULL) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02005305 return NULL;
5306 }
Steve Dowerbce26262016-11-19 19:17:26 -08005307 if (!argvlist[0][0]) {
5308 PyErr_SetString(PyExc_ValueError,
5309 "execv() arg 2 first element cannot be empty");
5310 free_string_array(argvlist, argc);
5311 return NULL;
5312 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005313
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005314 if (PySys_Audit("os.exec", "OOO", path->object, argv, Py_None) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -08005315 free_string_array(argvlist, argc);
5316 return NULL;
5317 }
5318
Steve Dowerbce26262016-11-19 19:17:26 -08005319 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005320#ifdef HAVE_WEXECV
5321 _wexecv(path->wide, argvlist);
5322#else
5323 execv(path->narrow, argvlist);
5324#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005325 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005326
5327 /* If we get here it's definitely an error */
5328
5329 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005330 return posix_error();
5331}
5332
Larry Hastings2f936352014-08-05 14:04:04 +10005333
5334/*[clinic input]
5335os.execve
5336
5337 path: path_t(allow_fd='PATH_HAVE_FEXECVE')
5338 Path of executable file.
5339 argv: object
5340 Tuple or list of strings.
5341 env: object
5342 Dictionary of strings mapping to strings.
5343
5344Execute an executable path with arguments, replacing current process.
5345[clinic start generated code]*/
5346
Larry Hastings2f936352014-08-05 14:04:04 +10005347static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005348os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
5349/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005350{
Steve Dowercc16be82016-09-08 10:35:16 -07005351 EXECV_CHAR **argvlist = NULL;
5352 EXECV_CHAR **envlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005353 Py_ssize_t argc, envc;
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005354
Victor Stinner8c62be82010-05-06 00:08:46 +00005355 /* execve has three arguments: (path, argv, env), where
5356 argv is a list or tuple of strings and env is a dictionary
5357 like posix.environ. */
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005358
Ross Lagerwall7807c352011-03-17 20:20:30 +02005359 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005360 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005361 "execve: argv must be a tuple or list");
Saiyang Gou95f60012020-02-04 16:15:00 -08005362 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005363 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005364 argc = PySequence_Size(argv);
Steve Dowerbce26262016-11-19 19:17:26 -08005365 if (argc < 1) {
5366 PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
5367 return NULL;
5368 }
5369
Victor Stinner8c62be82010-05-06 00:08:46 +00005370 if (!PyMapping_Check(env)) {
5371 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005372 "execve: environment must be a mapping object");
Saiyang Gou95f60012020-02-04 16:15:00 -08005373 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005374 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005375
Ross Lagerwall7807c352011-03-17 20:20:30 +02005376 argvlist = parse_arglist(argv, &argc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005377 if (argvlist == NULL) {
Saiyang Gou95f60012020-02-04 16:15:00 -08005378 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005379 }
Steve Dowerbce26262016-11-19 19:17:26 -08005380 if (!argvlist[0][0]) {
5381 PyErr_SetString(PyExc_ValueError,
5382 "execve: argv first element cannot be empty");
Saiyang Gou95f60012020-02-04 16:15:00 -08005383 goto fail_0;
Steve Dowerbce26262016-11-19 19:17:26 -08005384 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005385
Victor Stinner8c62be82010-05-06 00:08:46 +00005386 envlist = parse_envlist(env, &envc);
5387 if (envlist == NULL)
Saiyang Gou95f60012020-02-04 16:15:00 -08005388 goto fail_0;
5389
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005390 if (PySys_Audit("os.exec", "OOO", path->object, argv, env) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -08005391 goto fail_1;
5392 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005393
Steve Dowerbce26262016-11-19 19:17:26 -08005394 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07005395#ifdef HAVE_FEXECVE
Larry Hastings2f936352014-08-05 14:04:04 +10005396 if (path->fd > -1)
5397 fexecve(path->fd, argvlist, envlist);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005398 else
5399#endif
Steve Dowercc16be82016-09-08 10:35:16 -07005400#ifdef HAVE_WEXECV
5401 _wexecve(path->wide, argvlist, envlist);
5402#else
Larry Hastings2f936352014-08-05 14:04:04 +10005403 execve(path->narrow, argvlist, envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07005404#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005405 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005406
5407 /* If we get here it's definitely an error */
5408
Alexey Izbyshev83460312018-10-20 03:28:22 +03005409 posix_path_error(path);
Saiyang Gou95f60012020-02-04 16:15:00 -08005410 fail_1:
Steve Dowercc16be82016-09-08 10:35:16 -07005411 free_string_array(envlist, envc);
Saiyang Gou95f60012020-02-04 16:15:00 -08005412 fail_0:
Larry Hastings9cf065c2012-06-22 16:30:09 -07005413 if (argvlist)
5414 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005415 return NULL;
5416}
Steve Dowercc16be82016-09-08 10:35:16 -07005417
Larry Hastings9cf065c2012-06-22 16:30:09 -07005418#endif /* HAVE_EXECV */
5419
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005420#ifdef HAVE_POSIX_SPAWN
5421
5422enum posix_spawn_file_actions_identifier {
5423 POSIX_SPAWN_OPEN,
5424 POSIX_SPAWN_CLOSE,
5425 POSIX_SPAWN_DUP2
5426};
5427
William Orr81574b82018-10-01 22:19:56 -07005428#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005429static int
Pablo Galindo254a4662018-09-07 16:44:24 +01005430convert_sched_param(PyObject *param, struct sched_param *res);
William Orr81574b82018-10-01 22:19:56 -07005431#endif
Pablo Galindo254a4662018-09-07 16:44:24 +01005432
5433static int
Victor Stinner325e4ba2019-02-01 15:47:24 +01005434parse_posix_spawn_flags(const char *func_name, PyObject *setpgroup,
5435 int resetids, int setsid, PyObject *setsigmask,
Pablo Galindo254a4662018-09-07 16:44:24 +01005436 PyObject *setsigdef, PyObject *scheduler,
5437 posix_spawnattr_t *attrp)
5438{
5439 long all_flags = 0;
5440
5441 errno = posix_spawnattr_init(attrp);
5442 if (errno) {
5443 posix_error();
5444 return -1;
5445 }
5446
5447 if (setpgroup) {
5448 pid_t pgid = PyLong_AsPid(setpgroup);
5449 if (pgid == (pid_t)-1 && PyErr_Occurred()) {
5450 goto fail;
5451 }
5452 errno = posix_spawnattr_setpgroup(attrp, pgid);
5453 if (errno) {
5454 posix_error();
5455 goto fail;
5456 }
5457 all_flags |= POSIX_SPAWN_SETPGROUP;
5458 }
5459
5460 if (resetids) {
5461 all_flags |= POSIX_SPAWN_RESETIDS;
5462 }
5463
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005464 if (setsid) {
5465#ifdef POSIX_SPAWN_SETSID
5466 all_flags |= POSIX_SPAWN_SETSID;
5467#elif defined(POSIX_SPAWN_SETSID_NP)
5468 all_flags |= POSIX_SPAWN_SETSID_NP;
5469#else
5470 argument_unavailable_error(func_name, "setsid");
5471 return -1;
5472#endif
5473 }
5474
Pablo Galindo254a4662018-09-07 16:44:24 +01005475 if (setsigmask) {
5476 sigset_t set;
5477 if (!_Py_Sigset_Converter(setsigmask, &set)) {
5478 goto fail;
5479 }
5480 errno = posix_spawnattr_setsigmask(attrp, &set);
5481 if (errno) {
5482 posix_error();
5483 goto fail;
5484 }
5485 all_flags |= POSIX_SPAWN_SETSIGMASK;
5486 }
5487
5488 if (setsigdef) {
5489 sigset_t set;
5490 if (!_Py_Sigset_Converter(setsigdef, &set)) {
5491 goto fail;
5492 }
5493 errno = posix_spawnattr_setsigdefault(attrp, &set);
5494 if (errno) {
5495 posix_error();
5496 goto fail;
5497 }
5498 all_flags |= POSIX_SPAWN_SETSIGDEF;
5499 }
5500
5501 if (scheduler) {
5502#ifdef POSIX_SPAWN_SETSCHEDULER
5503 PyObject *py_schedpolicy;
5504 struct sched_param schedparam;
5505
5506 if (!PyArg_ParseTuple(scheduler, "OO&"
5507 ";A scheduler tuple must have two elements",
5508 &py_schedpolicy, convert_sched_param, &schedparam)) {
5509 goto fail;
5510 }
5511 if (py_schedpolicy != Py_None) {
5512 int schedpolicy = _PyLong_AsInt(py_schedpolicy);
5513
5514 if (schedpolicy == -1 && PyErr_Occurred()) {
5515 goto fail;
5516 }
5517 errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
5518 if (errno) {
5519 posix_error();
5520 goto fail;
5521 }
5522 all_flags |= POSIX_SPAWN_SETSCHEDULER;
5523 }
5524 errno = posix_spawnattr_setschedparam(attrp, &schedparam);
5525 if (errno) {
5526 posix_error();
5527 goto fail;
5528 }
5529 all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
5530#else
5531 PyErr_SetString(PyExc_NotImplementedError,
5532 "The scheduler option is not supported in this system.");
5533 goto fail;
5534#endif
5535 }
5536
5537 errno = posix_spawnattr_setflags(attrp, all_flags);
5538 if (errno) {
5539 posix_error();
5540 goto fail;
5541 }
5542
5543 return 0;
5544
5545fail:
5546 (void)posix_spawnattr_destroy(attrp);
5547 return -1;
5548}
5549
5550static int
Serhiy Storchakaef347532018-05-01 16:45:04 +03005551parse_file_actions(PyObject *file_actions,
Pablo Galindocb970732018-06-19 09:19:50 +01005552 posix_spawn_file_actions_t *file_actionsp,
5553 PyObject *temp_buffer)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005554{
5555 PyObject *seq;
5556 PyObject *file_action = NULL;
5557 PyObject *tag_obj;
5558
5559 seq = PySequence_Fast(file_actions,
5560 "file_actions must be a sequence or None");
5561 if (seq == NULL) {
5562 return -1;
5563 }
5564
5565 errno = posix_spawn_file_actions_init(file_actionsp);
5566 if (errno) {
5567 posix_error();
5568 Py_DECREF(seq);
5569 return -1;
5570 }
5571
Zackery Spytzd52a83a2019-06-26 14:54:20 -06005572 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
Serhiy Storchakaef347532018-05-01 16:45:04 +03005573 file_action = PySequence_Fast_GET_ITEM(seq, i);
5574 Py_INCREF(file_action);
5575 if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
5576 PyErr_SetString(PyExc_TypeError,
5577 "Each file_actions element must be a non-empty tuple");
5578 goto fail;
5579 }
5580 long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
5581 if (tag == -1 && PyErr_Occurred()) {
5582 goto fail;
5583 }
5584
5585 /* Populate the file_actions object */
5586 switch (tag) {
5587 case POSIX_SPAWN_OPEN: {
5588 int fd, oflag;
5589 PyObject *path;
5590 unsigned long mode;
5591 if (!PyArg_ParseTuple(file_action, "OiO&ik"
5592 ";A open file_action tuple must have 5 elements",
5593 &tag_obj, &fd, PyUnicode_FSConverter, &path,
5594 &oflag, &mode))
5595 {
5596 goto fail;
5597 }
Pablo Galindocb970732018-06-19 09:19:50 +01005598 if (PyList_Append(temp_buffer, path)) {
5599 Py_DECREF(path);
5600 goto fail;
5601 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005602 errno = posix_spawn_file_actions_addopen(file_actionsp,
5603 fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
Pablo Galindocb970732018-06-19 09:19:50 +01005604 Py_DECREF(path);
Serhiy Storchakaef347532018-05-01 16:45:04 +03005605 if (errno) {
5606 posix_error();
5607 goto fail;
5608 }
5609 break;
5610 }
5611 case POSIX_SPAWN_CLOSE: {
5612 int fd;
5613 if (!PyArg_ParseTuple(file_action, "Oi"
5614 ";A close file_action tuple must have 2 elements",
5615 &tag_obj, &fd))
5616 {
5617 goto fail;
5618 }
5619 errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
5620 if (errno) {
5621 posix_error();
5622 goto fail;
5623 }
5624 break;
5625 }
5626 case POSIX_SPAWN_DUP2: {
5627 int fd1, fd2;
5628 if (!PyArg_ParseTuple(file_action, "Oii"
5629 ";A dup2 file_action tuple must have 3 elements",
5630 &tag_obj, &fd1, &fd2))
5631 {
5632 goto fail;
5633 }
5634 errno = posix_spawn_file_actions_adddup2(file_actionsp,
5635 fd1, fd2);
5636 if (errno) {
5637 posix_error();
5638 goto fail;
5639 }
5640 break;
5641 }
5642 default: {
5643 PyErr_SetString(PyExc_TypeError,
5644 "Unknown file_actions identifier");
5645 goto fail;
5646 }
5647 }
5648 Py_DECREF(file_action);
5649 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005650
Serhiy Storchakaef347532018-05-01 16:45:04 +03005651 Py_DECREF(seq);
5652 return 0;
5653
5654fail:
5655 Py_DECREF(seq);
5656 Py_DECREF(file_action);
5657 (void)posix_spawn_file_actions_destroy(file_actionsp);
5658 return -1;
5659}
5660
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005661
5662static PyObject *
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005663py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
5664 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005665 PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005666 PyObject *setsigdef, PyObject *scheduler)
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005667{
Victor Stinner325e4ba2019-02-01 15:47:24 +01005668 const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005669 EXECV_CHAR **argvlist = NULL;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005670 EXECV_CHAR **envlist = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005671 posix_spawn_file_actions_t file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005672 posix_spawn_file_actions_t *file_actionsp = NULL;
Pablo Galindo254a4662018-09-07 16:44:24 +01005673 posix_spawnattr_t attr;
5674 posix_spawnattr_t *attrp = NULL;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005675 Py_ssize_t argc, envc;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005676 PyObject *result = NULL;
Pablo Galindocb970732018-06-19 09:19:50 +01005677 PyObject *temp_buffer = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005678 pid_t pid;
5679 int err_code;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005680
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005681 /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
Serhiy Storchakaef347532018-05-01 16:45:04 +03005682 argv is a list or tuple of strings and env is a dictionary
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005683 like posix.environ. */
5684
Serhiy Storchakaef347532018-05-01 16:45:04 +03005685 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005686 PyErr_Format(PyExc_TypeError,
5687 "%s: argv must be a tuple or list", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005688 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005689 }
5690 argc = PySequence_Size(argv);
5691 if (argc < 1) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005692 PyErr_Format(PyExc_ValueError,
5693 "%s: argv must not be empty", func_name);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005694 return NULL;
5695 }
5696
5697 if (!PyMapping_Check(env)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005698 PyErr_Format(PyExc_TypeError,
5699 "%s: environment must be a mapping object", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005700 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005701 }
5702
5703 argvlist = parse_arglist(argv, &argc);
5704 if (argvlist == NULL) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005705 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005706 }
5707 if (!argvlist[0][0]) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005708 PyErr_Format(PyExc_ValueError,
5709 "%s: argv first element cannot be empty", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005710 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005711 }
5712
5713 envlist = parse_envlist(env, &envc);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005714 if (envlist == NULL) {
5715 goto exit;
5716 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005717
Anthony Shaw948ed8c2019-05-10 12:00:06 +10005718 if (file_actions != NULL && file_actions != Py_None) {
Pablo Galindocb970732018-06-19 09:19:50 +01005719 /* There is a bug in old versions of glibc that makes some of the
5720 * helper functions for manipulating file actions not copy the provided
5721 * buffers. The problem is that posix_spawn_file_actions_addopen does not
5722 * copy the value of path for some old versions of glibc (<2.20).
5723 * The use of temp_buffer here is a workaround that keeps the
5724 * python objects that own the buffers alive until posix_spawn gets called.
5725 * Check https://bugs.python.org/issue33630 and
5726 * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
5727 temp_buffer = PyList_New(0);
5728 if (!temp_buffer) {
5729 goto exit;
5730 }
5731 if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005732 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005733 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005734 file_actionsp = &file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005735 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005736
Victor Stinner325e4ba2019-02-01 15:47:24 +01005737 if (parse_posix_spawn_flags(func_name, setpgroup, resetids, setsid,
5738 setsigmask, setsigdef, scheduler, &attr)) {
Pablo Galindo254a4662018-09-07 16:44:24 +01005739 goto exit;
5740 }
5741 attrp = &attr;
5742
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005743 if (PySys_Audit("os.posix_spawn", "OOO", path->object, argv, env) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -08005744 goto exit;
5745 }
5746
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005747 _Py_BEGIN_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005748#ifdef HAVE_POSIX_SPAWNP
5749 if (use_posix_spawnp) {
5750 err_code = posix_spawnp(&pid, path->narrow,
5751 file_actionsp, attrp, argvlist, envlist);
5752 }
5753 else
5754#endif /* HAVE_POSIX_SPAWNP */
5755 {
5756 err_code = posix_spawn(&pid, path->narrow,
5757 file_actionsp, attrp, argvlist, envlist);
5758 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005759 _Py_END_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005760
Serhiy Storchakaef347532018-05-01 16:45:04 +03005761 if (err_code) {
5762 errno = err_code;
5763 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005764 goto exit;
5765 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08005766#ifdef _Py_MEMORY_SANITIZER
5767 __msan_unpoison(&pid, sizeof(pid));
5768#endif
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005769 result = PyLong_FromPid(pid);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005770
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005771exit:
Serhiy Storchakaef347532018-05-01 16:45:04 +03005772 if (file_actionsp) {
5773 (void)posix_spawn_file_actions_destroy(file_actionsp);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005774 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005775 if (attrp) {
5776 (void)posix_spawnattr_destroy(attrp);
5777 }
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005778 if (envlist) {
5779 free_string_array(envlist, envc);
5780 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005781 if (argvlist) {
5782 free_string_array(argvlist, argc);
5783 }
Pablo Galindocb970732018-06-19 09:19:50 +01005784 Py_XDECREF(temp_buffer);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005785 return result;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005786}
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005787
5788
5789/*[clinic input]
5790
5791os.posix_spawn
5792 path: path_t
5793 Path of executable file.
5794 argv: object
5795 Tuple or list of strings.
5796 env: object
5797 Dictionary of strings mapping to strings.
5798 /
5799 *
5800 file_actions: object(c_default='NULL') = ()
5801 A sequence of file action tuples.
5802 setpgroup: object = NULL
5803 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5804 resetids: bool(accept={int}) = False
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005805 If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
5806 setsid: bool(accept={int}) = False
5807 If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005808 setsigmask: object(c_default='NULL') = ()
5809 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5810 setsigdef: object(c_default='NULL') = ()
5811 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5812 scheduler: object = NULL
5813 A tuple with the scheduler policy (optional) and parameters.
5814
5815Execute the program specified by path in a new process.
5816[clinic start generated code]*/
5817
5818static PyObject *
5819os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
5820 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005821 PyObject *setpgroup, int resetids, int setsid,
5822 PyObject *setsigmask, PyObject *setsigdef,
5823 PyObject *scheduler)
5824/*[clinic end generated code: output=14a1098c566bc675 input=8c6305619a00ad04]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005825{
5826 return py_posix_spawn(0, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005827 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005828 scheduler);
5829}
5830 #endif /* HAVE_POSIX_SPAWN */
5831
5832
5833
5834#ifdef HAVE_POSIX_SPAWNP
5835/*[clinic input]
5836
5837os.posix_spawnp
5838 path: path_t
5839 Path of executable file.
5840 argv: object
5841 Tuple or list of strings.
5842 env: object
5843 Dictionary of strings mapping to strings.
5844 /
5845 *
5846 file_actions: object(c_default='NULL') = ()
5847 A sequence of file action tuples.
5848 setpgroup: object = NULL
5849 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5850 resetids: bool(accept={int}) = False
5851 If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005852 setsid: bool(accept={int}) = False
5853 If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005854 setsigmask: object(c_default='NULL') = ()
5855 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5856 setsigdef: object(c_default='NULL') = ()
5857 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5858 scheduler: object = NULL
5859 A tuple with the scheduler policy (optional) and parameters.
5860
5861Execute the program specified by path in a new process.
5862[clinic start generated code]*/
5863
5864static PyObject *
5865os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
5866 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005867 PyObject *setpgroup, int resetids, int setsid,
5868 PyObject *setsigmask, PyObject *setsigdef,
5869 PyObject *scheduler)
5870/*[clinic end generated code: output=7b9aaefe3031238d input=c1911043a22028da]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005871{
5872 return py_posix_spawn(1, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005873 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005874 scheduler);
5875}
5876#endif /* HAVE_POSIX_SPAWNP */
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005877
pxinwrf2d7ac72019-05-21 18:46:37 +08005878#ifdef HAVE_RTPSPAWN
5879static intptr_t
5880_rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
5881 const char *envp[])
5882{
5883 RTP_ID rtpid;
5884 int status;
5885 pid_t res;
5886 int async_err = 0;
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005887
pxinwrf2d7ac72019-05-21 18:46:37 +08005888 /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
5889 uStackSize=0 cannot be used, the default stack size is too small for
5890 Python. */
5891 if (envp) {
5892 rtpid = rtpSpawn(rtpFileName, argv, envp,
5893 100, 0x1000000, 0, VX_FP_TASK);
5894 }
5895 else {
5896 rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
5897 100, 0x1000000, 0, VX_FP_TASK);
5898 }
5899 if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
5900 do {
5901 res = waitpid((pid_t)rtpid, &status, 0);
5902 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
5903
5904 if (res < 0)
5905 return RTP_ID_ERROR;
5906 return ((intptr_t)status);
5907 }
5908 return ((intptr_t)rtpid);
5909}
5910#endif
5911
5912#if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
Larry Hastings2f936352014-08-05 14:04:04 +10005913/*[clinic input]
5914os.spawnv
5915
5916 mode: int
5917 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005918 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005919 Path of executable file.
5920 argv: object
5921 Tuple or list of strings.
5922 /
5923
5924Execute the program specified by path in a new process.
5925[clinic start generated code]*/
5926
Larry Hastings2f936352014-08-05 14:04:04 +10005927static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005928os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
5929/*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005930{
Steve Dowercc16be82016-09-08 10:35:16 -07005931 EXECV_CHAR **argvlist;
Larry Hastings2f936352014-08-05 14:04:04 +10005932 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00005933 Py_ssize_t argc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005934 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005935 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Guido van Rossuma1065681999-01-25 23:20:23 +00005936
Victor Stinner8c62be82010-05-06 00:08:46 +00005937 /* spawnv has three arguments: (mode, path, argv), where
5938 argv is a list or tuple of strings. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005939
Victor Stinner8c62be82010-05-06 00:08:46 +00005940 if (PyList_Check(argv)) {
5941 argc = PyList_Size(argv);
5942 getitem = PyList_GetItem;
5943 }
5944 else if (PyTuple_Check(argv)) {
5945 argc = PyTuple_Size(argv);
5946 getitem = PyTuple_GetItem;
5947 }
5948 else {
5949 PyErr_SetString(PyExc_TypeError,
5950 "spawnv() arg 2 must be a tuple or list");
Victor Stinner8c62be82010-05-06 00:08:46 +00005951 return NULL;
5952 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005953 if (argc == 0) {
5954 PyErr_SetString(PyExc_ValueError,
5955 "spawnv() arg 2 cannot be empty");
5956 return NULL;
5957 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005958
Steve Dowercc16be82016-09-08 10:35:16 -07005959 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005960 if (argvlist == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005961 return PyErr_NoMemory();
5962 }
5963 for (i = 0; i < argc; i++) {
5964 if (!fsconvert_strdup((*getitem)(argv, i),
5965 &argvlist[i])) {
5966 free_string_array(argvlist, i);
5967 PyErr_SetString(
5968 PyExc_TypeError,
5969 "spawnv() arg 2 must contain only strings");
Victor Stinner8c62be82010-05-06 00:08:46 +00005970 return NULL;
5971 }
Steve Dower93ff8722016-11-19 19:03:54 -08005972 if (i == 0 && !argvlist[0][0]) {
Victor Stinner8acb4cf2017-06-15 15:30:40 +02005973 free_string_array(argvlist, i + 1);
Steve Dower93ff8722016-11-19 19:03:54 -08005974 PyErr_SetString(
5975 PyExc_ValueError,
5976 "spawnv() arg 2 first element cannot be empty");
5977 return NULL;
5978 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005979 }
5980 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005981
pxinwrf2d7ac72019-05-21 18:46:37 +08005982#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00005983 if (mode == _OLD_P_OVERLAY)
5984 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08005985#endif
Tim Peters5aa91602002-01-30 05:46:57 +00005986
Saiyang Gou7514f4f2020-02-12 23:47:42 -08005987 if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv,
Saiyang Gou95f60012020-02-04 16:15:00 -08005988 Py_None) < 0) {
5989 free_string_array(argvlist, argc);
5990 return NULL;
5991 }
5992
Victor Stinner8c62be82010-05-06 00:08:46 +00005993 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07005994 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005995#ifdef HAVE_WSPAWNV
5996 spawnval = _wspawnv(mode, path->wide, argvlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08005997#elif defined(HAVE_RTPSPAWN)
5998 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
Steve Dowercc16be82016-09-08 10:35:16 -07005999#else
6000 spawnval = _spawnv(mode, path->narrow, argvlist);
6001#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07006002 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00006003 Py_END_ALLOW_THREADS
Tim Peters5aa91602002-01-30 05:46:57 +00006004
Victor Stinner8c62be82010-05-06 00:08:46 +00006005 free_string_array(argvlist, argc);
Guido van Rossuma1065681999-01-25 23:20:23 +00006006
Victor Stinner8c62be82010-05-06 00:08:46 +00006007 if (spawnval == -1)
6008 return posix_error();
6009 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01006010 return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00006011}
6012
Larry Hastings2f936352014-08-05 14:04:04 +10006013/*[clinic input]
6014os.spawnve
6015
6016 mode: int
6017 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07006018 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10006019 Path of executable file.
6020 argv: object
6021 Tuple or list of strings.
6022 env: object
6023 Dictionary of strings mapping to strings.
6024 /
6025
6026Execute the program specified by path in a new process.
6027[clinic start generated code]*/
6028
Larry Hastings2f936352014-08-05 14:04:04 +10006029static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07006030os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006031 PyObject *env)
Steve Dowercc16be82016-09-08 10:35:16 -07006032/*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006033{
Steve Dowercc16be82016-09-08 10:35:16 -07006034 EXECV_CHAR **argvlist;
6035 EXECV_CHAR **envlist;
Victor Stinner8c62be82010-05-06 00:08:46 +00006036 PyObject *res = NULL;
Antoine Pitrou22e41552010-08-15 18:07:50 +00006037 Py_ssize_t argc, i, envc;
Benjamin Petersonca470632016-09-06 13:47:26 -07006038 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00006039 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006040 Py_ssize_t lastarg = 0;
Guido van Rossuma1065681999-01-25 23:20:23 +00006041
Victor Stinner8c62be82010-05-06 00:08:46 +00006042 /* spawnve has four arguments: (mode, path, argv, env), where
6043 argv is a list or tuple of strings and env is a dictionary
6044 like posix.environ. */
Guido van Rossuma1065681999-01-25 23:20:23 +00006045
Victor Stinner8c62be82010-05-06 00:08:46 +00006046 if (PyList_Check(argv)) {
6047 argc = PyList_Size(argv);
6048 getitem = PyList_GetItem;
6049 }
6050 else if (PyTuple_Check(argv)) {
6051 argc = PyTuple_Size(argv);
6052 getitem = PyTuple_GetItem;
6053 }
6054 else {
6055 PyErr_SetString(PyExc_TypeError,
6056 "spawnve() arg 2 must be a tuple or list");
6057 goto fail_0;
6058 }
Steve Dower859fd7b2016-11-19 18:53:19 -08006059 if (argc == 0) {
6060 PyErr_SetString(PyExc_ValueError,
6061 "spawnve() arg 2 cannot be empty");
6062 goto fail_0;
6063 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006064 if (!PyMapping_Check(env)) {
6065 PyErr_SetString(PyExc_TypeError,
6066 "spawnve() arg 3 must be a mapping object");
6067 goto fail_0;
6068 }
Guido van Rossuma1065681999-01-25 23:20:23 +00006069
Steve Dowercc16be82016-09-08 10:35:16 -07006070 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00006071 if (argvlist == NULL) {
6072 PyErr_NoMemory();
6073 goto fail_0;
6074 }
6075 for (i = 0; i < argc; i++) {
6076 if (!fsconvert_strdup((*getitem)(argv, i),
6077 &argvlist[i]))
6078 {
6079 lastarg = i;
6080 goto fail_1;
6081 }
Steve Dowerbce26262016-11-19 19:17:26 -08006082 if (i == 0 && !argvlist[0][0]) {
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006083 lastarg = i + 1;
Steve Dowerbce26262016-11-19 19:17:26 -08006084 PyErr_SetString(
6085 PyExc_ValueError,
6086 "spawnv() arg 2 first element cannot be empty");
6087 goto fail_1;
6088 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006089 }
6090 lastarg = argc;
6091 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00006092
Victor Stinner8c62be82010-05-06 00:08:46 +00006093 envlist = parse_envlist(env, &envc);
6094 if (envlist == NULL)
6095 goto fail_1;
Guido van Rossuma1065681999-01-25 23:20:23 +00006096
pxinwrf2d7ac72019-05-21 18:46:37 +08006097#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00006098 if (mode == _OLD_P_OVERLAY)
6099 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08006100#endif
Tim Peters25059d32001-12-07 20:35:43 +00006101
Saiyang Gou7514f4f2020-02-12 23:47:42 -08006102 if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv, env) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -08006103 goto fail_2;
6104 }
6105
Victor Stinner8c62be82010-05-06 00:08:46 +00006106 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07006107 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07006108#ifdef HAVE_WSPAWNV
6109 spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08006110#elif defined(HAVE_RTPSPAWN)
6111 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
6112 (const char **)envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07006113#else
6114 spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
6115#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07006116 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00006117 Py_END_ALLOW_THREADS
Tim Peters25059d32001-12-07 20:35:43 +00006118
Victor Stinner8c62be82010-05-06 00:08:46 +00006119 if (spawnval == -1)
6120 (void) posix_error();
6121 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01006122 res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00006123
Saiyang Gou95f60012020-02-04 16:15:00 -08006124 fail_2:
Victor Stinner8c62be82010-05-06 00:08:46 +00006125 while (--envc >= 0)
6126 PyMem_DEL(envlist[envc]);
6127 PyMem_DEL(envlist);
Guido van Rossum0847c5c2002-12-13 18:36:22 +00006128 fail_1:
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006129 free_string_array(argvlist, lastarg);
Martin v. Löwis114619e2002-10-07 06:44:21 +00006130 fail_0:
Victor Stinner8c62be82010-05-06 00:08:46 +00006131 return res;
Guido van Rossuma1065681999-01-25 23:20:23 +00006132}
Andrew MacIntyre69e18c92004-04-04 07:11:43 +00006133
Guido van Rossuma1065681999-01-25 23:20:23 +00006134#endif /* HAVE_SPAWNV */
6135
6136
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006137#ifdef HAVE_FORK
Gregory P. Smith163468a2017-05-29 10:03:41 -07006138
6139/* Helper function to validate arguments.
6140 Returns 0 on success. non-zero on failure with a TypeError raised.
6141 If obj is non-NULL it must be callable. */
6142static int
6143check_null_or_callable(PyObject *obj, const char* obj_name)
6144{
6145 if (obj && !PyCallable_Check(obj)) {
6146 PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
Eddie Elizondob3966632019-11-05 07:16:14 -08006147 obj_name, _PyType_Name(Py_TYPE(obj)));
Gregory P. Smith163468a2017-05-29 10:03:41 -07006148 return -1;
6149 }
6150 return 0;
6151}
6152
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006153/*[clinic input]
6154os.register_at_fork
6155
Gregory P. Smith163468a2017-05-29 10:03:41 -07006156 *
6157 before: object=NULL
6158 A callable to be called in the parent before the fork() syscall.
6159 after_in_child: object=NULL
6160 A callable to be called in the child after fork().
6161 after_in_parent: object=NULL
6162 A callable to be called in the parent after fork().
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006163
Gregory P. Smith163468a2017-05-29 10:03:41 -07006164Register callables to be called when forking a new process.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006165
Gregory P. Smith163468a2017-05-29 10:03:41 -07006166'before' callbacks are called in reverse order.
6167'after_in_child' and 'after_in_parent' callbacks are called in order.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006168
6169[clinic start generated code]*/
6170
6171static PyObject *
Gregory P. Smith163468a2017-05-29 10:03:41 -07006172os_register_at_fork_impl(PyObject *module, PyObject *before,
6173 PyObject *after_in_child, PyObject *after_in_parent)
6174/*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006175{
6176 PyInterpreterState *interp;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006177
Gregory P. Smith163468a2017-05-29 10:03:41 -07006178 if (!before && !after_in_child && !after_in_parent) {
6179 PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
6180 return NULL;
6181 }
6182 if (check_null_or_callable(before, "before") ||
6183 check_null_or_callable(after_in_child, "after_in_child") ||
6184 check_null_or_callable(after_in_parent, "after_in_parent")) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006185 return NULL;
6186 }
Victor Stinnerff4584c2020-03-13 18:03:56 +01006187 interp = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006188
Gregory P. Smith163468a2017-05-29 10:03:41 -07006189 if (register_at_forker(&interp->before_forkers, before)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006190 return NULL;
6191 }
Gregory P. Smith163468a2017-05-29 10:03:41 -07006192 if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006193 return NULL;
Gregory P. Smith163468a2017-05-29 10:03:41 -07006194 }
6195 if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
6196 return NULL;
6197 }
6198 Py_RETURN_NONE;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006199}
6200#endif /* HAVE_FORK */
6201
6202
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006203#ifdef HAVE_FORK1
Larry Hastings2f936352014-08-05 14:04:04 +10006204/*[clinic input]
6205os.fork1
6206
6207Fork a child process with a single multiplexed (i.e., not bound) thread.
6208
6209Return 0 to child process and PID of child to parent process.
6210[clinic start generated code]*/
6211
Larry Hastings2f936352014-08-05 14:04:04 +10006212static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006213os_fork1_impl(PyObject *module)
6214/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006215{
Victor Stinner8c62be82010-05-06 00:08:46 +00006216 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006217
Victor Stinnerff4584c2020-03-13 18:03:56 +01006218 if (_PyInterpreterState_GET_UNSAFE() != PyInterpreterState_Main()) {
Eric Snow59032962018-09-14 14:17:20 -07006219 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6220 return NULL;
6221 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006222 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006223 pid = fork1();
6224 if (pid == 0) {
6225 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006226 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006227 } else {
6228 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006229 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006230 }
6231 if (pid == -1)
6232 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006233 return PyLong_FromPid(pid);
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006234}
Larry Hastings2f936352014-08-05 14:04:04 +10006235#endif /* HAVE_FORK1 */
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006236
6237
Guido van Rossumad0ee831995-03-01 10:34:45 +00006238#ifdef HAVE_FORK
Larry Hastings2f936352014-08-05 14:04:04 +10006239/*[clinic input]
6240os.fork
6241
6242Fork a child process.
6243
6244Return 0 to child process and PID of child to parent process.
6245[clinic start generated code]*/
6246
Larry Hastings2f936352014-08-05 14:04:04 +10006247static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006248os_fork_impl(PyObject *module)
6249/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006250{
Victor Stinner8c62be82010-05-06 00:08:46 +00006251 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006252
Victor Stinnerff4584c2020-03-13 18:03:56 +01006253 if (_PyInterpreterState_GET_UNSAFE() != PyInterpreterState_Main()) {
Eric Snow59032962018-09-14 14:17:20 -07006254 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6255 return NULL;
6256 }
Saiyang Gou7514f4f2020-02-12 23:47:42 -08006257 if (PySys_Audit("os.fork", NULL) < 0) {
6258 return NULL;
6259 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006260 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006261 pid = fork();
6262 if (pid == 0) {
6263 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006264 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006265 } else {
6266 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006267 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006268 }
6269 if (pid == -1)
6270 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006271 return PyLong_FromPid(pid);
Guido van Rossum85e3b011991-06-03 12:42:10 +00006272}
Larry Hastings2f936352014-08-05 14:04:04 +10006273#endif /* HAVE_FORK */
6274
Guido van Rossum85e3b011991-06-03 12:42:10 +00006275
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006276#ifdef HAVE_SCHED_H
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006277#ifdef HAVE_SCHED_GET_PRIORITY_MAX
Larry Hastings2f936352014-08-05 14:04:04 +10006278/*[clinic input]
6279os.sched_get_priority_max
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006280
Larry Hastings2f936352014-08-05 14:04:04 +10006281 policy: int
6282
6283Get the maximum scheduling priority for policy.
6284[clinic start generated code]*/
6285
Larry Hastings2f936352014-08-05 14:04:04 +10006286static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006287os_sched_get_priority_max_impl(PyObject *module, int policy)
6288/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006289{
6290 int max;
6291
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006292 max = sched_get_priority_max(policy);
6293 if (max < 0)
6294 return posix_error();
6295 return PyLong_FromLong(max);
6296}
6297
Larry Hastings2f936352014-08-05 14:04:04 +10006298
6299/*[clinic input]
6300os.sched_get_priority_min
6301
6302 policy: int
6303
6304Get the minimum scheduling priority for policy.
6305[clinic start generated code]*/
6306
Larry Hastings2f936352014-08-05 14:04:04 +10006307static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006308os_sched_get_priority_min_impl(PyObject *module, int policy)
6309/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006310{
6311 int min = sched_get_priority_min(policy);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006312 if (min < 0)
6313 return posix_error();
6314 return PyLong_FromLong(min);
6315}
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006316#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
6317
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006318
Larry Hastings2f936352014-08-05 14:04:04 +10006319#ifdef HAVE_SCHED_SETSCHEDULER
6320/*[clinic input]
6321os.sched_getscheduler
6322 pid: pid_t
6323 /
6324
Min ho Kimc4cacc82019-07-31 08:16:13 +10006325Get the scheduling policy for the process identified by pid.
Larry Hastings2f936352014-08-05 14:04:04 +10006326
6327Passing 0 for pid returns the scheduling policy for the calling process.
6328[clinic start generated code]*/
6329
Larry Hastings2f936352014-08-05 14:04:04 +10006330static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006331os_sched_getscheduler_impl(PyObject *module, pid_t pid)
Min ho Kimc4cacc82019-07-31 08:16:13 +10006332/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=8d99dac505485ac8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006333{
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006334 int policy;
6335
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006336 policy = sched_getscheduler(pid);
6337 if (policy < 0)
6338 return posix_error();
6339 return PyLong_FromLong(policy);
6340}
Larry Hastings2f936352014-08-05 14:04:04 +10006341#endif /* HAVE_SCHED_SETSCHEDULER */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006342
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006343
William Orr81574b82018-10-01 22:19:56 -07006344#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Larry Hastings2f936352014-08-05 14:04:04 +10006345/*[clinic input]
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006346class os.sched_param "PyObject *" "SchedParamType"
Larry Hastings2f936352014-08-05 14:04:04 +10006347
6348@classmethod
6349os.sched_param.__new__
6350
6351 sched_priority: object
6352 A scheduling parameter.
6353
Eddie Elizondob3966632019-11-05 07:16:14 -08006354Currently has only one field: sched_priority
Larry Hastings2f936352014-08-05 14:04:04 +10006355[clinic start generated code]*/
6356
Larry Hastings2f936352014-08-05 14:04:04 +10006357static PyObject *
6358os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
Eddie Elizondob3966632019-11-05 07:16:14 -08006359/*[clinic end generated code: output=48f4067d60f48c13 input=eb42909a2c0e3e6c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006360{
6361 PyObject *res;
6362
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006363 res = PyStructSequence_New(type);
6364 if (!res)
6365 return NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10006366 Py_INCREF(sched_priority);
6367 PyStructSequence_SET_ITEM(res, 0, sched_priority);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006368 return res;
6369}
6370
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03006371PyDoc_VAR(os_sched_param__doc__);
6372
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006373static PyStructSequence_Field sched_param_fields[] = {
6374 {"sched_priority", "the scheduling priority"},
6375 {0}
6376};
6377
6378static PyStructSequence_Desc sched_param_desc = {
6379 "sched_param", /* name */
Larry Hastings2f936352014-08-05 14:04:04 +10006380 os_sched_param__doc__, /* doc */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006381 sched_param_fields,
6382 1
6383};
6384
6385static int
6386convert_sched_param(PyObject *param, struct sched_param *res)
6387{
6388 long priority;
6389
Andy Lester55728702020-03-06 16:53:17 -06006390 if (!Py_IS_TYPE(param, (PyTypeObject *)_posixstate_global->SchedParamType)) {
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006391 PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
6392 return 0;
6393 }
6394 priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
6395 if (priority == -1 && PyErr_Occurred())
6396 return 0;
6397 if (priority > INT_MAX || priority < INT_MIN) {
6398 PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
6399 return 0;
6400 }
6401 res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
6402 return 1;
6403}
William Orr81574b82018-10-01 22:19:56 -07006404#endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006405
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006406
6407#ifdef HAVE_SCHED_SETSCHEDULER
Larry Hastings2f936352014-08-05 14:04:04 +10006408/*[clinic input]
6409os.sched_setscheduler
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006410
Larry Hastings2f936352014-08-05 14:04:04 +10006411 pid: pid_t
6412 policy: int
6413 param: sched_param
6414 /
6415
6416Set the scheduling policy for the process identified by pid.
6417
6418If pid is 0, the calling process is changed.
6419param is an instance of sched_param.
6420[clinic start generated code]*/
6421
Larry Hastings2f936352014-08-05 14:04:04 +10006422static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006423os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
Larry Hastings89964c42015-04-14 18:07:59 -04006424 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006425/*[clinic end generated code: output=b0ac0a70d3b1d705 input=c581f9469a5327dd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006426{
Jesus Cea9c822272011-09-10 01:40:52 +02006427 /*
Jesus Cea54b01492011-09-10 01:53:19 +02006428 ** sched_setscheduler() returns 0 in Linux, but the previous
6429 ** scheduling policy under Solaris/Illumos, and others.
6430 ** On error, -1 is returned in all Operating Systems.
Jesus Cea9c822272011-09-10 01:40:52 +02006431 */
Larry Hastings2f936352014-08-05 14:04:04 +10006432 if (sched_setscheduler(pid, policy, param) == -1)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006433 return posix_error();
6434 Py_RETURN_NONE;
6435}
Larry Hastings2f936352014-08-05 14:04:04 +10006436#endif /* HAVE_SCHED_SETSCHEDULER*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006437
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006438
6439#ifdef HAVE_SCHED_SETPARAM
Larry Hastings2f936352014-08-05 14:04:04 +10006440/*[clinic input]
6441os.sched_getparam
6442 pid: pid_t
6443 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006444
Larry Hastings2f936352014-08-05 14:04:04 +10006445Returns scheduling parameters for the process identified by pid.
6446
6447If pid is 0, returns parameters for the calling process.
6448Return value is an instance of sched_param.
6449[clinic start generated code]*/
6450
Larry Hastings2f936352014-08-05 14:04:04 +10006451static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006452os_sched_getparam_impl(PyObject *module, pid_t pid)
6453/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006454{
6455 struct sched_param param;
6456 PyObject *result;
6457 PyObject *priority;
6458
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006459 if (sched_getparam(pid, &param))
6460 return posix_error();
Eddie Elizondob3966632019-11-05 07:16:14 -08006461 PyObject *SchedParamType = _posixstate_global->SchedParamType;
6462 result = PyStructSequence_New((PyTypeObject *)SchedParamType);
Larry Hastings2f936352014-08-05 14:04:04 +10006463 if (!result)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006464 return NULL;
6465 priority = PyLong_FromLong(param.sched_priority);
6466 if (!priority) {
Larry Hastings2f936352014-08-05 14:04:04 +10006467 Py_DECREF(result);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006468 return NULL;
6469 }
Larry Hastings2f936352014-08-05 14:04:04 +10006470 PyStructSequence_SET_ITEM(result, 0, priority);
6471 return result;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006472}
6473
Larry Hastings2f936352014-08-05 14:04:04 +10006474
6475/*[clinic input]
6476os.sched_setparam
6477 pid: pid_t
6478 param: sched_param
6479 /
6480
6481Set scheduling parameters for the process identified by pid.
6482
6483If pid is 0, sets parameters for the calling process.
6484param should be an instance of sched_param.
6485[clinic start generated code]*/
6486
Larry Hastings2f936352014-08-05 14:04:04 +10006487static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006488os_sched_setparam_impl(PyObject *module, pid_t pid,
Larry Hastings89964c42015-04-14 18:07:59 -04006489 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006490/*[clinic end generated code: output=8af013f78a32b591 input=6b8d6dfcecdc21bd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006491{
6492 if (sched_setparam(pid, param))
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006493 return posix_error();
6494 Py_RETURN_NONE;
6495}
Larry Hastings2f936352014-08-05 14:04:04 +10006496#endif /* HAVE_SCHED_SETPARAM */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006497
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006498
6499#ifdef HAVE_SCHED_RR_GET_INTERVAL
Larry Hastings2f936352014-08-05 14:04:04 +10006500/*[clinic input]
6501os.sched_rr_get_interval -> double
6502 pid: pid_t
6503 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006504
Larry Hastings2f936352014-08-05 14:04:04 +10006505Return the round-robin quantum for the process identified by pid, in seconds.
6506
6507Value returned is a float.
6508[clinic start generated code]*/
6509
Larry Hastings2f936352014-08-05 14:04:04 +10006510static double
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006511os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
6512/*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006513{
6514 struct timespec interval;
6515 if (sched_rr_get_interval(pid, &interval)) {
6516 posix_error();
6517 return -1.0;
6518 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006519#ifdef _Py_MEMORY_SANITIZER
6520 __msan_unpoison(&interval, sizeof(interval));
6521#endif
Larry Hastings2f936352014-08-05 14:04:04 +10006522 return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
6523}
6524#endif /* HAVE_SCHED_RR_GET_INTERVAL */
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006525
Larry Hastings2f936352014-08-05 14:04:04 +10006526
6527/*[clinic input]
6528os.sched_yield
6529
6530Voluntarily relinquish the CPU.
6531[clinic start generated code]*/
6532
Larry Hastings2f936352014-08-05 14:04:04 +10006533static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006534os_sched_yield_impl(PyObject *module)
6535/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006536{
6537 if (sched_yield())
6538 return posix_error();
6539 Py_RETURN_NONE;
6540}
6541
Benjamin Peterson2740af82011-08-02 17:41:34 -05006542#ifdef HAVE_SCHED_SETAFFINITY
Antoine Pitrou84869872012-08-04 16:16:35 +02006543/* The minimum number of CPUs allocated in a cpu_set_t */
6544static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006545
Larry Hastings2f936352014-08-05 14:04:04 +10006546/*[clinic input]
6547os.sched_setaffinity
6548 pid: pid_t
6549 mask : object
6550 /
6551
6552Set the CPU affinity of the process identified by pid to mask.
6553
6554mask should be an iterable of integers identifying CPUs.
6555[clinic start generated code]*/
6556
Larry Hastings2f936352014-08-05 14:04:04 +10006557static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006558os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
6559/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006560{
Antoine Pitrou84869872012-08-04 16:16:35 +02006561 int ncpus;
6562 size_t setsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006563 cpu_set_t *cpu_set = NULL;
6564 PyObject *iterator = NULL, *item;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006565
Larry Hastings2f936352014-08-05 14:04:04 +10006566 iterator = PyObject_GetIter(mask);
Antoine Pitrou84869872012-08-04 16:16:35 +02006567 if (iterator == NULL)
6568 return NULL;
6569
6570 ncpus = NCPUS_START;
6571 setsize = CPU_ALLOC_SIZE(ncpus);
Larry Hastings2f936352014-08-05 14:04:04 +10006572 cpu_set = CPU_ALLOC(ncpus);
6573 if (cpu_set == NULL) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006574 PyErr_NoMemory();
6575 goto error;
6576 }
Larry Hastings2f936352014-08-05 14:04:04 +10006577 CPU_ZERO_S(setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006578
6579 while ((item = PyIter_Next(iterator))) {
6580 long cpu;
6581 if (!PyLong_Check(item)) {
6582 PyErr_Format(PyExc_TypeError,
6583 "expected an iterator of ints, "
6584 "but iterator yielded %R",
6585 Py_TYPE(item));
6586 Py_DECREF(item);
6587 goto error;
6588 }
6589 cpu = PyLong_AsLong(item);
6590 Py_DECREF(item);
6591 if (cpu < 0) {
6592 if (!PyErr_Occurred())
6593 PyErr_SetString(PyExc_ValueError, "negative CPU number");
6594 goto error;
6595 }
6596 if (cpu > INT_MAX - 1) {
6597 PyErr_SetString(PyExc_OverflowError, "CPU number too large");
6598 goto error;
6599 }
6600 if (cpu >= ncpus) {
6601 /* Grow CPU mask to fit the CPU number */
6602 int newncpus = ncpus;
6603 cpu_set_t *newmask;
6604 size_t newsetsize;
6605 while (newncpus <= cpu) {
6606 if (newncpus > INT_MAX / 2)
6607 newncpus = cpu + 1;
6608 else
6609 newncpus = newncpus * 2;
6610 }
6611 newmask = CPU_ALLOC(newncpus);
6612 if (newmask == NULL) {
6613 PyErr_NoMemory();
6614 goto error;
6615 }
6616 newsetsize = CPU_ALLOC_SIZE(newncpus);
6617 CPU_ZERO_S(newsetsize, newmask);
Larry Hastings2f936352014-08-05 14:04:04 +10006618 memcpy(newmask, cpu_set, setsize);
6619 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006620 setsize = newsetsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006621 cpu_set = newmask;
Antoine Pitrou84869872012-08-04 16:16:35 +02006622 ncpus = newncpus;
6623 }
Larry Hastings2f936352014-08-05 14:04:04 +10006624 CPU_SET_S(cpu, setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006625 }
Brandt Bucher45a30af2019-06-27 09:10:57 -07006626 if (PyErr_Occurred()) {
6627 goto error;
6628 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006629 Py_CLEAR(iterator);
6630
Larry Hastings2f936352014-08-05 14:04:04 +10006631 if (sched_setaffinity(pid, setsize, cpu_set)) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006632 posix_error();
6633 goto error;
6634 }
Larry Hastings2f936352014-08-05 14:04:04 +10006635 CPU_FREE(cpu_set);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006636 Py_RETURN_NONE;
Antoine Pitrou84869872012-08-04 16:16:35 +02006637
6638error:
Larry Hastings2f936352014-08-05 14:04:04 +10006639 if (cpu_set)
6640 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006641 Py_XDECREF(iterator);
6642 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006643}
6644
Larry Hastings2f936352014-08-05 14:04:04 +10006645
6646/*[clinic input]
6647os.sched_getaffinity
6648 pid: pid_t
6649 /
6650
Charles-François Natalidc87e4b2015-07-13 21:01:39 +01006651Return the affinity of the process identified by pid (or the current process if zero).
Larry Hastings2f936352014-08-05 14:04:04 +10006652
6653The affinity is returned as a set of CPU identifiers.
6654[clinic start generated code]*/
6655
Larry Hastings2f936352014-08-05 14:04:04 +10006656static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006657os_sched_getaffinity_impl(PyObject *module, pid_t pid)
Serhiy Storchaka2954f832016-07-07 18:20:03 +03006658/*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006659{
Antoine Pitrou84869872012-08-04 16:16:35 +02006660 int cpu, ncpus, count;
6661 size_t setsize;
6662 cpu_set_t *mask = NULL;
6663 PyObject *res = NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006664
Antoine Pitrou84869872012-08-04 16:16:35 +02006665 ncpus = NCPUS_START;
6666 while (1) {
6667 setsize = CPU_ALLOC_SIZE(ncpus);
6668 mask = CPU_ALLOC(ncpus);
6669 if (mask == NULL)
6670 return PyErr_NoMemory();
6671 if (sched_getaffinity(pid, setsize, mask) == 0)
6672 break;
6673 CPU_FREE(mask);
6674 if (errno != EINVAL)
6675 return posix_error();
6676 if (ncpus > INT_MAX / 2) {
6677 PyErr_SetString(PyExc_OverflowError, "could not allocate "
6678 "a large enough CPU set");
6679 return NULL;
6680 }
6681 ncpus = ncpus * 2;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006682 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006683
6684 res = PySet_New(NULL);
6685 if (res == NULL)
6686 goto error;
6687 for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
6688 if (CPU_ISSET_S(cpu, setsize, mask)) {
6689 PyObject *cpu_num = PyLong_FromLong(cpu);
6690 --count;
6691 if (cpu_num == NULL)
6692 goto error;
6693 if (PySet_Add(res, cpu_num)) {
6694 Py_DECREF(cpu_num);
6695 goto error;
6696 }
6697 Py_DECREF(cpu_num);
6698 }
6699 }
6700 CPU_FREE(mask);
6701 return res;
6702
6703error:
6704 if (mask)
6705 CPU_FREE(mask);
6706 Py_XDECREF(res);
6707 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006708}
6709
Benjamin Peterson2740af82011-08-02 17:41:34 -05006710#endif /* HAVE_SCHED_SETAFFINITY */
6711
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006712#endif /* HAVE_SCHED_H */
6713
Larry Hastings2f936352014-08-05 14:04:04 +10006714
Neal Norwitzb59798b2003-03-21 01:43:31 +00006715/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
Neal Norwitz2deaddb2003-03-21 03:08:31 +00006716/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
6717#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
Neal Norwitzb59798b2003-03-21 01:43:31 +00006718#define DEV_PTY_FILE "/dev/ptc"
6719#define HAVE_DEV_PTMX
6720#else
6721#define DEV_PTY_FILE "/dev/ptmx"
6722#endif
6723
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006724#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
Fred Drake8cef4cf2000-06-28 16:40:38 +00006725#ifdef HAVE_PTY_H
6726#include <pty.h>
6727#else
6728#ifdef HAVE_LIBUTIL_H
6729#include <libutil.h>
Ronald Oussoren755740f2010-02-07 19:56:39 +00006730#else
6731#ifdef HAVE_UTIL_H
6732#include <util.h>
6733#endif /* HAVE_UTIL_H */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006734#endif /* HAVE_LIBUTIL_H */
6735#endif /* HAVE_PTY_H */
Martin v. Löwis14e73b12003-01-01 09:51:12 +00006736#ifdef HAVE_STROPTS_H
6737#include <stropts.h>
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006738#endif
ngie-eign7745ec42018-02-14 11:54:28 -08006739#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006740
Larry Hastings2f936352014-08-05 14:04:04 +10006741
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006742#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
Larry Hastings2f936352014-08-05 14:04:04 +10006743/*[clinic input]
6744os.openpty
6745
6746Open a pseudo-terminal.
6747
6748Return a tuple of (master_fd, slave_fd) containing open file descriptors
6749for both the master and slave ends.
6750[clinic start generated code]*/
6751
Larry Hastings2f936352014-08-05 14:04:04 +10006752static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006753os_openpty_impl(PyObject *module)
6754/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006755{
Victor Stinnerdaf45552013-08-28 00:53:59 +02006756 int master_fd = -1, slave_fd = -1;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006757#ifndef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006758 char * slave_name;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006759#endif
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006760#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006761 PyOS_sighandler_t sig_saved;
Jakub Kulík6f9bc722018-12-31 03:16:40 +01006762#if defined(__sun) && defined(__SVR4)
Victor Stinner8c62be82010-05-06 00:08:46 +00006763 extern char *ptsname(int fildes);
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006764#endif
6765#endif
Thomas Wouters70c21a12000-07-14 14:28:33 +00006766
Thomas Wouters70c21a12000-07-14 14:28:33 +00006767#ifdef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006768 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006769 goto posix_error;
6770
6771 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6772 goto error;
6773 if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
6774 goto error;
6775
Neal Norwitzb59798b2003-03-21 01:43:31 +00006776#elif defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006777 slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
6778 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006779 goto posix_error;
6780 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6781 goto error;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006782
Victor Stinnerdaf45552013-08-28 00:53:59 +02006783 slave_fd = _Py_open(slave_name, O_RDWR);
Victor Stinner8c62be82010-05-06 00:08:46 +00006784 if (slave_fd < 0)
Victor Stinnera555cfc2015-03-18 00:22:14 +01006785 goto error;
Victor Stinnerdaf45552013-08-28 00:53:59 +02006786
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006787#else
Victor Stinner000de532013-11-25 23:19:58 +01006788 master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
Victor Stinner8c62be82010-05-06 00:08:46 +00006789 if (master_fd < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006790 goto posix_error;
6791
Victor Stinner8c62be82010-05-06 00:08:46 +00006792 sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006793
Victor Stinner8c62be82010-05-06 00:08:46 +00006794 /* change permission of slave */
6795 if (grantpt(master_fd) < 0) {
6796 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006797 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006798 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006799
Victor Stinner8c62be82010-05-06 00:08:46 +00006800 /* unlock slave */
6801 if (unlockpt(master_fd) < 0) {
6802 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006803 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006804 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006805
Victor Stinner8c62be82010-05-06 00:08:46 +00006806 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006807
Victor Stinner8c62be82010-05-06 00:08:46 +00006808 slave_name = ptsname(master_fd); /* get name of slave */
6809 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006810 goto posix_error;
6811
6812 slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
Victor Stinnera555cfc2015-03-18 00:22:14 +01006813 if (slave_fd == -1)
6814 goto error;
Victor Stinner000de532013-11-25 23:19:58 +01006815
6816 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6817 goto posix_error;
6818
Stefan Krahfb7c8ae2016-04-26 17:04:18 +02006819#if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
Victor Stinner8c62be82010-05-06 00:08:46 +00006820 ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
6821 ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
Neal Norwitz6700e472002-12-31 16:16:07 +00006822#ifndef __hpux
Victor Stinner8c62be82010-05-06 00:08:46 +00006823 ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
Neal Norwitz6700e472002-12-31 16:16:07 +00006824#endif /* __hpux */
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006825#endif /* HAVE_CYGWIN */
Thomas Wouters1e0c2f42000-07-24 16:06:23 +00006826#endif /* HAVE_OPENPTY */
Thomas Wouters70c21a12000-07-14 14:28:33 +00006827
Victor Stinner8c62be82010-05-06 00:08:46 +00006828 return Py_BuildValue("(ii)", master_fd, slave_fd);
Thomas Wouters70c21a12000-07-14 14:28:33 +00006829
Victor Stinnerdaf45552013-08-28 00:53:59 +02006830posix_error:
6831 posix_error();
6832error:
6833 if (master_fd != -1)
6834 close(master_fd);
6835 if (slave_fd != -1)
6836 close(slave_fd);
6837 return NULL;
Fred Drake8cef4cf2000-06-28 16:40:38 +00006838}
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006839#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006840
Larry Hastings2f936352014-08-05 14:04:04 +10006841
Fred Drake8cef4cf2000-06-28 16:40:38 +00006842#ifdef HAVE_FORKPTY
Larry Hastings2f936352014-08-05 14:04:04 +10006843/*[clinic input]
6844os.forkpty
6845
6846Fork a new process with a new pseudo-terminal as controlling tty.
6847
6848Returns a tuple of (pid, master_fd).
6849Like fork(), return pid of 0 to the child process,
6850and pid of child to the parent process.
6851To both, return fd of newly opened pseudo-terminal.
6852[clinic start generated code]*/
6853
Larry Hastings2f936352014-08-05 14:04:04 +10006854static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006855os_forkpty_impl(PyObject *module)
6856/*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006857{
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006858 int master_fd = -1;
Victor Stinner8c62be82010-05-06 00:08:46 +00006859 pid_t pid;
Tim Peters5aa91602002-01-30 05:46:57 +00006860
Victor Stinnerff4584c2020-03-13 18:03:56 +01006861 if (_PyInterpreterState_GET_UNSAFE() != PyInterpreterState_Main()) {
Eric Snow59032962018-09-14 14:17:20 -07006862 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6863 return NULL;
6864 }
Saiyang Gou7514f4f2020-02-12 23:47:42 -08006865 if (PySys_Audit("os.forkpty", NULL) < 0) {
6866 return NULL;
6867 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006868 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006869 pid = forkpty(&master_fd, NULL, NULL, NULL);
6870 if (pid == 0) {
6871 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006872 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006873 } else {
6874 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006875 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006876 }
6877 if (pid == -1)
6878 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006879 return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
Fred Drake8cef4cf2000-06-28 16:40:38 +00006880}
Larry Hastings2f936352014-08-05 14:04:04 +10006881#endif /* HAVE_FORKPTY */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006882
Ross Lagerwall7807c352011-03-17 20:20:30 +02006883
Guido van Rossumad0ee831995-03-01 10:34:45 +00006884#ifdef HAVE_GETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10006885/*[clinic input]
6886os.getegid
6887
6888Return the current process's effective group id.
6889[clinic start generated code]*/
6890
Larry Hastings2f936352014-08-05 14:04:04 +10006891static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006892os_getegid_impl(PyObject *module)
6893/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006894{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006895 return _PyLong_FromGid(getegid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006896}
Larry Hastings2f936352014-08-05 14:04:04 +10006897#endif /* HAVE_GETEGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006898
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006899
Guido van Rossumad0ee831995-03-01 10:34:45 +00006900#ifdef HAVE_GETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10006901/*[clinic input]
6902os.geteuid
6903
6904Return the current process's effective user id.
6905[clinic start generated code]*/
6906
Larry Hastings2f936352014-08-05 14:04:04 +10006907static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006908os_geteuid_impl(PyObject *module)
6909/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006910{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006911 return _PyLong_FromUid(geteuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006912}
Larry Hastings2f936352014-08-05 14:04:04 +10006913#endif /* HAVE_GETEUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006914
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006915
Guido van Rossumad0ee831995-03-01 10:34:45 +00006916#ifdef HAVE_GETGID
Larry Hastings2f936352014-08-05 14:04:04 +10006917/*[clinic input]
6918os.getgid
6919
6920Return the current process's group id.
6921[clinic start generated code]*/
6922
Larry Hastings2f936352014-08-05 14:04:04 +10006923static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006924os_getgid_impl(PyObject *module)
6925/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006926{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006927 return _PyLong_FromGid(getgid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006928}
Larry Hastings2f936352014-08-05 14:04:04 +10006929#endif /* HAVE_GETGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006930
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006931
Berker Peksag39404992016-09-15 20:45:16 +03006932#ifdef HAVE_GETPID
Larry Hastings2f936352014-08-05 14:04:04 +10006933/*[clinic input]
6934os.getpid
6935
6936Return the current process id.
6937[clinic start generated code]*/
6938
Larry Hastings2f936352014-08-05 14:04:04 +10006939static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006940os_getpid_impl(PyObject *module)
6941/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006942{
Victor Stinner8c62be82010-05-06 00:08:46 +00006943 return PyLong_FromPid(getpid());
Guido van Rossum85e3b011991-06-03 12:42:10 +00006944}
Berker Peksag39404992016-09-15 20:45:16 +03006945#endif /* HAVE_GETPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00006946
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07006947#ifdef NGROUPS_MAX
6948#define MAX_GROUPS NGROUPS_MAX
6949#else
6950 /* defined to be 16 on Solaris7, so this should be a small number */
6951#define MAX_GROUPS 64
6952#endif
6953
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006954#ifdef HAVE_GETGROUPLIST
Larry Hastings2f936352014-08-05 14:04:04 +10006955
6956/* AC 3.5: funny apple logic below */
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006957PyDoc_STRVAR(posix_getgrouplist__doc__,
6958"getgrouplist(user, group) -> list of groups to which a user belongs\n\n\
6959Returns a list of groups to which a user belongs.\n\n\
6960 user: username to lookup\n\
6961 group: base group id of the user");
6962
6963static PyObject *
6964posix_getgrouplist(PyObject *self, PyObject *args)
6965{
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006966 const char *user;
6967 int i, ngroups;
6968 PyObject *list;
6969#ifdef __APPLE__
6970 int *groups, basegid;
6971#else
6972 gid_t *groups, basegid;
6973#endif
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07006974
6975 /*
6976 * NGROUPS_MAX is defined by POSIX.1 as the maximum
6977 * number of supplimental groups a users can belong to.
6978 * We have to increment it by one because
6979 * getgrouplist() returns both the supplemental groups
6980 * and the primary group, i.e. all of the groups the
6981 * user belongs to.
6982 */
6983 ngroups = 1 + MAX_GROUPS;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006984
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006985#ifdef __APPLE__
6986 if (!PyArg_ParseTuple(args, "si:getgrouplist", &user, &basegid))
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006987 return NULL;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006988#else
6989 if (!PyArg_ParseTuple(args, "sO&:getgrouplist", &user,
6990 _Py_Gid_Converter, &basegid))
6991 return NULL;
6992#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006993
6994#ifdef __APPLE__
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006995 groups = PyMem_New(int, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006996#else
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006997 groups = PyMem_New(gid_t, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006998#endif
6999 if (groups == NULL)
7000 return PyErr_NoMemory();
7001
7002 if (getgrouplist(user, basegid, groups, &ngroups) == -1) {
7003 PyMem_Del(groups);
7004 return posix_error();
7005 }
7006
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08007007#ifdef _Py_MEMORY_SANITIZER
7008 /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
7009 __msan_unpoison(&ngroups, sizeof(ngroups));
7010 __msan_unpoison(groups, ngroups*sizeof(*groups));
7011#endif
7012
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007013 list = PyList_New(ngroups);
7014 if (list == NULL) {
7015 PyMem_Del(groups);
7016 return NULL;
7017 }
7018
7019 for (i = 0; i < ngroups; i++) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007020#ifdef __APPLE__
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007021 PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007022#else
7023 PyObject *o = _PyLong_FromGid(groups[i]);
7024#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007025 if (o == NULL) {
7026 Py_DECREF(list);
7027 PyMem_Del(groups);
7028 return NULL;
7029 }
7030 PyList_SET_ITEM(list, i, o);
7031 }
7032
7033 PyMem_Del(groups);
7034
7035 return list;
7036}
Larry Hastings2f936352014-08-05 14:04:04 +10007037#endif /* HAVE_GETGROUPLIST */
7038
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007039
Fred Drakec9680921999-12-13 16:37:25 +00007040#ifdef HAVE_GETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007041/*[clinic input]
7042os.getgroups
7043
7044Return list of supplemental group IDs for the process.
7045[clinic start generated code]*/
7046
Larry Hastings2f936352014-08-05 14:04:04 +10007047static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007048os_getgroups_impl(PyObject *module)
7049/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
Fred Drakec9680921999-12-13 16:37:25 +00007050{
7051 PyObject *result = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00007052 gid_t grouplist[MAX_GROUPS];
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007053
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007054 /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007055 * This is a helper variable to store the intermediate result when
7056 * that happens.
7057 *
7058 * To keep the code readable the OSX behaviour is unconditional,
7059 * according to the POSIX spec this should be safe on all unix-y
7060 * systems.
7061 */
7062 gid_t* alt_grouplist = grouplist;
Victor Stinner8c62be82010-05-06 00:08:46 +00007063 int n;
Fred Drakec9680921999-12-13 16:37:25 +00007064
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007065#ifdef __APPLE__
7066 /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
7067 * there are more groups than can fit in grouplist. Therefore, on OS X
7068 * always first call getgroups with length 0 to get the actual number
7069 * of groups.
7070 */
7071 n = getgroups(0, NULL);
7072 if (n < 0) {
7073 return posix_error();
7074 } else if (n <= MAX_GROUPS) {
7075 /* groups will fit in existing array */
7076 alt_grouplist = grouplist;
7077 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02007078 alt_grouplist = PyMem_New(gid_t, n);
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007079 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07007080 return PyErr_NoMemory();
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007081 }
7082 }
7083
7084 n = getgroups(n, alt_grouplist);
7085 if (n == -1) {
7086 if (alt_grouplist != grouplist) {
7087 PyMem_Free(alt_grouplist);
7088 }
7089 return posix_error();
7090 }
7091#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007092 n = getgroups(MAX_GROUPS, grouplist);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007093 if (n < 0) {
7094 if (errno == EINVAL) {
7095 n = getgroups(0, NULL);
7096 if (n == -1) {
7097 return posix_error();
7098 }
7099 if (n == 0) {
7100 /* Avoid malloc(0) */
7101 alt_grouplist = grouplist;
7102 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02007103 alt_grouplist = PyMem_New(gid_t, n);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007104 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07007105 return PyErr_NoMemory();
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007106 }
7107 n = getgroups(n, alt_grouplist);
7108 if (n == -1) {
7109 PyMem_Free(alt_grouplist);
7110 return posix_error();
7111 }
7112 }
7113 } else {
7114 return posix_error();
7115 }
7116 }
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007117#endif
7118
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007119 result = PyList_New(n);
7120 if (result != NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007121 int i;
7122 for (i = 0; i < n; ++i) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007123 PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
Victor Stinner8c62be82010-05-06 00:08:46 +00007124 if (o == NULL) {
Stefan Krah0e803b32010-11-26 16:16:47 +00007125 Py_DECREF(result);
7126 result = NULL;
7127 break;
Fred Drakec9680921999-12-13 16:37:25 +00007128 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007129 PyList_SET_ITEM(result, i, o);
Fred Drakec9680921999-12-13 16:37:25 +00007130 }
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007131 }
7132
7133 if (alt_grouplist != grouplist) {
7134 PyMem_Free(alt_grouplist);
Victor Stinner8c62be82010-05-06 00:08:46 +00007135 }
Neal Norwitze241ce82003-02-17 18:17:05 +00007136
Fred Drakec9680921999-12-13 16:37:25 +00007137 return result;
7138}
Larry Hastings2f936352014-08-05 14:04:04 +10007139#endif /* HAVE_GETGROUPS */
Fred Drakec9680921999-12-13 16:37:25 +00007140
Antoine Pitroub7572f02009-12-02 20:46:48 +00007141#ifdef HAVE_INITGROUPS
7142PyDoc_STRVAR(posix_initgroups__doc__,
7143"initgroups(username, gid) -> None\n\n\
7144Call the system initgroups() to initialize the group access list with all of\n\
7145the groups of which the specified username is a member, plus the specified\n\
7146group id.");
7147
Larry Hastings2f936352014-08-05 14:04:04 +10007148/* AC 3.5: funny apple logic */
Antoine Pitroub7572f02009-12-02 20:46:48 +00007149static PyObject *
7150posix_initgroups(PyObject *self, PyObject *args)
7151{
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007152 PyObject *oname;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03007153 const char *username;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007154 int res;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007155#ifdef __APPLE__
7156 int gid;
7157#else
7158 gid_t gid;
7159#endif
Antoine Pitroub7572f02009-12-02 20:46:48 +00007160
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007161#ifdef __APPLE__
7162 if (!PyArg_ParseTuple(args, "O&i:initgroups",
7163 PyUnicode_FSConverter, &oname,
7164 &gid))
7165#else
7166 if (!PyArg_ParseTuple(args, "O&O&:initgroups",
7167 PyUnicode_FSConverter, &oname,
7168 _Py_Gid_Converter, &gid))
7169#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00007170 return NULL;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007171 username = PyBytes_AS_STRING(oname);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007172
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007173 res = initgroups(username, gid);
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007174 Py_DECREF(oname);
7175 if (res == -1)
Victor Stinner8c62be82010-05-06 00:08:46 +00007176 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007177
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007178 Py_RETURN_NONE;
Antoine Pitroub7572f02009-12-02 20:46:48 +00007179}
Larry Hastings2f936352014-08-05 14:04:04 +10007180#endif /* HAVE_INITGROUPS */
7181
Antoine Pitroub7572f02009-12-02 20:46:48 +00007182
Martin v. Löwis606edc12002-06-13 21:09:11 +00007183#ifdef HAVE_GETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10007184/*[clinic input]
7185os.getpgid
7186
7187 pid: pid_t
7188
7189Call the system call getpgid(), and return the result.
7190[clinic start generated code]*/
7191
Larry Hastings2f936352014-08-05 14:04:04 +10007192static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007193os_getpgid_impl(PyObject *module, pid_t pid)
7194/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007195{
7196 pid_t pgid = getpgid(pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007197 if (pgid < 0)
7198 return posix_error();
7199 return PyLong_FromPid(pgid);
Martin v. Löwis606edc12002-06-13 21:09:11 +00007200}
7201#endif /* HAVE_GETPGID */
7202
7203
Guido van Rossumb6775db1994-08-01 11:34:53 +00007204#ifdef HAVE_GETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007205/*[clinic input]
7206os.getpgrp
7207
7208Return the current process group id.
7209[clinic start generated code]*/
7210
Larry Hastings2f936352014-08-05 14:04:04 +10007211static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007212os_getpgrp_impl(PyObject *module)
7213/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
Guido van Rossum04814471991-06-04 20:23:49 +00007214{
Guido van Rossumb6775db1994-08-01 11:34:53 +00007215#ifdef GETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007216 return PyLong_FromPid(getpgrp(0));
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007217#else /* GETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007218 return PyLong_FromPid(getpgrp());
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007219#endif /* GETPGRP_HAVE_ARG */
Guido van Rossum04814471991-06-04 20:23:49 +00007220}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007221#endif /* HAVE_GETPGRP */
Guido van Rossum04814471991-06-04 20:23:49 +00007222
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007223
Guido van Rossumb6775db1994-08-01 11:34:53 +00007224#ifdef HAVE_SETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007225/*[clinic input]
7226os.setpgrp
7227
7228Make the current process the leader of its process group.
7229[clinic start generated code]*/
7230
Larry Hastings2f936352014-08-05 14:04:04 +10007231static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007232os_setpgrp_impl(PyObject *module)
7233/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00007234{
Guido van Rossum64933891994-10-20 21:56:42 +00007235#ifdef SETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007236 if (setpgrp(0, 0) < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007237#else /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007238 if (setpgrp() < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007239#endif /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007240 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007241 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00007242}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007243#endif /* HAVE_SETPGRP */
7244
Guido van Rossumad0ee831995-03-01 10:34:45 +00007245#ifdef HAVE_GETPPID
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007246
7247#ifdef MS_WINDOWS
7248#include <tlhelp32.h>
7249
7250static PyObject*
7251win32_getppid()
7252{
7253 HANDLE snapshot;
7254 pid_t mypid;
7255 PyObject* result = NULL;
7256 BOOL have_record;
7257 PROCESSENTRY32 pe;
7258
7259 mypid = getpid(); /* This function never fails */
7260
7261 snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
7262 if (snapshot == INVALID_HANDLE_VALUE)
7263 return PyErr_SetFromWindowsErr(GetLastError());
7264
7265 pe.dwSize = sizeof(pe);
7266 have_record = Process32First(snapshot, &pe);
7267 while (have_record) {
7268 if (mypid == (pid_t)pe.th32ProcessID) {
7269 /* We could cache the ulong value in a static variable. */
7270 result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
7271 break;
7272 }
7273
7274 have_record = Process32Next(snapshot, &pe);
7275 }
7276
7277 /* If our loop exits and our pid was not found (result will be NULL)
7278 * then GetLastError will return ERROR_NO_MORE_FILES. This is an
7279 * error anyway, so let's raise it. */
7280 if (!result)
7281 result = PyErr_SetFromWindowsErr(GetLastError());
7282
7283 CloseHandle(snapshot);
7284
7285 return result;
7286}
7287#endif /*MS_WINDOWS*/
7288
Larry Hastings2f936352014-08-05 14:04:04 +10007289
7290/*[clinic input]
7291os.getppid
7292
7293Return the parent's process id.
7294
7295If the parent process has already exited, Windows machines will still
7296return its id; others systems will return the id of the 'init' process (1).
7297[clinic start generated code]*/
7298
Larry Hastings2f936352014-08-05 14:04:04 +10007299static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007300os_getppid_impl(PyObject *module)
7301/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00007302{
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007303#ifdef MS_WINDOWS
7304 return win32_getppid();
7305#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007306 return PyLong_FromPid(getppid());
Guido van Rossumad0ee831995-03-01 10:34:45 +00007307#endif
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007308}
7309#endif /* HAVE_GETPPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007310
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007311
Fred Drake12c6e2d1999-12-14 21:25:03 +00007312#ifdef HAVE_GETLOGIN
Larry Hastings2f936352014-08-05 14:04:04 +10007313/*[clinic input]
7314os.getlogin
7315
7316Return the actual login name.
7317[clinic start generated code]*/
7318
Larry Hastings2f936352014-08-05 14:04:04 +10007319static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007320os_getlogin_impl(PyObject *module)
7321/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
Fred Drake12c6e2d1999-12-14 21:25:03 +00007322{
Victor Stinner8c62be82010-05-06 00:08:46 +00007323 PyObject *result = NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007324#ifdef MS_WINDOWS
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007325 wchar_t user_name[UNLEN + 1];
Victor Stinner63941882011-09-29 00:42:28 +02007326 DWORD num_chars = Py_ARRAY_LENGTH(user_name);
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007327
7328 if (GetUserNameW(user_name, &num_chars)) {
7329 /* num_chars is the number of unicode chars plus null terminator */
7330 result = PyUnicode_FromWideChar(user_name, num_chars - 1);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007331 }
7332 else
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007333 result = PyErr_SetFromWindowsErr(GetLastError());
7334#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007335 char *name;
7336 int old_errno = errno;
Fred Drake12c6e2d1999-12-14 21:25:03 +00007337
Victor Stinner8c62be82010-05-06 00:08:46 +00007338 errno = 0;
7339 name = getlogin();
7340 if (name == NULL) {
7341 if (errno)
Victor Stinnere039ffe2010-08-15 09:33:08 +00007342 posix_error();
Fred Drake12c6e2d1999-12-14 21:25:03 +00007343 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007344 PyErr_SetString(PyExc_OSError, "unable to determine login name");
Victor Stinner8c62be82010-05-06 00:08:46 +00007345 }
7346 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007347 result = PyUnicode_DecodeFSDefault(name);
Victor Stinner8c62be82010-05-06 00:08:46 +00007348 errno = old_errno;
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007349#endif
Fred Drake12c6e2d1999-12-14 21:25:03 +00007350 return result;
7351}
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007352#endif /* HAVE_GETLOGIN */
Fred Drake12c6e2d1999-12-14 21:25:03 +00007353
Larry Hastings2f936352014-08-05 14:04:04 +10007354
Guido van Rossumad0ee831995-03-01 10:34:45 +00007355#ifdef HAVE_GETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007356/*[clinic input]
7357os.getuid
7358
7359Return the current process's user id.
7360[clinic start generated code]*/
7361
Larry Hastings2f936352014-08-05 14:04:04 +10007362static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007363os_getuid_impl(PyObject *module)
7364/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00007365{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007366 return _PyLong_FromUid(getuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00007367}
Larry Hastings2f936352014-08-05 14:04:04 +10007368#endif /* HAVE_GETUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00007369
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007370
Brian Curtineb24d742010-04-12 17:16:38 +00007371#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007372#define HAVE_KILL
7373#endif /* MS_WINDOWS */
7374
7375#ifdef HAVE_KILL
7376/*[clinic input]
7377os.kill
7378
7379 pid: pid_t
7380 signal: Py_ssize_t
7381 /
7382
7383Kill a process with a signal.
7384[clinic start generated code]*/
7385
Larry Hastings2f936352014-08-05 14:04:04 +10007386static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007387os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
7388/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007389{
Saiyang Gou7514f4f2020-02-12 23:47:42 -08007390 if (PySys_Audit("os.kill", "in", pid, signal) < 0) {
7391 return NULL;
7392 }
7393#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007394 if (kill(pid, (int)signal) == -1)
7395 return posix_error();
7396 Py_RETURN_NONE;
Larry Hastings2f936352014-08-05 14:04:04 +10007397#else /* !MS_WINDOWS */
Amaury Forgeot d'Arc0a589c92010-05-15 20:35:12 +00007398 PyObject *result;
Larry Hastings2f936352014-08-05 14:04:04 +10007399 DWORD sig = (DWORD)signal;
7400 DWORD err;
Victor Stinner8c62be82010-05-06 00:08:46 +00007401 HANDLE handle;
Brian Curtineb24d742010-04-12 17:16:38 +00007402
Victor Stinner8c62be82010-05-06 00:08:46 +00007403 /* Console processes which share a common console can be sent CTRL+C or
7404 CTRL+BREAK events, provided they handle said events. */
7405 if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007406 if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007407 err = GetLastError();
7408 PyErr_SetFromWindowsErr(err);
7409 }
7410 else
7411 Py_RETURN_NONE;
7412 }
Brian Curtineb24d742010-04-12 17:16:38 +00007413
Victor Stinner8c62be82010-05-06 00:08:46 +00007414 /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
7415 attempt to open and terminate the process. */
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007416 handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007417 if (handle == NULL) {
7418 err = GetLastError();
7419 return PyErr_SetFromWindowsErr(err);
7420 }
Brian Curtineb24d742010-04-12 17:16:38 +00007421
Victor Stinner8c62be82010-05-06 00:08:46 +00007422 if (TerminateProcess(handle, sig) == 0) {
7423 err = GetLastError();
7424 result = PyErr_SetFromWindowsErr(err);
7425 } else {
7426 Py_INCREF(Py_None);
7427 result = Py_None;
7428 }
Brian Curtineb24d742010-04-12 17:16:38 +00007429
Victor Stinner8c62be82010-05-06 00:08:46 +00007430 CloseHandle(handle);
7431 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10007432#endif /* !MS_WINDOWS */
Saiyang Gou7514f4f2020-02-12 23:47:42 -08007433}
Larry Hastings2f936352014-08-05 14:04:04 +10007434#endif /* HAVE_KILL */
7435
7436
7437#ifdef HAVE_KILLPG
7438/*[clinic input]
7439os.killpg
7440
7441 pgid: pid_t
7442 signal: int
7443 /
7444
7445Kill a process group with a signal.
7446[clinic start generated code]*/
7447
Larry Hastings2f936352014-08-05 14:04:04 +10007448static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007449os_killpg_impl(PyObject *module, pid_t pgid, int signal)
7450/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007451{
Saiyang Gou7514f4f2020-02-12 23:47:42 -08007452 if (PySys_Audit("os.killpg", "ii", pgid, signal) < 0) {
7453 return NULL;
7454 }
Larry Hastings2f936352014-08-05 14:04:04 +10007455 /* XXX some man pages make the `pgid` parameter an int, others
7456 a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
7457 take the same type. Moreover, pid_t is always at least as wide as
7458 int (else compilation of this module fails), which is safe. */
7459 if (killpg(pgid, signal) == -1)
7460 return posix_error();
7461 Py_RETURN_NONE;
7462}
7463#endif /* HAVE_KILLPG */
7464
Brian Curtineb24d742010-04-12 17:16:38 +00007465
Guido van Rossumc0125471996-06-28 18:55:32 +00007466#ifdef HAVE_PLOCK
Guido van Rossumc0125471996-06-28 18:55:32 +00007467#ifdef HAVE_SYS_LOCK_H
7468#include <sys/lock.h>
7469#endif
7470
Larry Hastings2f936352014-08-05 14:04:04 +10007471/*[clinic input]
7472os.plock
7473 op: int
7474 /
7475
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007476Lock program segments into memory.");
Larry Hastings2f936352014-08-05 14:04:04 +10007477[clinic start generated code]*/
7478
Larry Hastings2f936352014-08-05 14:04:04 +10007479static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007480os_plock_impl(PyObject *module, int op)
7481/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007482{
Victor Stinner8c62be82010-05-06 00:08:46 +00007483 if (plock(op) == -1)
7484 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007485 Py_RETURN_NONE;
Guido van Rossumc0125471996-06-28 18:55:32 +00007486}
Larry Hastings2f936352014-08-05 14:04:04 +10007487#endif /* HAVE_PLOCK */
7488
Guido van Rossumc0125471996-06-28 18:55:32 +00007489
Guido van Rossumb6775db1994-08-01 11:34:53 +00007490#ifdef HAVE_SETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007491/*[clinic input]
7492os.setuid
7493
7494 uid: uid_t
7495 /
7496
7497Set the current process's user id.
7498[clinic start generated code]*/
7499
Larry Hastings2f936352014-08-05 14:04:04 +10007500static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007501os_setuid_impl(PyObject *module, uid_t uid)
7502/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007503{
Victor Stinner8c62be82010-05-06 00:08:46 +00007504 if (setuid(uid) < 0)
7505 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007506 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007507}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007508#endif /* HAVE_SETUID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007509
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007510
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007511#ifdef HAVE_SETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10007512/*[clinic input]
7513os.seteuid
7514
7515 euid: uid_t
7516 /
7517
7518Set the current process's effective user id.
7519[clinic start generated code]*/
7520
Larry Hastings2f936352014-08-05 14:04:04 +10007521static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007522os_seteuid_impl(PyObject *module, uid_t euid)
7523/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007524{
7525 if (seteuid(euid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007526 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007527 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007528}
7529#endif /* HAVE_SETEUID */
7530
Larry Hastings2f936352014-08-05 14:04:04 +10007531
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007532#ifdef HAVE_SETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10007533/*[clinic input]
7534os.setegid
7535
7536 egid: gid_t
7537 /
7538
7539Set the current process's effective group id.
7540[clinic start generated code]*/
7541
Larry Hastings2f936352014-08-05 14:04:04 +10007542static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007543os_setegid_impl(PyObject *module, gid_t egid)
7544/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007545{
7546 if (setegid(egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007547 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007548 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007549}
7550#endif /* HAVE_SETEGID */
7551
Larry Hastings2f936352014-08-05 14:04:04 +10007552
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007553#ifdef HAVE_SETREUID
Larry Hastings2f936352014-08-05 14:04:04 +10007554/*[clinic input]
7555os.setreuid
7556
7557 ruid: uid_t
7558 euid: uid_t
7559 /
7560
7561Set the current process's real and effective user ids.
7562[clinic start generated code]*/
7563
Larry Hastings2f936352014-08-05 14:04:04 +10007564static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007565os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
7566/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007567{
Victor Stinner8c62be82010-05-06 00:08:46 +00007568 if (setreuid(ruid, euid) < 0) {
7569 return posix_error();
7570 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007571 Py_RETURN_NONE;
Victor Stinner8c62be82010-05-06 00:08:46 +00007572 }
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007573}
7574#endif /* HAVE_SETREUID */
7575
Larry Hastings2f936352014-08-05 14:04:04 +10007576
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007577#ifdef HAVE_SETREGID
Larry Hastings2f936352014-08-05 14:04:04 +10007578/*[clinic input]
7579os.setregid
7580
7581 rgid: gid_t
7582 egid: gid_t
7583 /
7584
7585Set the current process's real and effective group ids.
7586[clinic start generated code]*/
7587
Larry Hastings2f936352014-08-05 14:04:04 +10007588static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007589os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
7590/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007591{
7592 if (setregid(rgid, egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007593 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007594 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007595}
7596#endif /* HAVE_SETREGID */
7597
Larry Hastings2f936352014-08-05 14:04:04 +10007598
Guido van Rossumb6775db1994-08-01 11:34:53 +00007599#ifdef HAVE_SETGID
Larry Hastings2f936352014-08-05 14:04:04 +10007600/*[clinic input]
7601os.setgid
7602 gid: gid_t
7603 /
7604
7605Set the current process's group id.
7606[clinic start generated code]*/
7607
Larry Hastings2f936352014-08-05 14:04:04 +10007608static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007609os_setgid_impl(PyObject *module, gid_t gid)
7610/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007611{
Victor Stinner8c62be82010-05-06 00:08:46 +00007612 if (setgid(gid) < 0)
7613 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007614 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007615}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007616#endif /* HAVE_SETGID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007617
Larry Hastings2f936352014-08-05 14:04:04 +10007618
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007619#ifdef HAVE_SETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007620/*[clinic input]
7621os.setgroups
7622
7623 groups: object
7624 /
7625
7626Set the groups of the current process to list.
7627[clinic start generated code]*/
7628
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007629static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007630os_setgroups(PyObject *module, PyObject *groups)
7631/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007632{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007633 Py_ssize_t i, len;
Victor Stinner8c62be82010-05-06 00:08:46 +00007634 gid_t grouplist[MAX_GROUPS];
Tim Peters5aa91602002-01-30 05:46:57 +00007635
Victor Stinner8c62be82010-05-06 00:08:46 +00007636 if (!PySequence_Check(groups)) {
7637 PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
7638 return NULL;
7639 }
7640 len = PySequence_Size(groups);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007641 if (len < 0) {
7642 return NULL;
7643 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007644 if (len > MAX_GROUPS) {
7645 PyErr_SetString(PyExc_ValueError, "too many groups");
7646 return NULL;
7647 }
7648 for(i = 0; i < len; i++) {
7649 PyObject *elem;
7650 elem = PySequence_GetItem(groups, i);
7651 if (!elem)
7652 return NULL;
7653 if (!PyLong_Check(elem)) {
7654 PyErr_SetString(PyExc_TypeError,
7655 "groups must be integers");
7656 Py_DECREF(elem);
7657 return NULL;
7658 } else {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007659 if (!_Py_Gid_Converter(elem, &grouplist[i])) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007660 Py_DECREF(elem);
7661 return NULL;
7662 }
7663 }
7664 Py_DECREF(elem);
7665 }
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007666
Victor Stinner8c62be82010-05-06 00:08:46 +00007667 if (setgroups(len, grouplist) < 0)
7668 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007669 Py_RETURN_NONE;
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007670}
7671#endif /* HAVE_SETGROUPS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007672
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007673#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
7674static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +01007675wait_helper(pid_t pid, int status, struct rusage *ru)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007676{
Victor Stinner8c62be82010-05-06 00:08:46 +00007677 PyObject *result;
Eddie Elizondob3966632019-11-05 07:16:14 -08007678 PyObject *struct_rusage;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007679
Victor Stinner8c62be82010-05-06 00:08:46 +00007680 if (pid == -1)
7681 return posix_error();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007682
Zackery Spytz682107c2019-09-09 09:48:32 -06007683 // If wait succeeded but no child was ready to report status, ru will not
7684 // have been populated.
7685 if (pid == 0) {
7686 memset(ru, 0, sizeof(*ru));
7687 }
7688
Eddie Elizondob3966632019-11-05 07:16:14 -08007689 PyObject *m = PyImport_ImportModuleNoBlock("resource");
7690 if (m == NULL)
7691 return NULL;
7692 struct_rusage = PyObject_GetAttr(m, _posixstate_global->struct_rusage);
7693 Py_DECREF(m);
7694 if (struct_rusage == NULL)
7695 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007696
Victor Stinner8c62be82010-05-06 00:08:46 +00007697 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
7698 result = PyStructSequence_New((PyTypeObject*) struct_rusage);
Eddie Elizondoe4db1f02019-11-25 19:07:37 -08007699 Py_DECREF(struct_rusage);
Victor Stinner8c62be82010-05-06 00:08:46 +00007700 if (!result)
7701 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007702
7703#ifndef doubletime
7704#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
7705#endif
7706
Victor Stinner8c62be82010-05-06 00:08:46 +00007707 PyStructSequence_SET_ITEM(result, 0,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007708 PyFloat_FromDouble(doubletime(ru->ru_utime)));
Victor Stinner8c62be82010-05-06 00:08:46 +00007709 PyStructSequence_SET_ITEM(result, 1,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007710 PyFloat_FromDouble(doubletime(ru->ru_stime)));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007711#define SET_INT(result, index, value)\
Victor Stinner8c62be82010-05-06 00:08:46 +00007712 PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
7713 SET_INT(result, 2, ru->ru_maxrss);
7714 SET_INT(result, 3, ru->ru_ixrss);
7715 SET_INT(result, 4, ru->ru_idrss);
7716 SET_INT(result, 5, ru->ru_isrss);
7717 SET_INT(result, 6, ru->ru_minflt);
7718 SET_INT(result, 7, ru->ru_majflt);
7719 SET_INT(result, 8, ru->ru_nswap);
7720 SET_INT(result, 9, ru->ru_inblock);
7721 SET_INT(result, 10, ru->ru_oublock);
7722 SET_INT(result, 11, ru->ru_msgsnd);
7723 SET_INT(result, 12, ru->ru_msgrcv);
7724 SET_INT(result, 13, ru->ru_nsignals);
7725 SET_INT(result, 14, ru->ru_nvcsw);
7726 SET_INT(result, 15, ru->ru_nivcsw);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007727#undef SET_INT
7728
Victor Stinner8c62be82010-05-06 00:08:46 +00007729 if (PyErr_Occurred()) {
7730 Py_DECREF(result);
7731 return NULL;
7732 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007733
Victor Stinner8c62be82010-05-06 00:08:46 +00007734 return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007735}
7736#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
7737
Larry Hastings2f936352014-08-05 14:04:04 +10007738
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007739#ifdef HAVE_WAIT3
Larry Hastings2f936352014-08-05 14:04:04 +10007740/*[clinic input]
7741os.wait3
7742
7743 options: int
7744Wait for completion of a child process.
7745
7746Returns a tuple of information about the child process:
7747 (pid, status, rusage)
7748[clinic start generated code]*/
7749
Larry Hastings2f936352014-08-05 14:04:04 +10007750static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007751os_wait3_impl(PyObject *module, int options)
7752/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007753{
Victor Stinner8c62be82010-05-06 00:08:46 +00007754 pid_t pid;
Victor Stinner8c62be82010-05-06 00:08:46 +00007755 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007756 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007757 WAIT_TYPE status;
7758 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007759
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007760 do {
7761 Py_BEGIN_ALLOW_THREADS
7762 pid = wait3(&status, options, &ru);
7763 Py_END_ALLOW_THREADS
7764 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7765 if (pid < 0)
7766 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007767
Victor Stinner4195b5c2012-02-08 23:03:19 +01007768 return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007769}
7770#endif /* HAVE_WAIT3 */
7771
Larry Hastings2f936352014-08-05 14:04:04 +10007772
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007773#ifdef HAVE_WAIT4
Larry Hastings2f936352014-08-05 14:04:04 +10007774/*[clinic input]
7775
7776os.wait4
7777
7778 pid: pid_t
7779 options: int
7780
7781Wait for completion of a specific child process.
7782
7783Returns a tuple of information about the child process:
7784 (pid, status, rusage)
7785[clinic start generated code]*/
7786
Larry Hastings2f936352014-08-05 14:04:04 +10007787static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007788os_wait4_impl(PyObject *module, pid_t pid, int options)
7789/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007790{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007791 pid_t res;
Victor Stinner8c62be82010-05-06 00:08:46 +00007792 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007793 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007794 WAIT_TYPE status;
7795 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007796
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007797 do {
7798 Py_BEGIN_ALLOW_THREADS
7799 res = wait4(pid, &status, options, &ru);
7800 Py_END_ALLOW_THREADS
7801 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7802 if (res < 0)
7803 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007804
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007805 return wait_helper(res, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007806}
7807#endif /* HAVE_WAIT4 */
7808
Larry Hastings2f936352014-08-05 14:04:04 +10007809
Ross Lagerwall7807c352011-03-17 20:20:30 +02007810#if defined(HAVE_WAITID) && !defined(__APPLE__)
Larry Hastings2f936352014-08-05 14:04:04 +10007811/*[clinic input]
7812os.waitid
7813
7814 idtype: idtype_t
7815 Must be one of be P_PID, P_PGID or P_ALL.
7816 id: id_t
7817 The id to wait on.
7818 options: int
7819 Constructed from the ORing of one or more of WEXITED, WSTOPPED
7820 or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
7821 /
7822
7823Returns the result of waiting for a process or processes.
7824
7825Returns either waitid_result or None if WNOHANG is specified and there are
7826no children in a waitable state.
7827[clinic start generated code]*/
7828
Larry Hastings2f936352014-08-05 14:04:04 +10007829static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007830os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
7831/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007832{
7833 PyObject *result;
7834 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007835 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007836 siginfo_t si;
7837 si.si_pid = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007838
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007839 do {
7840 Py_BEGIN_ALLOW_THREADS
7841 res = waitid(idtype, id, &si, options);
7842 Py_END_ALLOW_THREADS
7843 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7844 if (res < 0)
7845 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007846
7847 if (si.si_pid == 0)
7848 Py_RETURN_NONE;
7849
Hai Shif707d942020-03-16 21:15:01 +08007850 PyObject *WaitidResultType = get_posix_state(module)->WaitidResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -08007851 result = PyStructSequence_New((PyTypeObject *)WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +02007852 if (!result)
7853 return NULL;
7854
7855 PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007856 PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
Ross Lagerwall7807c352011-03-17 20:20:30 +02007857 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
7858 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
7859 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
7860 if (PyErr_Occurred()) {
7861 Py_DECREF(result);
7862 return NULL;
7863 }
7864
7865 return result;
7866}
Larry Hastings2f936352014-08-05 14:04:04 +10007867#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
Ross Lagerwall7807c352011-03-17 20:20:30 +02007868
Larry Hastings2f936352014-08-05 14:04:04 +10007869
7870#if defined(HAVE_WAITPID)
7871/*[clinic input]
7872os.waitpid
7873 pid: pid_t
7874 options: int
7875 /
7876
7877Wait for completion of a given child process.
7878
7879Returns a tuple of information regarding the child process:
7880 (pid, status)
7881
7882The options argument is ignored on Windows.
7883[clinic start generated code]*/
7884
Larry Hastings2f936352014-08-05 14:04:04 +10007885static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007886os_waitpid_impl(PyObject *module, pid_t pid, int options)
7887/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007888{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007889 pid_t res;
7890 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007891 WAIT_TYPE status;
7892 WAIT_STATUS_INT(status) = 0;
Guido van Rossum54ecc3d1999-01-27 17:53:11 +00007893
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007894 do {
7895 Py_BEGIN_ALLOW_THREADS
7896 res = waitpid(pid, &status, options);
7897 Py_END_ALLOW_THREADS
7898 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7899 if (res < 0)
7900 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007901
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007902 return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
Guido van Rossum21803b81992-08-09 12:55:27 +00007903}
Tim Petersab034fa2002-02-01 11:27:43 +00007904#elif defined(HAVE_CWAIT)
Tim Petersab034fa2002-02-01 11:27:43 +00007905/* MS C has a variant of waitpid() that's usable for most purposes. */
Larry Hastings2f936352014-08-05 14:04:04 +10007906/*[clinic input]
7907os.waitpid
Benjamin Petersonca470632016-09-06 13:47:26 -07007908 pid: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +10007909 options: int
7910 /
7911
7912Wait for completion of a given process.
7913
7914Returns a tuple of information regarding the process:
7915 (pid, status << 8)
7916
7917The options argument is ignored on Windows.
7918[clinic start generated code]*/
7919
Larry Hastings2f936352014-08-05 14:04:04 +10007920static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -07007921os_waitpid_impl(PyObject *module, intptr_t pid, int options)
Victor Stinner581139c2016-09-06 15:54:20 -07007922/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007923{
7924 int status;
Benjamin Petersonca470632016-09-06 13:47:26 -07007925 intptr_t res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007926 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007927
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007928 do {
7929 Py_BEGIN_ALLOW_THREADS
Steve Dower11f43262016-11-19 18:33:39 -08007930 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007931 res = _cwait(&status, pid, options);
Steve Dower11f43262016-11-19 18:33:39 -08007932 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007933 Py_END_ALLOW_THREADS
7934 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinnerd3ffd322015-09-15 10:11:03 +02007935 if (res < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007936 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007937
Victor Stinner8c62be82010-05-06 00:08:46 +00007938 /* shift the status left a byte so this is more like the POSIX waitpid */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007939 return Py_BuildValue(_Py_PARSE_INTPTR "i", res, status << 8);
Tim Petersab034fa2002-02-01 11:27:43 +00007940}
Larry Hastings2f936352014-08-05 14:04:04 +10007941#endif
7942
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007943
Guido van Rossumad0ee831995-03-01 10:34:45 +00007944#ifdef HAVE_WAIT
Larry Hastings2f936352014-08-05 14:04:04 +10007945/*[clinic input]
7946os.wait
7947
7948Wait for completion of a child process.
7949
7950Returns a tuple of information about the child process:
7951 (pid, status)
7952[clinic start generated code]*/
7953
Larry Hastings2f936352014-08-05 14:04:04 +10007954static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007955os_wait_impl(PyObject *module)
7956/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
Guido van Rossum21803b81992-08-09 12:55:27 +00007957{
Victor Stinner8c62be82010-05-06 00:08:46 +00007958 pid_t pid;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007959 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007960 WAIT_TYPE status;
7961 WAIT_STATUS_INT(status) = 0;
Neal Norwitze241ce82003-02-17 18:17:05 +00007962
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007963 do {
7964 Py_BEGIN_ALLOW_THREADS
7965 pid = wait(&status);
7966 Py_END_ALLOW_THREADS
7967 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7968 if (pid < 0)
7969 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007970
Victor Stinner8c62be82010-05-06 00:08:46 +00007971 return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
Guido van Rossum85e3b011991-06-03 12:42:10 +00007972}
Larry Hastings2f936352014-08-05 14:04:04 +10007973#endif /* HAVE_WAIT */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007974
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -08007975#if defined(__linux__) && defined(__NR_pidfd_open)
7976/*[clinic input]
7977os.pidfd_open
7978 pid: pid_t
7979 flags: unsigned_int = 0
7980
7981Return a file descriptor referring to the process *pid*.
7982
7983The descriptor can be used to perform process management without races and
7984signals.
7985[clinic start generated code]*/
7986
7987static PyObject *
7988os_pidfd_open_impl(PyObject *module, pid_t pid, unsigned int flags)
7989/*[clinic end generated code: output=5c7252698947dc41 input=c3fd99ce947ccfef]*/
7990{
7991 int fd = syscall(__NR_pidfd_open, pid, flags);
7992 if (fd < 0) {
7993 return posix_error();
7994 }
7995 return PyLong_FromLong(fd);
7996}
7997#endif
7998
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007999
Larry Hastings9cf065c2012-06-22 16:30:09 -07008000#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008001/*[clinic input]
8002os.readlink
8003
8004 path: path_t
8005 *
8006 dir_fd: dir_fd(requires='readlinkat') = None
8007
8008Return a string representing the path to which the symbolic link points.
8009
8010If dir_fd is not None, it should be a file descriptor open to a directory,
8011and path should be relative; path will then be relative to that directory.
8012
8013dir_fd may not be implemented on your platform. If it is unavailable,
8014using it will raise a NotImplementedError.
8015[clinic start generated code]*/
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008016
Barry Warsaw53699e91996-12-10 23:23:01 +00008017static PyObject *
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008018os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
8019/*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008020{
Berker Peksage0b5b202018-08-15 13:03:41 +03008021#if defined(HAVE_READLINK)
Christian Heimes3cb091e2016-09-23 20:24:28 +02008022 char buffer[MAXPATHLEN+1];
Larry Hastings9cf065c2012-06-22 16:30:09 -07008023 ssize_t length;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008024
8025 Py_BEGIN_ALLOW_THREADS
8026#ifdef HAVE_READLINKAT
8027 if (dir_fd != DEFAULT_DIR_FD)
8028 length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
8029 else
8030#endif
8031 length = readlink(path->narrow, buffer, MAXPATHLEN);
8032 Py_END_ALLOW_THREADS
8033
8034 if (length < 0) {
8035 return path_error(path);
8036 }
8037 buffer[length] = '\0';
8038
8039 if (PyUnicode_Check(path->object))
8040 return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
8041 else
8042 return PyBytes_FromStringAndSize(buffer, length);
Berker Peksage0b5b202018-08-15 13:03:41 +03008043#elif defined(MS_WINDOWS)
8044 DWORD n_bytes_returned;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008045 DWORD io_result = 0;
Berker Peksage0b5b202018-08-15 13:03:41 +03008046 HANDLE reparse_point_handle;
Berker Peksage0b5b202018-08-15 13:03:41 +03008047 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
8048 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Steve Dower993ac922019-09-03 12:50:51 -07008049 PyObject *result = NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00008050
Larry Hastings2f936352014-08-05 14:04:04 +10008051 /* First get a handle to the reparse point */
8052 Py_BEGIN_ALLOW_THREADS
8053 reparse_point_handle = CreateFileW(
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008054 path->wide,
Larry Hastings2f936352014-08-05 14:04:04 +10008055 0,
8056 0,
8057 0,
8058 OPEN_EXISTING,
8059 FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
8060 0);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008061 if (reparse_point_handle != INVALID_HANDLE_VALUE) {
8062 /* New call DeviceIoControl to read the reparse point */
8063 io_result = DeviceIoControl(
8064 reparse_point_handle,
8065 FSCTL_GET_REPARSE_POINT,
8066 0, 0, /* in buffer */
8067 target_buffer, sizeof(target_buffer),
8068 &n_bytes_returned,
8069 0 /* we're not using OVERLAPPED_IO */
8070 );
8071 CloseHandle(reparse_point_handle);
Berker Peksage0b5b202018-08-15 13:03:41 +03008072 }
Larry Hastings2f936352014-08-05 14:04:04 +10008073 Py_END_ALLOW_THREADS
8074
Berker Peksage0b5b202018-08-15 13:03:41 +03008075 if (io_result == 0) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008076 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03008077 }
Larry Hastings2f936352014-08-05 14:04:04 +10008078
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008079 wchar_t *name = NULL;
8080 Py_ssize_t nameLen = 0;
8081 if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
Larry Hastings2f936352014-08-05 14:04:04 +10008082 {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008083 name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
8084 rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
8085 nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
Larry Hastings2f936352014-08-05 14:04:04 +10008086 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008087 else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
8088 {
8089 name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
8090 rdb->MountPointReparseBuffer.SubstituteNameOffset);
8091 nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
8092 }
8093 else
8094 {
8095 PyErr_SetString(PyExc_ValueError, "not a symbolic link");
8096 }
8097 if (name) {
8098 if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
8099 /* Our buffer is mutable, so this is okay */
8100 name[1] = L'\\';
8101 }
8102 result = PyUnicode_FromWideChar(name, nameLen);
Steve Dower993ac922019-09-03 12:50:51 -07008103 if (result && path->narrow) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008104 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
8105 }
Berker Peksage0b5b202018-08-15 13:03:41 +03008106 }
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008107 return result;
Berker Peksage0b5b202018-08-15 13:03:41 +03008108#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008109}
Berker Peksage0b5b202018-08-15 13:03:41 +03008110#endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008111
Larry Hastings9cf065c2012-06-22 16:30:09 -07008112#ifdef HAVE_SYMLINK
Larry Hastings9cf065c2012-06-22 16:30:09 -07008113
8114#if defined(MS_WINDOWS)
8115
Steve Dower6921e732018-03-05 14:26:08 -08008116/* Remove the last portion of the path - return 0 on success */
8117static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008118_dirnameW(WCHAR *path)
8119{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008120 WCHAR *ptr;
Steve Dower6921e732018-03-05 14:26:08 -08008121 size_t length = wcsnlen_s(path, MAX_PATH);
8122 if (length == MAX_PATH) {
8123 return -1;
8124 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008125
8126 /* walk the path from the end until a backslash is encountered */
Steve Dower6921e732018-03-05 14:26:08 -08008127 for(ptr = path + length; ptr != path; ptr--) {
8128 if (*ptr == L'\\' || *ptr == L'/') {
Jason R. Coombs3a092862013-05-27 23:21:28 -04008129 break;
Steve Dower6921e732018-03-05 14:26:08 -08008130 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008131 }
8132 *ptr = 0;
Steve Dower6921e732018-03-05 14:26:08 -08008133 return 0;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008134}
8135
Victor Stinner31b3b922013-06-05 01:49:17 +02008136/* Is this path absolute? */
8137static int
8138_is_absW(const WCHAR *path)
8139{
Steve Dower6921e732018-03-05 14:26:08 -08008140 return path[0] == L'\\' || path[0] == L'/' ||
8141 (path[0] && path[1] == L':');
Jason R. Coombs3a092862013-05-27 23:21:28 -04008142}
8143
Steve Dower6921e732018-03-05 14:26:08 -08008144/* join root and rest with a backslash - return 0 on success */
8145static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008146_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
8147{
Victor Stinner31b3b922013-06-05 01:49:17 +02008148 if (_is_absW(rest)) {
Steve Dower6921e732018-03-05 14:26:08 -08008149 return wcscpy_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008150 }
8151
Steve Dower6921e732018-03-05 14:26:08 -08008152 if (wcscpy_s(dest_path, MAX_PATH, root)) {
8153 return -1;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008154 }
Steve Dower6921e732018-03-05 14:26:08 -08008155
8156 if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
8157 return -1;
8158 }
8159
8160 return wcscat_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008161}
8162
Victor Stinner31b3b922013-06-05 01:49:17 +02008163/* Return True if the path at src relative to dest is a directory */
8164static int
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03008165_check_dirW(LPCWSTR src, LPCWSTR dest)
Jason R. Coombs3a092862013-05-27 23:21:28 -04008166{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008167 WIN32_FILE_ATTRIBUTE_DATA src_info;
8168 WCHAR dest_parent[MAX_PATH];
8169 WCHAR src_resolved[MAX_PATH] = L"";
8170
8171 /* dest_parent = os.path.dirname(dest) */
Steve Dower6921e732018-03-05 14:26:08 -08008172 if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
8173 _dirnameW(dest_parent)) {
8174 return 0;
8175 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008176 /* src_resolved = os.path.join(dest_parent, src) */
Steve Dower6921e732018-03-05 14:26:08 -08008177 if (_joinW(src_resolved, dest_parent, src)) {
8178 return 0;
8179 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008180 return (
8181 GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
8182 && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
8183 );
8184}
Larry Hastings9cf065c2012-06-22 16:30:09 -07008185#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008186
Larry Hastings2f936352014-08-05 14:04:04 +10008187
8188/*[clinic input]
8189os.symlink
8190 src: path_t
8191 dst: path_t
8192 target_is_directory: bool = False
8193 *
8194 dir_fd: dir_fd(requires='symlinkat')=None
8195
8196# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
8197
8198Create a symbolic link pointing to src named dst.
8199
8200target_is_directory is required on Windows if the target is to be
8201 interpreted as a directory. (On Windows, symlink requires
8202 Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
8203 target_is_directory is ignored on non-Windows platforms.
8204
8205If dir_fd is not None, it should be a file descriptor open to a directory,
8206 and path should be relative; path will then be relative to that directory.
8207dir_fd may not be implemented on your platform.
8208 If it is unavailable, using it will raise a NotImplementedError.
8209
8210[clinic start generated code]*/
8211
Larry Hastings2f936352014-08-05 14:04:04 +10008212static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008213os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
Larry Hastings89964c42015-04-14 18:07:59 -04008214 int target_is_directory, int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008215/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008216{
Larry Hastings9cf065c2012-06-22 16:30:09 -07008217#ifdef MS_WINDOWS
8218 DWORD result;
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008219 DWORD flags = 0;
8220
8221 /* Assumed true, set to false if detected to not be available. */
8222 static int windows_has_symlink_unprivileged_flag = TRUE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008223#else
8224 int result;
8225#endif
8226
Saiyang Gou7514f4f2020-02-12 23:47:42 -08008227 if (PySys_Audit("os.symlink", "OOi", src->object, dst->object,
8228 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
8229 return NULL;
8230 }
8231
Larry Hastings9cf065c2012-06-22 16:30:09 -07008232#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008233
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008234 if (windows_has_symlink_unprivileged_flag) {
8235 /* Allow non-admin symlinks if system allows it. */
8236 flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
8237 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008238
Larry Hastings9cf065c2012-06-22 16:30:09 -07008239 Py_BEGIN_ALLOW_THREADS
Steve Dower6921e732018-03-05 14:26:08 -08008240 _Py_BEGIN_SUPPRESS_IPH
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008241 /* if src is a directory, ensure flags==1 (target_is_directory bit) */
8242 if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
8243 flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
8244 }
8245
8246 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
Steve Dower6921e732018-03-05 14:26:08 -08008247 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07008248 Py_END_ALLOW_THREADS
8249
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008250 if (windows_has_symlink_unprivileged_flag && !result &&
8251 ERROR_INVALID_PARAMETER == GetLastError()) {
8252
8253 Py_BEGIN_ALLOW_THREADS
8254 _Py_BEGIN_SUPPRESS_IPH
8255 /* This error might be caused by
8256 SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
8257 Try again, and update windows_has_symlink_unprivileged_flag if we
8258 are successful this time.
8259
8260 NOTE: There is a risk of a race condition here if there are other
8261 conditions than the flag causing ERROR_INVALID_PARAMETER, and
8262 another process (or thread) changes that condition in between our
8263 calls to CreateSymbolicLink.
8264 */
8265 flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
8266 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
8267 _Py_END_SUPPRESS_IPH
8268 Py_END_ALLOW_THREADS
8269
8270 if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
8271 windows_has_symlink_unprivileged_flag = FALSE;
8272 }
8273 }
8274
Larry Hastings2f936352014-08-05 14:04:04 +10008275 if (!result)
8276 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008277
8278#else
8279
Steve Dower6921e732018-03-05 14:26:08 -08008280 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
8281 PyErr_SetString(PyExc_ValueError,
8282 "symlink: src and dst must be the same type");
8283 return NULL;
8284 }
8285
Larry Hastings9cf065c2012-06-22 16:30:09 -07008286 Py_BEGIN_ALLOW_THREADS
8287#if HAVE_SYMLINKAT
8288 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10008289 result = symlinkat(src->narrow, dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008290 else
8291#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008292 result = symlink(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008293 Py_END_ALLOW_THREADS
8294
Larry Hastings2f936352014-08-05 14:04:04 +10008295 if (result)
8296 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008297#endif
8298
Larry Hastings2f936352014-08-05 14:04:04 +10008299 Py_RETURN_NONE;
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008300}
8301#endif /* HAVE_SYMLINK */
8302
Larry Hastings9cf065c2012-06-22 16:30:09 -07008303
Brian Curtind40e6f72010-07-08 21:39:08 +00008304
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008305
Larry Hastings605a62d2012-06-24 04:33:36 -07008306static PyStructSequence_Field times_result_fields[] = {
8307 {"user", "user time"},
8308 {"system", "system time"},
8309 {"children_user", "user time of children"},
8310 {"children_system", "system time of children"},
8311 {"elapsed", "elapsed time since an arbitrary point in the past"},
8312 {NULL}
8313};
8314
8315PyDoc_STRVAR(times_result__doc__,
8316"times_result: Result from os.times().\n\n\
8317This object may be accessed either as a tuple of\n\
8318 (user, system, children_user, children_system, elapsed),\n\
8319or via the attributes user, system, children_user, children_system,\n\
8320and elapsed.\n\
8321\n\
8322See os.times for more information.");
8323
8324static PyStructSequence_Desc times_result_desc = {
8325 "times_result", /* name */
8326 times_result__doc__, /* doc */
8327 times_result_fields,
8328 5
8329};
8330
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008331#ifdef MS_WINDOWS
8332#define HAVE_TIMES /* mandatory, for the method table */
8333#endif
Larry Hastings605a62d2012-06-24 04:33:36 -07008334
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008335#ifdef HAVE_TIMES
Larry Hastings605a62d2012-06-24 04:33:36 -07008336
8337static PyObject *
8338build_times_result(double user, double system,
8339 double children_user, double children_system,
8340 double elapsed)
8341{
Eddie Elizondob3966632019-11-05 07:16:14 -08008342 PyObject *TimesResultType = _posixstate_global->TimesResultType;
8343 PyObject *value = PyStructSequence_New((PyTypeObject *)TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07008344 if (value == NULL)
8345 return NULL;
8346
8347#define SET(i, field) \
8348 { \
8349 PyObject *o = PyFloat_FromDouble(field); \
8350 if (!o) { \
8351 Py_DECREF(value); \
8352 return NULL; \
8353 } \
8354 PyStructSequence_SET_ITEM(value, i, o); \
8355 } \
8356
8357 SET(0, user);
8358 SET(1, system);
8359 SET(2, children_user);
8360 SET(3, children_system);
8361 SET(4, elapsed);
8362
8363#undef SET
8364
8365 return value;
8366}
8367
Larry Hastings605a62d2012-06-24 04:33:36 -07008368
Larry Hastings2f936352014-08-05 14:04:04 +10008369#ifndef MS_WINDOWS
8370#define NEED_TICKS_PER_SECOND
8371static long ticks_per_second = -1;
8372#endif /* MS_WINDOWS */
8373
8374/*[clinic input]
8375os.times
8376
8377Return a collection containing process timing information.
8378
8379The object returned behaves like a named tuple with these fields:
8380 (utime, stime, cutime, cstime, elapsed_time)
8381All fields are floating point numbers.
8382[clinic start generated code]*/
8383
Larry Hastings2f936352014-08-05 14:04:04 +10008384static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008385os_times_impl(PyObject *module)
8386/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008387#ifdef MS_WINDOWS
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008388{
Victor Stinner8c62be82010-05-06 00:08:46 +00008389 FILETIME create, exit, kernel, user;
8390 HANDLE hProc;
8391 hProc = GetCurrentProcess();
8392 GetProcessTimes(hProc, &create, &exit, &kernel, &user);
8393 /* The fields of a FILETIME structure are the hi and lo part
8394 of a 64-bit value expressed in 100 nanosecond units.
8395 1e7 is one second in such units; 1e-7 the inverse.
8396 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
8397 */
Larry Hastings605a62d2012-06-24 04:33:36 -07008398 return build_times_result(
Victor Stinner8c62be82010-05-06 00:08:46 +00008399 (double)(user.dwHighDateTime*429.4967296 +
8400 user.dwLowDateTime*1e-7),
8401 (double)(kernel.dwHighDateTime*429.4967296 +
8402 kernel.dwLowDateTime*1e-7),
8403 (double)0,
8404 (double)0,
8405 (double)0);
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008406}
Larry Hastings2f936352014-08-05 14:04:04 +10008407#else /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008408{
Larry Hastings2f936352014-08-05 14:04:04 +10008409
8410
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008411 struct tms t;
8412 clock_t c;
8413 errno = 0;
8414 c = times(&t);
8415 if (c == (clock_t) -1)
8416 return posix_error();
8417 return build_times_result(
8418 (double)t.tms_utime / ticks_per_second,
8419 (double)t.tms_stime / ticks_per_second,
8420 (double)t.tms_cutime / ticks_per_second,
8421 (double)t.tms_cstime / ticks_per_second,
8422 (double)c / ticks_per_second);
8423}
Larry Hastings2f936352014-08-05 14:04:04 +10008424#endif /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008425#endif /* HAVE_TIMES */
8426
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008427
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008428#ifdef HAVE_GETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008429/*[clinic input]
8430os.getsid
8431
8432 pid: pid_t
8433 /
8434
8435Call the system call getsid(pid) and return the result.
8436[clinic start generated code]*/
8437
Larry Hastings2f936352014-08-05 14:04:04 +10008438static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008439os_getsid_impl(PyObject *module, pid_t pid)
8440/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008441{
Victor Stinner8c62be82010-05-06 00:08:46 +00008442 int sid;
Victor Stinner8c62be82010-05-06 00:08:46 +00008443 sid = getsid(pid);
8444 if (sid < 0)
8445 return posix_error();
8446 return PyLong_FromLong((long)sid);
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008447}
8448#endif /* HAVE_GETSID */
8449
8450
Guido van Rossumb6775db1994-08-01 11:34:53 +00008451#ifdef HAVE_SETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008452/*[clinic input]
8453os.setsid
8454
8455Call the system call setsid().
8456[clinic start generated code]*/
8457
Larry Hastings2f936352014-08-05 14:04:04 +10008458static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008459os_setsid_impl(PyObject *module)
8460/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00008461{
Victor Stinner8c62be82010-05-06 00:08:46 +00008462 if (setsid() < 0)
8463 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008464 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008465}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008466#endif /* HAVE_SETSID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008467
Larry Hastings2f936352014-08-05 14:04:04 +10008468
Guido van Rossumb6775db1994-08-01 11:34:53 +00008469#ifdef HAVE_SETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10008470/*[clinic input]
8471os.setpgid
8472
8473 pid: pid_t
8474 pgrp: pid_t
8475 /
8476
8477Call the system call setpgid(pid, pgrp).
8478[clinic start generated code]*/
8479
Larry Hastings2f936352014-08-05 14:04:04 +10008480static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008481os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
8482/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008483{
Victor Stinner8c62be82010-05-06 00:08:46 +00008484 if (setpgid(pid, pgrp) < 0)
8485 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008486 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008487}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008488#endif /* HAVE_SETPGID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008489
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008490
Guido van Rossumb6775db1994-08-01 11:34:53 +00008491#ifdef HAVE_TCGETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008492/*[clinic input]
8493os.tcgetpgrp
8494
8495 fd: int
8496 /
8497
8498Return the process group associated with the terminal specified by fd.
8499[clinic start generated code]*/
8500
Larry Hastings2f936352014-08-05 14:04:04 +10008501static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008502os_tcgetpgrp_impl(PyObject *module, int fd)
8503/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008504{
8505 pid_t pgid = tcgetpgrp(fd);
Victor Stinner8c62be82010-05-06 00:08:46 +00008506 if (pgid < 0)
8507 return posix_error();
8508 return PyLong_FromPid(pgid);
Guido van Rossum7066dd71992-09-17 17:54:56 +00008509}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008510#endif /* HAVE_TCGETPGRP */
Guido van Rossum7066dd71992-09-17 17:54:56 +00008511
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008512
Guido van Rossumb6775db1994-08-01 11:34:53 +00008513#ifdef HAVE_TCSETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008514/*[clinic input]
8515os.tcsetpgrp
8516
8517 fd: int
8518 pgid: pid_t
8519 /
8520
8521Set the process group associated with the terminal specified by fd.
8522[clinic start generated code]*/
8523
Larry Hastings2f936352014-08-05 14:04:04 +10008524static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008525os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
8526/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008527{
Victor Stinner8c62be82010-05-06 00:08:46 +00008528 if (tcsetpgrp(fd, pgid) < 0)
8529 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008530 Py_RETURN_NONE;
Guido van Rossum7066dd71992-09-17 17:54:56 +00008531}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008532#endif /* HAVE_TCSETPGRP */
Guido van Rossum22db57e1992-04-05 14:25:30 +00008533
Guido van Rossum687dd131993-05-17 08:34:16 +00008534/* Functions acting on file descriptors */
8535
Victor Stinnerdaf45552013-08-28 00:53:59 +02008536#ifdef O_CLOEXEC
8537extern int _Py_open_cloexec_works;
8538#endif
8539
Larry Hastings2f936352014-08-05 14:04:04 +10008540
8541/*[clinic input]
8542os.open -> int
8543 path: path_t
8544 flags: int
8545 mode: int = 0o777
8546 *
8547 dir_fd: dir_fd(requires='openat') = None
8548
8549# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
8550
8551Open a file for low level IO. Returns a file descriptor (integer).
8552
8553If dir_fd is not None, it should be a file descriptor open to a directory,
8554 and path should be relative; path will then be relative to that directory.
8555dir_fd may not be implemented on your platform.
8556 If it is unavailable, using it will raise a NotImplementedError.
8557[clinic start generated code]*/
8558
Larry Hastings2f936352014-08-05 14:04:04 +10008559static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008560os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
8561/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008562{
8563 int fd;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008564 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008565
Victor Stinnerdaf45552013-08-28 00:53:59 +02008566#ifdef O_CLOEXEC
8567 int *atomic_flag_works = &_Py_open_cloexec_works;
8568#elif !defined(MS_WINDOWS)
8569 int *atomic_flag_works = NULL;
8570#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +00008571
Victor Stinnerdaf45552013-08-28 00:53:59 +02008572#ifdef MS_WINDOWS
8573 flags |= O_NOINHERIT;
8574#elif defined(O_CLOEXEC)
8575 flags |= O_CLOEXEC;
8576#endif
8577
Steve Dowerb82e17e2019-05-23 08:45:22 -07008578 if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
8579 return -1;
8580 }
8581
Steve Dower8fc89802015-04-12 00:26:27 -04008582 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008583 do {
8584 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008585#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07008586 fd = _wopen(path->wide, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008587#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07008588#ifdef HAVE_OPENAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008589 if (dir_fd != DEFAULT_DIR_FD)
8590 fd = openat(dir_fd, path->narrow, flags, mode);
8591 else
Steve Dower6230aaf2016-09-09 09:03:15 -07008592#endif /* HAVE_OPENAT */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008593 fd = open(path->narrow, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008594#endif /* !MS_WINDOWS */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008595 Py_END_ALLOW_THREADS
8596 } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04008597 _Py_END_SUPPRESS_IPH
Guido van Rossum687dd131993-05-17 08:34:16 +00008598
Victor Stinnerd3ffd322015-09-15 10:11:03 +02008599 if (fd < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008600 if (!async_err)
8601 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Larry Hastings2f936352014-08-05 14:04:04 +10008602 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008603 }
8604
Victor Stinnerdaf45552013-08-28 00:53:59 +02008605#ifndef MS_WINDOWS
8606 if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
8607 close(fd);
Larry Hastings2f936352014-08-05 14:04:04 +10008608 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008609 }
8610#endif
8611
Larry Hastings2f936352014-08-05 14:04:04 +10008612 return fd;
8613}
8614
8615
8616/*[clinic input]
8617os.close
8618
8619 fd: int
8620
8621Close a file descriptor.
8622[clinic start generated code]*/
8623
Barry Warsaw53699e91996-12-10 23:23:01 +00008624static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008625os_close_impl(PyObject *module, int fd)
8626/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00008627{
Larry Hastings2f936352014-08-05 14:04:04 +10008628 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008629 /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
8630 * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
8631 * for more details.
8632 */
Victor Stinner8c62be82010-05-06 00:08:46 +00008633 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008634 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008635 res = close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04008636 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008637 Py_END_ALLOW_THREADS
8638 if (res < 0)
8639 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008640 Py_RETURN_NONE;
Guido van Rossum687dd131993-05-17 08:34:16 +00008641}
8642
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008643
Jakub Kulíke20134f2019-09-11 17:11:57 +02008644#ifdef HAVE_FDWALK
8645static int
8646_fdwalk_close_func(void *lohi, int fd)
8647{
8648 int lo = ((int *)lohi)[0];
8649 int hi = ((int *)lohi)[1];
8650
8651 if (fd >= hi)
8652 return 1;
8653 else if (fd >= lo)
8654 close(fd);
8655 return 0;
8656}
8657#endif /* HAVE_FDWALK */
8658
Larry Hastings2f936352014-08-05 14:04:04 +10008659/*[clinic input]
8660os.closerange
8661
8662 fd_low: int
8663 fd_high: int
8664 /
8665
8666Closes all file descriptors in [fd_low, fd_high), ignoring errors.
8667[clinic start generated code]*/
8668
Larry Hastings2f936352014-08-05 14:04:04 +10008669static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008670os_closerange_impl(PyObject *module, int fd_low, int fd_high)
8671/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008672{
Jakub Kulíke20134f2019-09-11 17:11:57 +02008673#ifdef HAVE_FDWALK
8674 int lohi[2];
8675#else
Larry Hastings2f936352014-08-05 14:04:04 +10008676 int i;
Jakub Kulíke20134f2019-09-11 17:11:57 +02008677#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00008678 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008679 _Py_BEGIN_SUPPRESS_IPH
Jakub Kulíke20134f2019-09-11 17:11:57 +02008680#ifdef HAVE_FDWALK
8681 lohi[0] = Py_MAX(fd_low, 0);
8682 lohi[1] = fd_high;
8683 fdwalk(_fdwalk_close_func, lohi);
8684#else
Benjamin Peterson207116b2016-09-08 11:28:06 -07008685 for (i = Py_MAX(fd_low, 0); i < fd_high; i++)
Steve Dower940f33a2016-09-08 11:21:54 -07008686 close(i);
Jakub Kulíke20134f2019-09-11 17:11:57 +02008687#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008688 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008689 Py_END_ALLOW_THREADS
8690 Py_RETURN_NONE;
Christian Heimesfdab48e2008-01-20 09:06:41 +00008691}
8692
8693
Larry Hastings2f936352014-08-05 14:04:04 +10008694/*[clinic input]
8695os.dup -> int
8696
8697 fd: int
8698 /
8699
8700Return a duplicate of a file descriptor.
8701[clinic start generated code]*/
8702
Larry Hastings2f936352014-08-05 14:04:04 +10008703static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008704os_dup_impl(PyObject *module, int fd)
8705/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008706{
8707 return _Py_dup(fd);
Guido van Rossum687dd131993-05-17 08:34:16 +00008708}
8709
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008710
Larry Hastings2f936352014-08-05 14:04:04 +10008711/*[clinic input]
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008712os.dup2 -> int
Larry Hastings2f936352014-08-05 14:04:04 +10008713 fd: int
8714 fd2: int
8715 inheritable: bool=True
8716
8717Duplicate file descriptor.
8718[clinic start generated code]*/
8719
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008720static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008721os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008722/*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008723{
Stéphane Wirtel3d86e482018-01-30 07:04:36 +01008724 int res = 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008725#if defined(HAVE_DUP3) && \
8726 !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
8727 /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
Alexey Izbyshevb3caf382018-02-20 10:25:46 +03008728 static int dup3_works = -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008729#endif
8730
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008731 if (fd < 0 || fd2 < 0) {
8732 posix_error();
8733 return -1;
8734 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008735
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008736 /* dup2() can fail with EINTR if the target FD is already open, because it
8737 * then has to be closed. See os_close_impl() for why we don't handle EINTR
8738 * upon close(), and therefore below.
8739 */
Victor Stinnerdaf45552013-08-28 00:53:59 +02008740#ifdef MS_WINDOWS
8741 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008742 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008743 res = dup2(fd, fd2);
Steve Dower8fc89802015-04-12 00:26:27 -04008744 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02008745 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008746 if (res < 0) {
8747 posix_error();
8748 return -1;
8749 }
8750 res = fd2; // msvcrt dup2 returns 0 on success.
Victor Stinnerdaf45552013-08-28 00:53:59 +02008751
8752 /* Character files like console cannot be make non-inheritable */
8753 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8754 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008755 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008756 }
8757
8758#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
8759 Py_BEGIN_ALLOW_THREADS
8760 if (!inheritable)
8761 res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
8762 else
8763 res = dup2(fd, fd2);
8764 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008765 if (res < 0) {
8766 posix_error();
8767 return -1;
8768 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008769
8770#else
8771
8772#ifdef HAVE_DUP3
8773 if (!inheritable && dup3_works != 0) {
8774 Py_BEGIN_ALLOW_THREADS
8775 res = dup3(fd, fd2, O_CLOEXEC);
8776 Py_END_ALLOW_THREADS
8777 if (res < 0) {
8778 if (dup3_works == -1)
8779 dup3_works = (errno != ENOSYS);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008780 if (dup3_works) {
8781 posix_error();
8782 return -1;
8783 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008784 }
8785 }
8786
8787 if (inheritable || dup3_works == 0)
8788 {
8789#endif
8790 Py_BEGIN_ALLOW_THREADS
8791 res = dup2(fd, fd2);
8792 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008793 if (res < 0) {
8794 posix_error();
8795 return -1;
8796 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008797
8798 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8799 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008800 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008801 }
8802#ifdef HAVE_DUP3
8803 }
8804#endif
8805
8806#endif
8807
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008808 return res;
Guido van Rossum687dd131993-05-17 08:34:16 +00008809}
8810
Larry Hastings2f936352014-08-05 14:04:04 +10008811
Ross Lagerwall7807c352011-03-17 20:20:30 +02008812#ifdef HAVE_LOCKF
Larry Hastings2f936352014-08-05 14:04:04 +10008813/*[clinic input]
8814os.lockf
8815
8816 fd: int
8817 An open file descriptor.
8818 command: int
8819 One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
8820 length: Py_off_t
8821 The number of bytes to lock, starting at the current position.
8822 /
8823
8824Apply, test or remove a POSIX lock on an open file descriptor.
8825
8826[clinic start generated code]*/
8827
Larry Hastings2f936352014-08-05 14:04:04 +10008828static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008829os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
8830/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008831{
8832 int res;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008833
Saiyang Gou7514f4f2020-02-12 23:47:42 -08008834 if (PySys_Audit("os.lockf", "iiL", fd, command, length) < 0) {
8835 return NULL;
8836 }
8837
Ross Lagerwall7807c352011-03-17 20:20:30 +02008838 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008839 res = lockf(fd, command, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008840 Py_END_ALLOW_THREADS
8841
8842 if (res < 0)
8843 return posix_error();
8844
8845 Py_RETURN_NONE;
8846}
Larry Hastings2f936352014-08-05 14:04:04 +10008847#endif /* HAVE_LOCKF */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008848
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008849
Larry Hastings2f936352014-08-05 14:04:04 +10008850/*[clinic input]
8851os.lseek -> Py_off_t
8852
8853 fd: int
8854 position: Py_off_t
8855 how: int
8856 /
8857
8858Set the position of a file descriptor. Return the new position.
8859
8860Return the new cursor position in number of bytes
8861relative to the beginning of the file.
8862[clinic start generated code]*/
8863
Larry Hastings2f936352014-08-05 14:04:04 +10008864static Py_off_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008865os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
8866/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008867{
8868 Py_off_t result;
8869
Guido van Rossum687dd131993-05-17 08:34:16 +00008870#ifdef SEEK_SET
Victor Stinner8c62be82010-05-06 00:08:46 +00008871 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
8872 switch (how) {
Larry Hastings2f936352014-08-05 14:04:04 +10008873 case 0: how = SEEK_SET; break;
8874 case 1: how = SEEK_CUR; break;
8875 case 2: how = SEEK_END; break;
Victor Stinner8c62be82010-05-06 00:08:46 +00008876 }
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00008877#endif /* SEEK_END */
Guido van Rossum94f6f721999-01-06 18:42:14 +00008878
Victor Stinner8c62be82010-05-06 00:08:46 +00008879 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008880 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner14b9b112013-06-25 00:37:25 +02008881#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10008882 result = _lseeki64(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008883#else
Larry Hastings2f936352014-08-05 14:04:04 +10008884 result = lseek(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008885#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008886 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008887 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008888 if (result < 0)
8889 posix_error();
Guido van Rossum94f6f721999-01-06 18:42:14 +00008890
Larry Hastings2f936352014-08-05 14:04:04 +10008891 return result;
Guido van Rossum687dd131993-05-17 08:34:16 +00008892}
8893
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008894
Larry Hastings2f936352014-08-05 14:04:04 +10008895/*[clinic input]
8896os.read
8897 fd: int
8898 length: Py_ssize_t
8899 /
8900
8901Read from a file descriptor. Returns a bytes object.
8902[clinic start generated code]*/
8903
Larry Hastings2f936352014-08-05 14:04:04 +10008904static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008905os_read_impl(PyObject *module, int fd, Py_ssize_t length)
8906/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008907{
Victor Stinner8c62be82010-05-06 00:08:46 +00008908 Py_ssize_t n;
8909 PyObject *buffer;
Larry Hastings2f936352014-08-05 14:04:04 +10008910
8911 if (length < 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008912 errno = EINVAL;
8913 return posix_error();
8914 }
Larry Hastings2f936352014-08-05 14:04:04 +10008915
Victor Stinner9a0d7a72018-11-22 15:03:40 +01008916 length = Py_MIN(length, _PY_READ_MAX);
Larry Hastings2f936352014-08-05 14:04:04 +10008917
8918 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Victor Stinner8c62be82010-05-06 00:08:46 +00008919 if (buffer == NULL)
8920 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008921
Victor Stinner66aab0c2015-03-19 22:53:20 +01008922 n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
8923 if (n == -1) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008924 Py_DECREF(buffer);
Victor Stinner66aab0c2015-03-19 22:53:20 +01008925 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00008926 }
Larry Hastings2f936352014-08-05 14:04:04 +10008927
8928 if (n != length)
Victor Stinner8c62be82010-05-06 00:08:46 +00008929 _PyBytes_Resize(&buffer, n);
Larry Hastings2f936352014-08-05 14:04:04 +10008930
Victor Stinner8c62be82010-05-06 00:08:46 +00008931 return buffer;
Guido van Rossum687dd131993-05-17 08:34:16 +00008932}
8933
Ross Lagerwall7807c352011-03-17 20:20:30 +02008934#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008935 || defined(__APPLE__))) \
8936 || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
8937 || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
8938static int
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008939iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008940{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008941 Py_ssize_t i, j;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008942
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008943 *iov = PyMem_New(struct iovec, cnt);
8944 if (*iov == NULL) {
8945 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008946 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008947 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008948
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008949 *buf = PyMem_New(Py_buffer, cnt);
8950 if (*buf == NULL) {
8951 PyMem_Del(*iov);
8952 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008953 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008954 }
8955
8956 for (i = 0; i < cnt; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008957 PyObject *item = PySequence_GetItem(seq, i);
8958 if (item == NULL)
8959 goto fail;
8960 if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
8961 Py_DECREF(item);
8962 goto fail;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008963 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008964 Py_DECREF(item);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008965 (*iov)[i].iov_base = (*buf)[i].buf;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008966 (*iov)[i].iov_len = (*buf)[i].len;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008967 }
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008968 return 0;
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008969
8970fail:
8971 PyMem_Del(*iov);
8972 for (j = 0; j < i; j++) {
8973 PyBuffer_Release(&(*buf)[j]);
8974 }
8975 PyMem_Del(*buf);
Victor Stinner57ddf782014-01-08 15:21:28 +01008976 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008977}
8978
8979static void
8980iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
8981{
8982 int i;
8983 PyMem_Del(iov);
8984 for (i = 0; i < cnt; i++) {
8985 PyBuffer_Release(&buf[i]);
8986 }
8987 PyMem_Del(buf);
8988}
8989#endif
8990
Larry Hastings2f936352014-08-05 14:04:04 +10008991
Ross Lagerwall7807c352011-03-17 20:20:30 +02008992#ifdef HAVE_READV
Larry Hastings2f936352014-08-05 14:04:04 +10008993/*[clinic input]
8994os.readv -> Py_ssize_t
8995
8996 fd: int
8997 buffers: object
8998 /
8999
9000Read from a file descriptor fd into an iterable of buffers.
9001
9002The buffers should be mutable buffers accepting bytes.
9003readv will transfer data into each buffer until it is full
9004and then move on to the next buffer in the sequence to hold
9005the rest of the data.
9006
9007readv returns the total number of bytes read,
9008which may be less than the total capacity of all the buffers.
9009[clinic start generated code]*/
9010
Larry Hastings2f936352014-08-05 14:04:04 +10009011static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009012os_readv_impl(PyObject *module, int fd, PyObject *buffers)
9013/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009014{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009015 Py_ssize_t cnt, n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009016 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009017 struct iovec *iov;
9018 Py_buffer *buf;
9019
Larry Hastings2f936352014-08-05 14:04:04 +10009020 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009021 PyErr_SetString(PyExc_TypeError,
9022 "readv() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009023 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009024 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02009025
Larry Hastings2f936352014-08-05 14:04:04 +10009026 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009027 if (cnt < 0)
9028 return -1;
Larry Hastings2f936352014-08-05 14:04:04 +10009029
9030 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
9031 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009032
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009033 do {
9034 Py_BEGIN_ALLOW_THREADS
9035 n = readv(fd, iov, cnt);
9036 Py_END_ALLOW_THREADS
9037 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009038
9039 iov_cleanup(iov, buf, cnt);
Larry Hastings2f936352014-08-05 14:04:04 +10009040 if (n < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009041 if (!async_err)
9042 posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10009043 return -1;
9044 }
Victor Stinner57ddf782014-01-08 15:21:28 +01009045
Larry Hastings2f936352014-08-05 14:04:04 +10009046 return n;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009047}
Larry Hastings2f936352014-08-05 14:04:04 +10009048#endif /* HAVE_READV */
9049
Ross Lagerwall7807c352011-03-17 20:20:30 +02009050
9051#ifdef HAVE_PREAD
Larry Hastings2f936352014-08-05 14:04:04 +10009052/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10009053os.pread
9054
9055 fd: int
Dong-hee Naad7736f2019-09-25 14:47:04 +09009056 length: Py_ssize_t
Larry Hastings2f936352014-08-05 14:04:04 +10009057 offset: Py_off_t
9058 /
9059
9060Read a number of bytes from a file descriptor starting at a particular offset.
9061
9062Read length bytes from file descriptor fd, starting at offset bytes from
9063the beginning of the file. The file offset remains unchanged.
9064[clinic start generated code]*/
9065
Larry Hastings2f936352014-08-05 14:04:04 +10009066static PyObject *
Dong-hee Naad7736f2019-09-25 14:47:04 +09009067os_pread_impl(PyObject *module, int fd, Py_ssize_t length, Py_off_t offset)
9068/*[clinic end generated code: output=3f875c1eef82e32f input=85cb4a5589627144]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009069{
Ross Lagerwall7807c352011-03-17 20:20:30 +02009070 Py_ssize_t n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009071 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009072 PyObject *buffer;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009073
Larry Hastings2f936352014-08-05 14:04:04 +10009074 if (length < 0) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009075 errno = EINVAL;
9076 return posix_error();
9077 }
Larry Hastings2f936352014-08-05 14:04:04 +10009078 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02009079 if (buffer == NULL)
9080 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009081
9082 do {
9083 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009084 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009085 n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009086 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009087 Py_END_ALLOW_THREADS
9088 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9089
Ross Lagerwall7807c352011-03-17 20:20:30 +02009090 if (n < 0) {
9091 Py_DECREF(buffer);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009092 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009093 }
Larry Hastings2f936352014-08-05 14:04:04 +10009094 if (n != length)
Ross Lagerwall7807c352011-03-17 20:20:30 +02009095 _PyBytes_Resize(&buffer, n);
9096 return buffer;
9097}
Larry Hastings2f936352014-08-05 14:04:04 +10009098#endif /* HAVE_PREAD */
Ross Lagerwall7807c352011-03-17 20:20:30 +02009099
Pablo Galindo4defba32018-01-27 16:16:37 +00009100#if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
9101/*[clinic input]
9102os.preadv -> Py_ssize_t
9103
9104 fd: int
9105 buffers: object
9106 offset: Py_off_t
9107 flags: int = 0
9108 /
9109
9110Reads from a file descriptor into a number of mutable bytes-like objects.
9111
9112Combines the functionality of readv() and pread(). As readv(), it will
9113transfer data into each buffer until it is full and then move on to the next
9114buffer in the sequence to hold the rest of the data. Its fourth argument,
9115specifies the file offset at which the input operation is to be performed. It
9116will return the total number of bytes read (which can be less than the total
9117capacity of all the objects).
9118
9119The flags argument contains a bitwise OR of zero or more of the following flags:
9120
9121- RWF_HIPRI
9122- RWF_NOWAIT
9123
9124Using non-zero flags requires Linux 4.6 or newer.
9125[clinic start generated code]*/
9126
9127static Py_ssize_t
9128os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9129 int flags)
9130/*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
9131{
9132 Py_ssize_t cnt, n;
9133 int async_err = 0;
9134 struct iovec *iov;
9135 Py_buffer *buf;
9136
9137 if (!PySequence_Check(buffers)) {
9138 PyErr_SetString(PyExc_TypeError,
9139 "preadv2() arg 2 must be a sequence");
9140 return -1;
9141 }
9142
9143 cnt = PySequence_Size(buffers);
9144 if (cnt < 0) {
9145 return -1;
9146 }
9147
9148#ifndef HAVE_PREADV2
9149 if(flags != 0) {
9150 argument_unavailable_error("preadv2", "flags");
9151 return -1;
9152 }
9153#endif
9154
9155 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
9156 return -1;
9157 }
9158#ifdef HAVE_PREADV2
9159 do {
9160 Py_BEGIN_ALLOW_THREADS
9161 _Py_BEGIN_SUPPRESS_IPH
9162 n = preadv2(fd, iov, cnt, offset, flags);
9163 _Py_END_SUPPRESS_IPH
9164 Py_END_ALLOW_THREADS
9165 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9166#else
9167 do {
9168 Py_BEGIN_ALLOW_THREADS
9169 _Py_BEGIN_SUPPRESS_IPH
9170 n = preadv(fd, iov, cnt, offset);
9171 _Py_END_SUPPRESS_IPH
9172 Py_END_ALLOW_THREADS
9173 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9174#endif
9175
9176 iov_cleanup(iov, buf, cnt);
9177 if (n < 0) {
9178 if (!async_err) {
9179 posix_error();
9180 }
9181 return -1;
9182 }
9183
9184 return n;
9185}
9186#endif /* HAVE_PREADV */
9187
Larry Hastings2f936352014-08-05 14:04:04 +10009188
9189/*[clinic input]
9190os.write -> Py_ssize_t
9191
9192 fd: int
9193 data: Py_buffer
9194 /
9195
9196Write a bytes object to a file descriptor.
9197[clinic start generated code]*/
9198
Larry Hastings2f936352014-08-05 14:04:04 +10009199static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009200os_write_impl(PyObject *module, int fd, Py_buffer *data)
9201/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009202{
Victor Stinner66aab0c2015-03-19 22:53:20 +01009203 return _Py_write(fd, data->buf, data->len);
Ross Lagerwall7807c352011-03-17 20:20:30 +02009204}
9205
9206#ifdef HAVE_SENDFILE
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009207PyDoc_STRVAR(posix_sendfile__doc__,
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009208"sendfile(out_fd, in_fd, offset, count) -> byteswritten\n\
9209sendfile(out_fd, in_fd, offset, count[, headers][, trailers], flags=0)\n\
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009210 -> byteswritten\n\
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009211Copy count bytes from file descriptor in_fd to file descriptor out_fd.");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009212
Larry Hastings2f936352014-08-05 14:04:04 +10009213/* AC 3.5: don't bother converting, has optional group*/
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009214static PyObject *
9215posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict)
9216{
9217 int in, out;
9218 Py_ssize_t ret;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009219 int async_err = 0;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009220 off_t offset;
9221
9222#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
9223#ifndef __APPLE__
9224 Py_ssize_t len;
9225#endif
9226 PyObject *headers = NULL, *trailers = NULL;
9227 Py_buffer *hbuf, *tbuf;
9228 off_t sbytes;
9229 struct sf_hdtr sf;
9230 int flags = 0;
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009231 static char *keywords[] = {"out_fd", "in_fd",
Benjamin Petersond8a43b42011-02-26 21:35:16 +00009232 "offset", "count",
9233 "headers", "trailers", "flags", NULL};
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009234
Victor Stinner6ce0dbf2013-07-07 16:32:36 +02009235 sf.headers = NULL;
9236 sf.trailers = NULL;
9237
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009238#ifdef __APPLE__
9239 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&O&|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10009240 keywords, &out, &in, Py_off_t_converter, &offset, Py_off_t_converter, &sbytes,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009241#else
9242 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&n|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10009243 keywords, &out, &in, Py_off_t_converter, &offset, &len,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009244#endif
9245 &headers, &trailers, &flags))
9246 return NULL;
9247 if (headers != NULL) {
9248 if (!PySequence_Check(headers)) {
9249 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009250 "sendfile() headers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009251 return NULL;
9252 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009253 Py_ssize_t i = PySequence_Size(headers);
9254 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009255 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009256 if (i > INT_MAX) {
9257 PyErr_SetString(PyExc_OverflowError,
9258 "sendfile() header is too large");
9259 return NULL;
9260 }
9261 if (i > 0) {
9262 sf.hdr_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009263 if (iov_setup(&(sf.headers), &hbuf,
9264 headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009265 return NULL;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009266#ifdef __APPLE__
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009267 for (i = 0; i < sf.hdr_cnt; i++) {
9268 Py_ssize_t blen = sf.headers[i].iov_len;
9269# define OFF_T_MAX 0x7fffffffffffffff
9270 if (sbytes >= OFF_T_MAX - blen) {
9271 PyErr_SetString(PyExc_OverflowError,
9272 "sendfile() header is too large");
9273 return NULL;
9274 }
9275 sbytes += blen;
9276 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009277#endif
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009278 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009279 }
9280 }
9281 if (trailers != NULL) {
9282 if (!PySequence_Check(trailers)) {
9283 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009284 "sendfile() trailers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009285 return NULL;
9286 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009287 Py_ssize_t i = PySequence_Size(trailers);
9288 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009289 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009290 if (i > INT_MAX) {
9291 PyErr_SetString(PyExc_OverflowError,
9292 "sendfile() trailer is too large");
9293 return NULL;
9294 }
9295 if (i > 0) {
9296 sf.trl_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009297 if (iov_setup(&(sf.trailers), &tbuf,
9298 trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009299 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009300 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009301 }
9302 }
9303
Steve Dower8fc89802015-04-12 00:26:27 -04009304 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009305 do {
9306 Py_BEGIN_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009307#ifdef __APPLE__
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009308 ret = sendfile(in, out, offset, &sbytes, &sf, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009309#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009310 ret = sendfile(in, out, offset, len, &sf, &sbytes, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009311#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009312 Py_END_ALLOW_THREADS
9313 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04009314 _Py_END_SUPPRESS_IPH
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009315
9316 if (sf.headers != NULL)
9317 iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
9318 if (sf.trailers != NULL)
9319 iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
9320
9321 if (ret < 0) {
9322 if ((errno == EAGAIN) || (errno == EBUSY)) {
9323 if (sbytes != 0) {
9324 // some data has been sent
9325 goto done;
9326 }
9327 else {
9328 // no data has been sent; upper application is supposed
9329 // to retry on EAGAIN or EBUSY
9330 return posix_error();
9331 }
9332 }
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009333 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009334 }
9335 goto done;
9336
9337done:
9338 #if !defined(HAVE_LARGEFILE_SUPPORT)
9339 return Py_BuildValue("l", sbytes);
9340 #else
9341 return Py_BuildValue("L", sbytes);
9342 #endif
9343
9344#else
9345 Py_ssize_t count;
9346 PyObject *offobj;
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009347 static char *keywords[] = {"out_fd", "in_fd",
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009348 "offset", "count", NULL};
9349 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiOn:sendfile",
9350 keywords, &out, &in, &offobj, &count))
9351 return NULL;
Benjamin Peterson840ef8f2016-09-07 14:45:10 -07009352#ifdef __linux__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009353 if (offobj == Py_None) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009354 do {
9355 Py_BEGIN_ALLOW_THREADS
9356 ret = sendfile(out, in, NULL, count);
9357 Py_END_ALLOW_THREADS
9358 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009359 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009360 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodola'ff1a7352011-04-19 09:47:16 +02009361 return Py_BuildValue("n", ret);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009362 }
9363#endif
Larry Hastings2f936352014-08-05 14:04:04 +10009364 if (!Py_off_t_converter(offobj, &offset))
Antoine Pitroudcc20b82011-02-26 13:38:35 +00009365 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009366
9367 do {
9368 Py_BEGIN_ALLOW_THREADS
9369 ret = sendfile(out, in, &offset, count);
9370 Py_END_ALLOW_THREADS
9371 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009372 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009373 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009374 return Py_BuildValue("n", ret);
9375#endif
9376}
Larry Hastings2f936352014-08-05 14:04:04 +10009377#endif /* HAVE_SENDFILE */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009378
Larry Hastings2f936352014-08-05 14:04:04 +10009379
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009380#if defined(__APPLE__)
9381/*[clinic input]
9382os._fcopyfile
9383
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009384 in_fd: int
9385 out_fd: int
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009386 flags: int
9387 /
9388
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009389Efficiently copy content or metadata of 2 regular file descriptors (macOS).
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009390[clinic start generated code]*/
9391
9392static PyObject *
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009393os__fcopyfile_impl(PyObject *module, int in_fd, int out_fd, int flags)
9394/*[clinic end generated code: output=c9d1a35a992e401b input=1e34638a86948795]*/
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009395{
9396 int ret;
9397
9398 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009399 ret = fcopyfile(in_fd, out_fd, NULL, flags);
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009400 Py_END_ALLOW_THREADS
9401 if (ret < 0)
9402 return posix_error();
9403 Py_RETURN_NONE;
9404}
9405#endif
9406
9407
Larry Hastings2f936352014-08-05 14:04:04 +10009408/*[clinic input]
9409os.fstat
9410
9411 fd : int
9412
9413Perform a stat system call on the given file descriptor.
9414
9415Like stat(), but for an open file descriptor.
9416Equivalent to os.stat(fd).
9417[clinic start generated code]*/
9418
Larry Hastings2f936352014-08-05 14:04:04 +10009419static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009420os_fstat_impl(PyObject *module, int fd)
9421/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009422{
Victor Stinner8c62be82010-05-06 00:08:46 +00009423 STRUCT_STAT st;
9424 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009425 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009426
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009427 do {
9428 Py_BEGIN_ALLOW_THREADS
9429 res = FSTAT(fd, &st);
9430 Py_END_ALLOW_THREADS
9431 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner8c62be82010-05-06 00:08:46 +00009432 if (res != 0) {
Martin v. Löwis14694662006-02-03 12:54:16 +00009433#ifdef MS_WINDOWS
Victor Stinnerb024e842012-10-31 22:24:06 +01009434 return PyErr_SetFromWindowsErr(0);
Martin v. Löwis14694662006-02-03 12:54:16 +00009435#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009436 return (!async_err) ? posix_error() : NULL;
Martin v. Löwis14694662006-02-03 12:54:16 +00009437#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00009438 }
Tim Peters5aa91602002-01-30 05:46:57 +00009439
Victor Stinner4195b5c2012-02-08 23:03:19 +01009440 return _pystat_fromstructstat(&st);
Guido van Rossum687dd131993-05-17 08:34:16 +00009441}
9442
Larry Hastings2f936352014-08-05 14:04:04 +10009443
9444/*[clinic input]
9445os.isatty -> bool
9446 fd: int
9447 /
9448
9449Return True if the fd is connected to a terminal.
9450
9451Return True if the file descriptor is an open file descriptor
9452connected to the slave end of a terminal.
9453[clinic start generated code]*/
9454
Larry Hastings2f936352014-08-05 14:04:04 +10009455static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009456os_isatty_impl(PyObject *module, int fd)
9457/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009458{
Steve Dower8fc89802015-04-12 00:26:27 -04009459 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -04009460 _Py_BEGIN_SUPPRESS_IPH
9461 return_value = isatty(fd);
9462 _Py_END_SUPPRESS_IPH
9463 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +10009464}
9465
9466
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009467#ifdef HAVE_PIPE
Larry Hastings2f936352014-08-05 14:04:04 +10009468/*[clinic input]
9469os.pipe
9470
9471Create a pipe.
9472
9473Returns a tuple of two file descriptors:
9474 (read_fd, write_fd)
9475[clinic start generated code]*/
9476
Larry Hastings2f936352014-08-05 14:04:04 +10009477static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009478os_pipe_impl(PyObject *module)
9479/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00009480{
Victor Stinner8c62be82010-05-06 00:08:46 +00009481 int fds[2];
Victor Stinnerdaf45552013-08-28 00:53:59 +02009482#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00009483 HANDLE read, write;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009484 SECURITY_ATTRIBUTES attr;
Victor Stinner8c62be82010-05-06 00:08:46 +00009485 BOOL ok;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009486#else
9487 int res;
9488#endif
9489
9490#ifdef MS_WINDOWS
9491 attr.nLength = sizeof(attr);
9492 attr.lpSecurityDescriptor = NULL;
9493 attr.bInheritHandle = FALSE;
9494
9495 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08009496 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009497 ok = CreatePipe(&read, &write, &attr, 0);
9498 if (ok) {
Benjamin Petersonca470632016-09-06 13:47:26 -07009499 fds[0] = _open_osfhandle((intptr_t)read, _O_RDONLY);
9500 fds[1] = _open_osfhandle((intptr_t)write, _O_WRONLY);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009501 if (fds[0] == -1 || fds[1] == -1) {
9502 CloseHandle(read);
9503 CloseHandle(write);
9504 ok = 0;
9505 }
9506 }
Steve Dowerc3630612016-11-19 18:41:16 -08009507 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009508 Py_END_ALLOW_THREADS
9509
Victor Stinner8c62be82010-05-06 00:08:46 +00009510 if (!ok)
Victor Stinnerb024e842012-10-31 22:24:06 +01009511 return PyErr_SetFromWindowsErr(0);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009512#else
9513
9514#ifdef HAVE_PIPE2
9515 Py_BEGIN_ALLOW_THREADS
9516 res = pipe2(fds, O_CLOEXEC);
9517 Py_END_ALLOW_THREADS
9518
9519 if (res != 0 && errno == ENOSYS)
9520 {
9521#endif
9522 Py_BEGIN_ALLOW_THREADS
9523 res = pipe(fds);
9524 Py_END_ALLOW_THREADS
9525
9526 if (res == 0) {
9527 if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
9528 close(fds[0]);
9529 close(fds[1]);
9530 return NULL;
9531 }
9532 if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
9533 close(fds[0]);
9534 close(fds[1]);
9535 return NULL;
9536 }
9537 }
9538#ifdef HAVE_PIPE2
9539 }
9540#endif
9541
9542 if (res != 0)
9543 return PyErr_SetFromErrno(PyExc_OSError);
9544#endif /* !MS_WINDOWS */
9545 return Py_BuildValue("(ii)", fds[0], fds[1]);
Guido van Rossum687dd131993-05-17 08:34:16 +00009546}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009547#endif /* HAVE_PIPE */
9548
Larry Hastings2f936352014-08-05 14:04:04 +10009549
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009550#ifdef HAVE_PIPE2
Larry Hastings2f936352014-08-05 14:04:04 +10009551/*[clinic input]
9552os.pipe2
9553
9554 flags: int
9555 /
9556
9557Create a pipe with flags set atomically.
9558
9559Returns a tuple of two file descriptors:
9560 (read_fd, write_fd)
9561
9562flags can be constructed by ORing together one or more of these values:
9563O_NONBLOCK, O_CLOEXEC.
9564[clinic start generated code]*/
9565
Larry Hastings2f936352014-08-05 14:04:04 +10009566static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009567os_pipe2_impl(PyObject *module, int flags)
9568/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009569{
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009570 int fds[2];
9571 int res;
9572
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009573 res = pipe2(fds, flags);
9574 if (res != 0)
9575 return posix_error();
9576 return Py_BuildValue("(ii)", fds[0], fds[1]);
9577}
9578#endif /* HAVE_PIPE2 */
9579
Larry Hastings2f936352014-08-05 14:04:04 +10009580
Ross Lagerwall7807c352011-03-17 20:20:30 +02009581#ifdef HAVE_WRITEV
Larry Hastings2f936352014-08-05 14:04:04 +10009582/*[clinic input]
9583os.writev -> Py_ssize_t
9584 fd: int
9585 buffers: object
9586 /
9587
9588Iterate over buffers, and write the contents of each to a file descriptor.
9589
9590Returns the total number of bytes written.
9591buffers must be a sequence of bytes-like objects.
9592[clinic start generated code]*/
9593
Larry Hastings2f936352014-08-05 14:04:04 +10009594static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009595os_writev_impl(PyObject *module, int fd, PyObject *buffers)
9596/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009597{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009598 Py_ssize_t cnt;
Larry Hastings2f936352014-08-05 14:04:04 +10009599 Py_ssize_t result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009600 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009601 struct iovec *iov;
9602 Py_buffer *buf;
Larry Hastings2f936352014-08-05 14:04:04 +10009603
9604 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009605 PyErr_SetString(PyExc_TypeError,
9606 "writev() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009607 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009608 }
Larry Hastings2f936352014-08-05 14:04:04 +10009609 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009610 if (cnt < 0)
9611 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009612
Larry Hastings2f936352014-08-05 14:04:04 +10009613 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9614 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009615 }
9616
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009617 do {
9618 Py_BEGIN_ALLOW_THREADS
9619 result = writev(fd, iov, cnt);
9620 Py_END_ALLOW_THREADS
9621 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009622
9623 iov_cleanup(iov, buf, cnt);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009624 if (result < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009625 posix_error();
Victor Stinner57ddf782014-01-08 15:21:28 +01009626
Georg Brandl306336b2012-06-24 12:55:33 +02009627 return result;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009628}
Larry Hastings2f936352014-08-05 14:04:04 +10009629#endif /* HAVE_WRITEV */
9630
9631
9632#ifdef HAVE_PWRITE
9633/*[clinic input]
9634os.pwrite -> Py_ssize_t
9635
9636 fd: int
9637 buffer: Py_buffer
9638 offset: Py_off_t
9639 /
9640
9641Write bytes to a file descriptor starting at a particular offset.
9642
9643Write buffer to fd, starting at offset bytes from the beginning of
9644the file. Returns the number of bytes writte. Does not change the
9645current file offset.
9646[clinic start generated code]*/
9647
Larry Hastings2f936352014-08-05 14:04:04 +10009648static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009649os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
9650/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009651{
9652 Py_ssize_t size;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009653 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009654
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009655 do {
9656 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009657 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009658 size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009659 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009660 Py_END_ALLOW_THREADS
9661 } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +10009662
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009663 if (size < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009664 posix_error();
9665 return size;
9666}
9667#endif /* HAVE_PWRITE */
9668
Pablo Galindo4defba32018-01-27 16:16:37 +00009669#if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
9670/*[clinic input]
9671os.pwritev -> Py_ssize_t
9672
9673 fd: int
9674 buffers: object
9675 offset: Py_off_t
9676 flags: int = 0
9677 /
9678
9679Writes the contents of bytes-like objects to a file descriptor at a given offset.
9680
9681Combines the functionality of writev() and pwrite(). All buffers must be a sequence
9682of bytes-like objects. Buffers are processed in array order. Entire contents of first
9683buffer is written before proceeding to second, and so on. The operating system may
9684set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
9685This function writes the contents of each object to the file descriptor and returns
9686the total number of bytes written.
9687
9688The flags argument contains a bitwise OR of zero or more of the following flags:
9689
9690- RWF_DSYNC
9691- RWF_SYNC
9692
9693Using non-zero flags requires Linux 4.7 or newer.
9694[clinic start generated code]*/
9695
9696static Py_ssize_t
9697os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9698 int flags)
9699/*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=803dc5ddbf0cfd3b]*/
9700{
9701 Py_ssize_t cnt;
9702 Py_ssize_t result;
9703 int async_err = 0;
9704 struct iovec *iov;
9705 Py_buffer *buf;
9706
9707 if (!PySequence_Check(buffers)) {
9708 PyErr_SetString(PyExc_TypeError,
9709 "pwritev() arg 2 must be a sequence");
9710 return -1;
9711 }
9712
9713 cnt = PySequence_Size(buffers);
9714 if (cnt < 0) {
9715 return -1;
9716 }
9717
9718#ifndef HAVE_PWRITEV2
9719 if(flags != 0) {
9720 argument_unavailable_error("pwritev2", "flags");
9721 return -1;
9722 }
9723#endif
9724
9725 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9726 return -1;
9727 }
9728#ifdef HAVE_PWRITEV2
9729 do {
9730 Py_BEGIN_ALLOW_THREADS
9731 _Py_BEGIN_SUPPRESS_IPH
9732 result = pwritev2(fd, iov, cnt, offset, flags);
9733 _Py_END_SUPPRESS_IPH
9734 Py_END_ALLOW_THREADS
9735 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9736#else
9737 do {
9738 Py_BEGIN_ALLOW_THREADS
9739 _Py_BEGIN_SUPPRESS_IPH
9740 result = pwritev(fd, iov, cnt, offset);
9741 _Py_END_SUPPRESS_IPH
9742 Py_END_ALLOW_THREADS
9743 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9744#endif
9745
9746 iov_cleanup(iov, buf, cnt);
9747 if (result < 0) {
9748 if (!async_err) {
9749 posix_error();
9750 }
9751 return -1;
9752 }
9753
9754 return result;
9755}
9756#endif /* HAVE_PWRITEV */
9757
Pablo Galindoaac4d032019-05-31 19:39:47 +01009758#ifdef HAVE_COPY_FILE_RANGE
9759/*[clinic input]
9760
9761os.copy_file_range
9762 src: int
9763 Source file descriptor.
9764 dst: int
9765 Destination file descriptor.
9766 count: Py_ssize_t
9767 Number of bytes to copy.
9768 offset_src: object = None
9769 Starting offset in src.
9770 offset_dst: object = None
9771 Starting offset in dst.
9772
9773Copy count bytes from one file descriptor to another.
9774
9775If offset_src is None, then src is read from the current position;
9776respectively for offset_dst.
9777[clinic start generated code]*/
9778
9779static PyObject *
9780os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
9781 PyObject *offset_src, PyObject *offset_dst)
9782/*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
9783{
9784 off_t offset_src_val, offset_dst_val;
9785 off_t *p_offset_src = NULL;
9786 off_t *p_offset_dst = NULL;
9787 Py_ssize_t ret;
9788 int async_err = 0;
9789 /* The flags argument is provided to allow
9790 * for future extensions and currently must be to 0. */
9791 int flags = 0;
Pablo Galindo4defba32018-01-27 16:16:37 +00009792
9793
Pablo Galindoaac4d032019-05-31 19:39:47 +01009794 if (count < 0) {
9795 PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
9796 return NULL;
9797 }
9798
9799 if (offset_src != Py_None) {
9800 if (!Py_off_t_converter(offset_src, &offset_src_val)) {
9801 return NULL;
9802 }
9803 p_offset_src = &offset_src_val;
9804 }
9805
9806 if (offset_dst != Py_None) {
9807 if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
9808 return NULL;
9809 }
9810 p_offset_dst = &offset_dst_val;
9811 }
9812
9813 do {
9814 Py_BEGIN_ALLOW_THREADS
9815 ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
9816 Py_END_ALLOW_THREADS
9817 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9818
9819 if (ret < 0) {
9820 return (!async_err) ? posix_error() : NULL;
9821 }
9822
9823 return PyLong_FromSsize_t(ret);
9824}
9825#endif /* HAVE_COPY_FILE_RANGE*/
Larry Hastings2f936352014-08-05 14:04:04 +10009826
9827#ifdef HAVE_MKFIFO
9828/*[clinic input]
9829os.mkfifo
9830
9831 path: path_t
9832 mode: int=0o666
9833 *
9834 dir_fd: dir_fd(requires='mkfifoat')=None
9835
9836Create a "fifo" (a POSIX named pipe).
9837
9838If dir_fd is not None, it should be a file descriptor open to a directory,
9839 and path should be relative; path will then be relative to that directory.
9840dir_fd may not be implemented on your platform.
9841 If it is unavailable, using it will raise a NotImplementedError.
9842[clinic start generated code]*/
9843
Larry Hastings2f936352014-08-05 14:04:04 +10009844static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009845os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
9846/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009847{
9848 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009849 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009850
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009851 do {
9852 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009853#ifdef HAVE_MKFIFOAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009854 if (dir_fd != DEFAULT_DIR_FD)
9855 result = mkfifoat(dir_fd, path->narrow, mode);
9856 else
Ross Lagerwall7807c352011-03-17 20:20:30 +02009857#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009858 result = mkfifo(path->narrow, mode);
9859 Py_END_ALLOW_THREADS
9860 } while (result != 0 && errno == EINTR &&
9861 !(async_err = PyErr_CheckSignals()));
9862 if (result != 0)
9863 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009864
9865 Py_RETURN_NONE;
9866}
9867#endif /* HAVE_MKFIFO */
9868
9869
9870#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
9871/*[clinic input]
9872os.mknod
9873
9874 path: path_t
9875 mode: int=0o600
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009876 device: dev_t=0
Larry Hastings2f936352014-08-05 14:04:04 +10009877 *
9878 dir_fd: dir_fd(requires='mknodat')=None
9879
9880Create a node in the file system.
9881
9882Create a node in the file system (file, device special file or named pipe)
9883at path. mode specifies both the permissions to use and the
9884type of node to be created, being combined (bitwise OR) with one of
9885S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
9886device defines the newly created device special file (probably using
9887os.makedev()). Otherwise device is ignored.
9888
9889If dir_fd is not None, it should be a file descriptor open to a directory,
9890 and path should be relative; path will then be relative to that directory.
9891dir_fd may not be implemented on your platform.
9892 If it is unavailable, using it will raise a NotImplementedError.
9893[clinic start generated code]*/
9894
Larry Hastings2f936352014-08-05 14:04:04 +10009895static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009896os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
Larry Hastings89964c42015-04-14 18:07:59 -04009897 int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009898/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009899{
9900 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009901 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009902
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009903 do {
9904 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009905#ifdef HAVE_MKNODAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009906 if (dir_fd != DEFAULT_DIR_FD)
9907 result = mknodat(dir_fd, path->narrow, mode, device);
9908 else
Larry Hastings2f936352014-08-05 14:04:04 +10009909#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009910 result = mknod(path->narrow, mode, device);
9911 Py_END_ALLOW_THREADS
9912 } while (result != 0 && errno == EINTR &&
9913 !(async_err = PyErr_CheckSignals()));
9914 if (result != 0)
9915 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009916
9917 Py_RETURN_NONE;
9918}
9919#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
9920
9921
9922#ifdef HAVE_DEVICE_MACROS
9923/*[clinic input]
9924os.major -> unsigned_int
9925
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009926 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009927 /
9928
9929Extracts a device major number from a raw device number.
9930[clinic start generated code]*/
9931
Larry Hastings2f936352014-08-05 14:04:04 +10009932static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009933os_major_impl(PyObject *module, dev_t device)
9934/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009935{
9936 return major(device);
9937}
9938
9939
9940/*[clinic input]
9941os.minor -> unsigned_int
9942
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009943 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009944 /
9945
9946Extracts a device minor number from a raw device number.
9947[clinic start generated code]*/
9948
Larry Hastings2f936352014-08-05 14:04:04 +10009949static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009950os_minor_impl(PyObject *module, dev_t device)
9951/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009952{
9953 return minor(device);
9954}
9955
9956
9957/*[clinic input]
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009958os.makedev -> dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009959
9960 major: int
9961 minor: int
9962 /
9963
9964Composes a raw device number from the major and minor device numbers.
9965[clinic start generated code]*/
9966
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009967static dev_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009968os_makedev_impl(PyObject *module, int major, int minor)
9969/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009970{
9971 return makedev(major, minor);
9972}
9973#endif /* HAVE_DEVICE_MACROS */
9974
9975
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009976#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009977/*[clinic input]
9978os.ftruncate
9979
9980 fd: int
9981 length: Py_off_t
9982 /
9983
9984Truncate a file, specified by file descriptor, to a specific length.
9985[clinic start generated code]*/
9986
Larry Hastings2f936352014-08-05 14:04:04 +10009987static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009988os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
9989/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009990{
9991 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009992 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009993
Steve Dowerb82e17e2019-05-23 08:45:22 -07009994 if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
9995 return NULL;
9996 }
9997
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009998 do {
9999 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -040010000 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010001#ifdef MS_WINDOWS
10002 result = _chsize_s(fd, length);
10003#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010004 result = ftruncate(fd, length);
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010005#endif
Steve Dowera1c7e722015-04-12 00:26:43 -040010006 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010007 Py_END_ALLOW_THREADS
10008 } while (result != 0 && errno == EINTR &&
10009 !(async_err = PyErr_CheckSignals()));
10010 if (result != 0)
10011 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100010012 Py_RETURN_NONE;
10013}
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010014#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +100010015
10016
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010017#if defined HAVE_TRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010018/*[clinic input]
10019os.truncate
10020 path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
10021 length: Py_off_t
10022
10023Truncate a file, specified by path, to a specific length.
10024
10025On some platforms, path may also be specified as an open file descriptor.
10026 If this functionality is unavailable, using it raises an exception.
10027[clinic start generated code]*/
10028
Larry Hastings2f936352014-08-05 14:04:04 +100010029static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010030os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
10031/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010032{
10033 int result;
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010034#ifdef MS_WINDOWS
10035 int fd;
10036#endif
10037
10038 if (path->fd != -1)
10039 return os_ftruncate_impl(module, path->fd, length);
Larry Hastings2f936352014-08-05 14:04:04 +100010040
Steve Dowerb82e17e2019-05-23 08:45:22 -070010041 if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
10042 return NULL;
10043 }
10044
Larry Hastings2f936352014-08-05 14:04:04 +100010045 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -040010046 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010047#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -070010048 fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
Victor Stinnercc0bbbc2015-04-25 00:21:52 +020010049 if (fd < 0)
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010050 result = -1;
10051 else {
10052 result = _chsize_s(fd, length);
10053 close(fd);
10054 if (result < 0)
10055 errno = result;
10056 }
10057#else
10058 result = truncate(path->narrow, length);
Larry Hastings2f936352014-08-05 14:04:04 +100010059#endif
Steve Dowera1c7e722015-04-12 00:26:43 -040010060 _Py_END_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +100010061 Py_END_ALLOW_THREADS
10062 if (result < 0)
Alexey Izbyshev83460312018-10-20 03:28:22 +030010063 return posix_path_error(path);
Larry Hastings2f936352014-08-05 14:04:04 +100010064
10065 Py_RETURN_NONE;
10066}
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010067#endif /* HAVE_TRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +100010068
Ross Lagerwall7807c352011-03-17 20:20:30 +020010069
Victor Stinnerd6b17692014-09-30 12:20:05 +020010070/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
10071 and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
10072 defined, which is the case in Python on AIX. AIX bug report:
10073 http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
10074#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
10075# define POSIX_FADVISE_AIX_BUG
10076#endif
10077
Victor Stinnerec39e262014-09-30 12:35:58 +020010078
Victor Stinnerd6b17692014-09-30 12:20:05 +020010079#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +100010080/*[clinic input]
10081os.posix_fallocate
10082
10083 fd: int
10084 offset: Py_off_t
10085 length: Py_off_t
10086 /
10087
10088Ensure a file has allocated at least a particular number of bytes on disk.
10089
10090Ensure that the file specified by fd encompasses a range of bytes
10091starting at offset bytes from the beginning and continuing for length bytes.
10092[clinic start generated code]*/
10093
Larry Hastings2f936352014-08-05 14:04:04 +100010094static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010095os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -040010096 Py_off_t length)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010097/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010098{
10099 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010100 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010101
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010102 do {
10103 Py_BEGIN_ALLOW_THREADS
10104 result = posix_fallocate(fd, offset, length);
10105 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010106 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10107
10108 if (result == 0)
10109 Py_RETURN_NONE;
10110
10111 if (async_err)
10112 return NULL;
10113
10114 errno = result;
10115 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010116}
Victor Stinnerec39e262014-09-30 12:35:58 +020010117#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
Larry Hastings2f936352014-08-05 14:04:04 +100010118
Ross Lagerwall7807c352011-03-17 20:20:30 +020010119
Victor Stinnerd6b17692014-09-30 12:20:05 +020010120#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +100010121/*[clinic input]
10122os.posix_fadvise
10123
10124 fd: int
10125 offset: Py_off_t
10126 length: Py_off_t
10127 advice: int
10128 /
10129
10130Announce an intention to access data in a specific pattern.
10131
10132Announce an intention to access data in a specific pattern, thus allowing
10133the kernel to make optimizations.
10134The advice applies to the region of the file specified by fd starting at
10135offset and continuing for length bytes.
10136advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
10137POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
10138POSIX_FADV_DONTNEED.
10139[clinic start generated code]*/
10140
Larry Hastings2f936352014-08-05 14:04:04 +100010141static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010142os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -040010143 Py_off_t length, int advice)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010144/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010145{
10146 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010147 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010148
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010149 do {
10150 Py_BEGIN_ALLOW_THREADS
10151 result = posix_fadvise(fd, offset, length, advice);
10152 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010153 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10154
10155 if (result == 0)
10156 Py_RETURN_NONE;
10157
10158 if (async_err)
10159 return NULL;
10160
10161 errno = result;
10162 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010163}
Victor Stinnerec39e262014-09-30 12:35:58 +020010164#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
Ross Lagerwall7807c352011-03-17 20:20:30 +020010165
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000010166
Thomas Hellerf78f12a2007-11-08 19:33:05 +000010167#ifdef MS_WINDOWS
Victor Stinner161e7b32020-01-24 11:53:44 +010010168static PyObject*
10169win32_putenv(PyObject *name, PyObject *value)
10170{
10171 /* Search from index 1 because on Windows starting '=' is allowed for
10172 defining hidden environment variables. */
10173 if (PyUnicode_GET_LENGTH(name) == 0 ||
10174 PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
10175 {
10176 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10177 return NULL;
10178 }
10179 PyObject *unicode;
10180 if (value != NULL) {
10181 unicode = PyUnicode_FromFormat("%U=%U", name, value);
10182 }
10183 else {
10184 unicode = PyUnicode_FromFormat("%U=", name);
10185 }
10186 if (unicode == NULL) {
10187 return NULL;
10188 }
10189
10190 Py_ssize_t size;
10191 /* PyUnicode_AsWideCharString() rejects embedded null characters */
10192 wchar_t *env = PyUnicode_AsWideCharString(unicode, &size);
10193 Py_DECREF(unicode);
10194
10195 if (env == NULL) {
10196 return NULL;
10197 }
10198 if (size > _MAX_ENV) {
10199 PyErr_Format(PyExc_ValueError,
10200 "the environment variable is longer than %u characters",
10201 _MAX_ENV);
10202 PyMem_Free(env);
10203 return NULL;
10204 }
10205
10206 /* _wputenv() and SetEnvironmentVariableW() update the environment in the
10207 Process Environment Block (PEB). _wputenv() also updates CRT 'environ'
10208 and '_wenviron' variables, whereas SetEnvironmentVariableW() does not.
10209
10210 Prefer _wputenv() to be compatible with C libraries using CRT
10211 variables and CRT functions using these variables (ex: getenv()). */
10212 int err = _wputenv(env);
10213 PyMem_Free(env);
10214
10215 if (err) {
10216 posix_error();
10217 return NULL;
10218 }
10219
10220 Py_RETURN_NONE;
10221}
10222#endif
10223
10224
10225#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010226/*[clinic input]
10227os.putenv
10228
10229 name: unicode
10230 value: unicode
10231 /
10232
10233Change or add an environment variable.
10234[clinic start generated code]*/
10235
Larry Hastings2f936352014-08-05 14:04:04 +100010236static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010237os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10238/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010239{
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010240 if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
10241 return NULL;
10242 }
Victor Stinner161e7b32020-01-24 11:53:44 +010010243 return win32_putenv(name, value);
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010244}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010245#else
Larry Hastings2f936352014-08-05 14:04:04 +100010246/*[clinic input]
10247os.putenv
Guido van Rossumb6a47161997-09-15 22:54:34 +000010248
Larry Hastings2f936352014-08-05 14:04:04 +100010249 name: FSConverter
10250 value: FSConverter
10251 /
10252
10253Change or add an environment variable.
10254[clinic start generated code]*/
10255
Larry Hastings2f936352014-08-05 14:04:04 +100010256static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010257os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10258/*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010259{
Serhiy Storchaka77703942017-06-25 07:33:01 +030010260 const char *name_string = PyBytes_AS_STRING(name);
10261 const char *value_string = PyBytes_AS_STRING(value);
Larry Hastings2f936352014-08-05 14:04:04 +100010262
Serhiy Storchaka77703942017-06-25 07:33:01 +030010263 if (strchr(name_string, '=') != NULL) {
10264 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10265 return NULL;
10266 }
Victor Stinnerb477d192020-01-22 22:48:16 +010010267
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010268 if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
10269 return NULL;
10270 }
10271
Victor Stinnerb477d192020-01-22 22:48:16 +010010272 if (setenv(name_string, value_string, 1)) {
10273 return posix_error();
10274 }
Larry Hastings2f936352014-08-05 14:04:04 +100010275 Py_RETURN_NONE;
10276}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010277#endif /* !defined(MS_WINDOWS) */
Larry Hastings2f936352014-08-05 14:04:04 +100010278
10279
Victor Stinner161e7b32020-01-24 11:53:44 +010010280#ifdef MS_WINDOWS
10281/*[clinic input]
10282os.unsetenv
10283 name: unicode
10284 /
10285
10286Delete an environment variable.
10287[clinic start generated code]*/
10288
10289static PyObject *
10290os_unsetenv_impl(PyObject *module, PyObject *name)
10291/*[clinic end generated code: output=54c4137ab1834f02 input=4d6a1747cc526d2f]*/
10292{
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010293 if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
10294 return NULL;
10295 }
Victor Stinner161e7b32020-01-24 11:53:44 +010010296 return win32_putenv(name, NULL);
10297}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010298#else
Larry Hastings2f936352014-08-05 14:04:04 +100010299/*[clinic input]
10300os.unsetenv
10301 name: FSConverter
10302 /
10303
10304Delete an environment variable.
10305[clinic start generated code]*/
10306
Larry Hastings2f936352014-08-05 14:04:04 +100010307static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010308os_unsetenv_impl(PyObject *module, PyObject *name)
10309/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010310{
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010311 if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
10312 return NULL;
10313 }
Victor Stinner984890f2011-11-24 13:53:38 +010010314#ifdef HAVE_BROKEN_UNSETENV
10315 unsetenv(PyBytes_AS_STRING(name));
10316#else
Victor Stinner161e7b32020-01-24 11:53:44 +010010317 int err = unsetenv(PyBytes_AS_STRING(name));
10318 if (err) {
Victor Stinner60b385e2011-11-22 22:01:28 +010010319 return posix_error();
Victor Stinner161e7b32020-01-24 11:53:44 +010010320 }
Victor Stinner984890f2011-11-24 13:53:38 +010010321#endif
Guido van Rossumc524d952001-10-19 01:31:59 +000010322
Victor Stinner84ae1182010-05-06 22:05:07 +000010323 Py_RETURN_NONE;
Guido van Rossumc524d952001-10-19 01:31:59 +000010324}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010325#endif /* !MS_WINDOWS */
Guido van Rossumc524d952001-10-19 01:31:59 +000010326
Larry Hastings2f936352014-08-05 14:04:04 +100010327
10328/*[clinic input]
10329os.strerror
10330
10331 code: int
10332 /
10333
10334Translate an error code to a message string.
10335[clinic start generated code]*/
10336
Larry Hastings2f936352014-08-05 14:04:04 +100010337static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010338os_strerror_impl(PyObject *module, int code)
10339/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010340{
10341 char *message = strerror(code);
Victor Stinner8c62be82010-05-06 00:08:46 +000010342 if (message == NULL) {
10343 PyErr_SetString(PyExc_ValueError,
10344 "strerror() argument out of range");
10345 return NULL;
10346 }
Victor Stinner1b579672011-12-17 05:47:23 +010010347 return PyUnicode_DecodeLocale(message, "surrogateescape");
Guido van Rossumb6a47161997-09-15 22:54:34 +000010348}
Guido van Rossumb6a47161997-09-15 22:54:34 +000010349
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010350
Guido van Rossumc9641791998-08-04 15:26:23 +000010351#ifdef HAVE_SYS_WAIT_H
Fred Drake106c1a02002-04-23 15:58:02 +000010352#ifdef WCOREDUMP
Larry Hastings2f936352014-08-05 14:04:04 +100010353/*[clinic input]
10354os.WCOREDUMP -> bool
10355
10356 status: int
10357 /
10358
10359Return True if the process returning status was dumped to a core file.
10360[clinic start generated code]*/
10361
Larry Hastings2f936352014-08-05 14:04:04 +100010362static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010363os_WCOREDUMP_impl(PyObject *module, int status)
10364/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010365{
10366 WAIT_TYPE wait_status;
10367 WAIT_STATUS_INT(wait_status) = status;
10368 return WCOREDUMP(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010369}
10370#endif /* WCOREDUMP */
10371
Larry Hastings2f936352014-08-05 14:04:04 +100010372
Fred Drake106c1a02002-04-23 15:58:02 +000010373#ifdef WIFCONTINUED
Larry Hastings2f936352014-08-05 14:04:04 +100010374/*[clinic input]
10375os.WIFCONTINUED -> bool
10376
10377 status: int
10378
10379Return True if a particular process was continued from a job control stop.
10380
10381Return True if the process returning status was continued from a
10382job control stop.
10383[clinic start generated code]*/
10384
Larry Hastings2f936352014-08-05 14:04:04 +100010385static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010386os_WIFCONTINUED_impl(PyObject *module, int status)
10387/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010388{
10389 WAIT_TYPE wait_status;
10390 WAIT_STATUS_INT(wait_status) = status;
10391 return WIFCONTINUED(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010392}
10393#endif /* WIFCONTINUED */
10394
Larry Hastings2f936352014-08-05 14:04:04 +100010395
Guido van Rossumc9641791998-08-04 15:26:23 +000010396#ifdef WIFSTOPPED
Larry Hastings2f936352014-08-05 14:04:04 +100010397/*[clinic input]
10398os.WIFSTOPPED -> bool
10399
10400 status: int
10401
10402Return True if the process returning status was stopped.
10403[clinic start generated code]*/
10404
Larry Hastings2f936352014-08-05 14:04:04 +100010405static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010406os_WIFSTOPPED_impl(PyObject *module, int status)
10407/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010408{
10409 WAIT_TYPE wait_status;
10410 WAIT_STATUS_INT(wait_status) = status;
10411 return WIFSTOPPED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010412}
10413#endif /* WIFSTOPPED */
10414
Larry Hastings2f936352014-08-05 14:04:04 +100010415
Guido van Rossumc9641791998-08-04 15:26:23 +000010416#ifdef WIFSIGNALED
Larry Hastings2f936352014-08-05 14:04:04 +100010417/*[clinic input]
10418os.WIFSIGNALED -> bool
10419
10420 status: int
10421
10422Return True if the process returning status was terminated by a signal.
10423[clinic start generated code]*/
10424
Larry Hastings2f936352014-08-05 14:04:04 +100010425static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010426os_WIFSIGNALED_impl(PyObject *module, int status)
10427/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010428{
10429 WAIT_TYPE wait_status;
10430 WAIT_STATUS_INT(wait_status) = status;
10431 return WIFSIGNALED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010432}
10433#endif /* WIFSIGNALED */
10434
Larry Hastings2f936352014-08-05 14:04:04 +100010435
Guido van Rossumc9641791998-08-04 15:26:23 +000010436#ifdef WIFEXITED
Larry Hastings2f936352014-08-05 14:04:04 +100010437/*[clinic input]
10438os.WIFEXITED -> bool
10439
10440 status: int
10441
10442Return True if the process returning status exited via the exit() system call.
10443[clinic start generated code]*/
10444
Larry Hastings2f936352014-08-05 14:04:04 +100010445static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010446os_WIFEXITED_impl(PyObject *module, int status)
10447/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010448{
10449 WAIT_TYPE wait_status;
10450 WAIT_STATUS_INT(wait_status) = status;
10451 return WIFEXITED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010452}
10453#endif /* WIFEXITED */
10454
Larry Hastings2f936352014-08-05 14:04:04 +100010455
Guido van Rossum54ecc3d1999-01-27 17:53:11 +000010456#ifdef WEXITSTATUS
Larry Hastings2f936352014-08-05 14:04:04 +100010457/*[clinic input]
10458os.WEXITSTATUS -> int
10459
10460 status: int
10461
10462Return the process return code from status.
10463[clinic start generated code]*/
10464
Larry Hastings2f936352014-08-05 14:04:04 +100010465static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010466os_WEXITSTATUS_impl(PyObject *module, int status)
10467/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010468{
10469 WAIT_TYPE wait_status;
10470 WAIT_STATUS_INT(wait_status) = status;
10471 return WEXITSTATUS(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010472}
10473#endif /* WEXITSTATUS */
10474
Larry Hastings2f936352014-08-05 14:04:04 +100010475
Guido van Rossumc9641791998-08-04 15:26:23 +000010476#ifdef WTERMSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010477/*[clinic input]
10478os.WTERMSIG -> int
10479
10480 status: int
10481
10482Return the signal that terminated the process that provided the status value.
10483[clinic start generated code]*/
10484
Larry Hastings2f936352014-08-05 14:04:04 +100010485static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010486os_WTERMSIG_impl(PyObject *module, int status)
10487/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010488{
10489 WAIT_TYPE wait_status;
10490 WAIT_STATUS_INT(wait_status) = status;
10491 return WTERMSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010492}
10493#endif /* WTERMSIG */
10494
Larry Hastings2f936352014-08-05 14:04:04 +100010495
Guido van Rossumc9641791998-08-04 15:26:23 +000010496#ifdef WSTOPSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010497/*[clinic input]
10498os.WSTOPSIG -> int
10499
10500 status: int
10501
10502Return the signal that stopped the process that provided the status value.
10503[clinic start generated code]*/
10504
Larry Hastings2f936352014-08-05 14:04:04 +100010505static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010506os_WSTOPSIG_impl(PyObject *module, int status)
10507/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010508{
10509 WAIT_TYPE wait_status;
10510 WAIT_STATUS_INT(wait_status) = status;
10511 return WSTOPSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010512}
10513#endif /* WSTOPSIG */
Guido van Rossumc9641791998-08-04 15:26:23 +000010514#endif /* HAVE_SYS_WAIT_H */
10515
10516
Thomas Wouters477c8d52006-05-27 19:21:47 +000010517#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossumd5753e11999-10-19 13:29:23 +000010518#ifdef _SCO_DS
10519/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
10520 needed definitions in sys/statvfs.h */
10521#define _SVID3
10522#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000010523#include <sys/statvfs.h>
10524
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010525static PyObject*
10526_pystatvfs_fromstructstatvfs(struct statvfs st) {
Eddie Elizondob3966632019-11-05 07:16:14 -080010527 PyObject *StatVFSResultType = _posixstate_global->StatVFSResultType;
10528 PyObject *v = PyStructSequence_New((PyTypeObject *)StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000010529 if (v == NULL)
10530 return NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010531
10532#if !defined(HAVE_LARGEFILE_SUPPORT)
Victor Stinner8c62be82010-05-06 00:08:46 +000010533 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10534 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10535 PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
10536 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
10537 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
10538 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
10539 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
10540 PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
10541 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10542 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010543#else
Victor Stinner8c62be82010-05-06 00:08:46 +000010544 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10545 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10546 PyStructSequence_SET_ITEM(v, 2,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010547 PyLong_FromLongLong((long long) st.f_blocks));
Victor Stinner8c62be82010-05-06 00:08:46 +000010548 PyStructSequence_SET_ITEM(v, 3,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010549 PyLong_FromLongLong((long long) st.f_bfree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010550 PyStructSequence_SET_ITEM(v, 4,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010551 PyLong_FromLongLong((long long) st.f_bavail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010552 PyStructSequence_SET_ITEM(v, 5,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010553 PyLong_FromLongLong((long long) st.f_files));
Victor Stinner8c62be82010-05-06 00:08:46 +000010554 PyStructSequence_SET_ITEM(v, 6,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010555 PyLong_FromLongLong((long long) st.f_ffree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010556 PyStructSequence_SET_ITEM(v, 7,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010557 PyLong_FromLongLong((long long) st.f_favail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010558 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10559 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010560#endif
Michael Felt502d5512018-01-05 13:01:58 +010010561/* The _ALL_SOURCE feature test macro defines f_fsid as a structure
10562 * (issue #32390). */
10563#if defined(_AIX) && defined(_ALL_SOURCE)
10564 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
10565#else
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +010010566 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid));
Michael Felt502d5512018-01-05 13:01:58 +010010567#endif
Victor Stinnerf0a7bac2013-10-30 18:55:24 +010010568 if (PyErr_Occurred()) {
10569 Py_DECREF(v);
10570 return NULL;
10571 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010572
Victor Stinner8c62be82010-05-06 00:08:46 +000010573 return v;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010574}
10575
Larry Hastings2f936352014-08-05 14:04:04 +100010576
10577/*[clinic input]
10578os.fstatvfs
10579 fd: int
10580 /
10581
10582Perform an fstatvfs system call on the given fd.
10583
10584Equivalent to statvfs(fd).
10585[clinic start generated code]*/
10586
Larry Hastings2f936352014-08-05 14:04:04 +100010587static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010588os_fstatvfs_impl(PyObject *module, int fd)
10589/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010590{
10591 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010592 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010593 struct statvfs st;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010594
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010595 do {
10596 Py_BEGIN_ALLOW_THREADS
10597 result = fstatvfs(fd, &st);
10598 Py_END_ALLOW_THREADS
10599 } while (result != 0 && errno == EINTR &&
10600 !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +100010601 if (result != 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010602 return (!async_err) ? posix_error() : NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010603
Victor Stinner8c62be82010-05-06 00:08:46 +000010604 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010605}
Larry Hastings2f936352014-08-05 14:04:04 +100010606#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
Guido van Rossum94f6f721999-01-06 18:42:14 +000010607
10608
Thomas Wouters477c8d52006-05-27 19:21:47 +000010609#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossum94f6f721999-01-06 18:42:14 +000010610#include <sys/statvfs.h>
Larry Hastings2f936352014-08-05 14:04:04 +100010611/*[clinic input]
10612os.statvfs
Guido van Rossum94f6f721999-01-06 18:42:14 +000010613
Larry Hastings2f936352014-08-05 14:04:04 +100010614 path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
10615
10616Perform a statvfs system call on the given path.
10617
10618path may always be specified as a string.
10619On some platforms, path may also be specified as an open file descriptor.
10620 If this functionality is unavailable, using it raises an exception.
10621[clinic start generated code]*/
10622
Larry Hastings2f936352014-08-05 14:04:04 +100010623static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010624os_statvfs_impl(PyObject *module, path_t *path)
10625/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010626{
10627 int result;
10628 struct statvfs st;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010629
10630 Py_BEGIN_ALLOW_THREADS
10631#ifdef HAVE_FSTATVFS
Larry Hastings2f936352014-08-05 14:04:04 +100010632 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -070010633#ifdef __APPLE__
10634 /* handle weak-linking on Mac OS X 10.3 */
10635 if (fstatvfs == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010636 fd_specified("statvfs", path->fd);
10637 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010638 }
10639#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010640 result = fstatvfs(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010641 }
10642 else
10643#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010644 result = statvfs(path->narrow, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010645 Py_END_ALLOW_THREADS
10646
10647 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100010648 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010649 }
10650
Larry Hastings2f936352014-08-05 14:04:04 +100010651 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010652}
Larry Hastings2f936352014-08-05 14:04:04 +100010653#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
10654
Guido van Rossum94f6f721999-01-06 18:42:14 +000010655
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010656#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010657/*[clinic input]
10658os._getdiskusage
10659
Steve Dower23ad6d02018-02-22 10:39:10 -080010660 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +100010661
10662Return disk usage statistics about the given path as a (total, free) tuple.
10663[clinic start generated code]*/
10664
Larry Hastings2f936352014-08-05 14:04:04 +100010665static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -080010666os__getdiskusage_impl(PyObject *module, path_t *path)
10667/*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010668{
10669 BOOL retval;
10670 ULARGE_INTEGER _, total, free;
Joe Pamerc8c02492018-09-25 10:57:36 -040010671 DWORD err = 0;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010672
10673 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -080010674 retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010675 Py_END_ALLOW_THREADS
Joe Pamerc8c02492018-09-25 10:57:36 -040010676 if (retval == 0) {
10677 if (GetLastError() == ERROR_DIRECTORY) {
10678 wchar_t *dir_path = NULL;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010679
Joe Pamerc8c02492018-09-25 10:57:36 -040010680 dir_path = PyMem_New(wchar_t, path->length + 1);
10681 if (dir_path == NULL) {
10682 return PyErr_NoMemory();
10683 }
10684
10685 wcscpy_s(dir_path, path->length + 1, path->wide);
10686
10687 if (_dirnameW(dir_path) != -1) {
10688 Py_BEGIN_ALLOW_THREADS
10689 retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
10690 Py_END_ALLOW_THREADS
10691 }
10692 /* Record the last error in case it's modified by PyMem_Free. */
10693 err = GetLastError();
10694 PyMem_Free(dir_path);
10695 if (retval) {
10696 goto success;
10697 }
10698 }
10699 return PyErr_SetFromWindowsErr(err);
10700 }
10701
10702success:
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010703 return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
10704}
Larry Hastings2f936352014-08-05 14:04:04 +100010705#endif /* MS_WINDOWS */
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010706
10707
Fred Drakec9680921999-12-13 16:37:25 +000010708/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
10709 * It maps strings representing configuration variable names to
10710 * integer values, allowing those functions to be called with the
Thomas Wouters7e474022000-07-16 12:04:32 +000010711 * magic names instead of polluting the module's namespace with tons of
Fred Drake12c6e2d1999-12-14 21:25:03 +000010712 * rarely-used constants. There are three separate tables that use
10713 * these definitions.
Fred Drakebec628d1999-12-15 18:31:10 +000010714 *
10715 * This code is always included, even if none of the interfaces that
10716 * need it are included. The #if hackery needed to avoid it would be
10717 * sufficiently pervasive that it's not worth the loss of readability.
Fred Drakec9680921999-12-13 16:37:25 +000010718 */
10719struct constdef {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020010720 const char *name;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010721 int value;
Fred Drakec9680921999-12-13 16:37:25 +000010722};
10723
Fred Drake12c6e2d1999-12-14 21:25:03 +000010724static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010725conv_confname(PyObject *arg, int *valuep, struct constdef *table,
Guido van Rossum7d5baac2007-08-27 23:24:46 +000010726 size_t tablesize)
Fred Drake12c6e2d1999-12-14 21:25:03 +000010727{
Christian Heimes217cfd12007-12-02 14:31:20 +000010728 if (PyLong_Check(arg)) {
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010729 int value = _PyLong_AsInt(arg);
10730 if (value == -1 && PyErr_Occurred())
10731 return 0;
10732 *valuep = value;
Stefan Krah0e803b32010-11-26 16:16:47 +000010733 return 1;
Fred Drake12c6e2d1999-12-14 21:25:03 +000010734 }
Guido van Rossumbce56a62007-05-10 18:04:33 +000010735 else {
Stefan Krah0e803b32010-11-26 16:16:47 +000010736 /* look up the value in the table using a binary search */
10737 size_t lo = 0;
10738 size_t mid;
10739 size_t hi = tablesize;
10740 int cmp;
10741 const char *confname;
10742 if (!PyUnicode_Check(arg)) {
10743 PyErr_SetString(PyExc_TypeError,
10744 "configuration names must be strings or integers");
10745 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010746 }
Serhiy Storchaka06515832016-11-20 09:13:07 +020010747 confname = PyUnicode_AsUTF8(arg);
Stefan Krah0e803b32010-11-26 16:16:47 +000010748 if (confname == NULL)
10749 return 0;
10750 while (lo < hi) {
10751 mid = (lo + hi) / 2;
10752 cmp = strcmp(confname, table[mid].name);
10753 if (cmp < 0)
10754 hi = mid;
10755 else if (cmp > 0)
10756 lo = mid + 1;
10757 else {
10758 *valuep = table[mid].value;
10759 return 1;
10760 }
10761 }
10762 PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
10763 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010764 }
Fred Drake12c6e2d1999-12-14 21:25:03 +000010765}
10766
10767
10768#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
10769static struct constdef posix_constants_pathconf[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010770#ifdef _PC_ABI_AIO_XFER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010771 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000010772#endif
10773#ifdef _PC_ABI_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010774 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010775#endif
Fred Drakec9680921999-12-13 16:37:25 +000010776#ifdef _PC_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010777 {"PC_ASYNC_IO", _PC_ASYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010778#endif
10779#ifdef _PC_CHOWN_RESTRICTED
Victor Stinner8c62be82010-05-06 00:08:46 +000010780 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
Fred Drakec9680921999-12-13 16:37:25 +000010781#endif
10782#ifdef _PC_FILESIZEBITS
Victor Stinner8c62be82010-05-06 00:08:46 +000010783 {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
Fred Drakec9680921999-12-13 16:37:25 +000010784#endif
10785#ifdef _PC_LAST
Victor Stinner8c62be82010-05-06 00:08:46 +000010786 {"PC_LAST", _PC_LAST},
Fred Drakec9680921999-12-13 16:37:25 +000010787#endif
10788#ifdef _PC_LINK_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010789 {"PC_LINK_MAX", _PC_LINK_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010790#endif
10791#ifdef _PC_MAX_CANON
Victor Stinner8c62be82010-05-06 00:08:46 +000010792 {"PC_MAX_CANON", _PC_MAX_CANON},
Fred Drakec9680921999-12-13 16:37:25 +000010793#endif
10794#ifdef _PC_MAX_INPUT
Victor Stinner8c62be82010-05-06 00:08:46 +000010795 {"PC_MAX_INPUT", _PC_MAX_INPUT},
Fred Drakec9680921999-12-13 16:37:25 +000010796#endif
10797#ifdef _PC_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010798 {"PC_NAME_MAX", _PC_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010799#endif
10800#ifdef _PC_NO_TRUNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010801 {"PC_NO_TRUNC", _PC_NO_TRUNC},
Fred Drakec9680921999-12-13 16:37:25 +000010802#endif
10803#ifdef _PC_PATH_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010804 {"PC_PATH_MAX", _PC_PATH_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010805#endif
10806#ifdef _PC_PIPE_BUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010807 {"PC_PIPE_BUF", _PC_PIPE_BUF},
Fred Drakec9680921999-12-13 16:37:25 +000010808#endif
10809#ifdef _PC_PRIO_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010810 {"PC_PRIO_IO", _PC_PRIO_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010811#endif
10812#ifdef _PC_SOCK_MAXBUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010813 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
Fred Drakec9680921999-12-13 16:37:25 +000010814#endif
10815#ifdef _PC_SYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010816 {"PC_SYNC_IO", _PC_SYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010817#endif
10818#ifdef _PC_VDISABLE
Victor Stinner8c62be82010-05-06 00:08:46 +000010819 {"PC_VDISABLE", _PC_VDISABLE},
Fred Drakec9680921999-12-13 16:37:25 +000010820#endif
Jesus Cea7e9065c2010-10-25 13:02:04 +000010821#ifdef _PC_ACL_ENABLED
10822 {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
10823#endif
10824#ifdef _PC_MIN_HOLE_SIZE
10825 {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
10826#endif
10827#ifdef _PC_ALLOC_SIZE_MIN
10828 {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
10829#endif
10830#ifdef _PC_REC_INCR_XFER_SIZE
10831 {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
10832#endif
10833#ifdef _PC_REC_MAX_XFER_SIZE
10834 {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
10835#endif
10836#ifdef _PC_REC_MIN_XFER_SIZE
10837 {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
10838#endif
10839#ifdef _PC_REC_XFER_ALIGN
10840 {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
10841#endif
10842#ifdef _PC_SYMLINK_MAX
10843 {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
10844#endif
10845#ifdef _PC_XATTR_ENABLED
10846 {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
10847#endif
10848#ifdef _PC_XATTR_EXISTS
10849 {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
10850#endif
10851#ifdef _PC_TIMESTAMP_RESOLUTION
10852 {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
10853#endif
Fred Drakec9680921999-12-13 16:37:25 +000010854};
10855
Fred Drakec9680921999-12-13 16:37:25 +000010856static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010857conv_path_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010858{
10859 return conv_confname(arg, valuep, posix_constants_pathconf,
10860 sizeof(posix_constants_pathconf)
10861 / sizeof(struct constdef));
10862}
10863#endif
10864
Larry Hastings2f936352014-08-05 14:04:04 +100010865
Fred Drakec9680921999-12-13 16:37:25 +000010866#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010867/*[clinic input]
10868os.fpathconf -> long
10869
10870 fd: int
10871 name: path_confname
10872 /
10873
10874Return the configuration limit name for the file descriptor fd.
10875
10876If there is no limit, return -1.
10877[clinic start generated code]*/
10878
Larry Hastings2f936352014-08-05 14:04:04 +100010879static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010880os_fpathconf_impl(PyObject *module, int fd, int name)
10881/*[clinic end generated code: output=d5b7042425fc3e21 input=5942a024d3777810]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010882{
10883 long limit;
10884
10885 errno = 0;
10886 limit = fpathconf(fd, name);
10887 if (limit == -1 && errno != 0)
10888 posix_error();
10889
10890 return limit;
10891}
10892#endif /* HAVE_FPATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010893
10894
10895#ifdef HAVE_PATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010896/*[clinic input]
10897os.pathconf -> long
10898 path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
10899 name: path_confname
10900
10901Return the configuration limit name for the file or directory path.
10902
10903If there is no limit, return -1.
10904On some platforms, path may also be specified as an open file descriptor.
10905 If this functionality is unavailable, using it raises an exception.
10906[clinic start generated code]*/
10907
Larry Hastings2f936352014-08-05 14:04:04 +100010908static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010909os_pathconf_impl(PyObject *module, path_t *path, int name)
10910/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010911{
Victor Stinner8c62be82010-05-06 00:08:46 +000010912 long limit;
Fred Drakec9680921999-12-13 16:37:25 +000010913
Victor Stinner8c62be82010-05-06 00:08:46 +000010914 errno = 0;
Georg Brandl306336b2012-06-24 12:55:33 +020010915#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010916 if (path->fd != -1)
10917 limit = fpathconf(path->fd, name);
Georg Brandl306336b2012-06-24 12:55:33 +020010918 else
10919#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010920 limit = pathconf(path->narrow, name);
Victor Stinner8c62be82010-05-06 00:08:46 +000010921 if (limit == -1 && errno != 0) {
10922 if (errno == EINVAL)
Stefan Krah99439262010-11-26 12:58:05 +000010923 /* could be a path or name problem */
10924 posix_error();
Fred Drakec9680921999-12-13 16:37:25 +000010925 else
Larry Hastings2f936352014-08-05 14:04:04 +100010926 path_error(path);
Victor Stinner8c62be82010-05-06 00:08:46 +000010927 }
Larry Hastings2f936352014-08-05 14:04:04 +100010928
10929 return limit;
Fred Drakec9680921999-12-13 16:37:25 +000010930}
Larry Hastings2f936352014-08-05 14:04:04 +100010931#endif /* HAVE_PATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010932
10933#ifdef HAVE_CONFSTR
10934static struct constdef posix_constants_confstr[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010935#ifdef _CS_ARCHITECTURE
Victor Stinner8c62be82010-05-06 00:08:46 +000010936 {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
Fred Draked86ed291999-12-15 15:34:33 +000010937#endif
Mark Dickinson876d7c82010-04-16 12:47:52 +000010938#ifdef _CS_GNU_LIBC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010939 {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010940#endif
10941#ifdef _CS_GNU_LIBPTHREAD_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010942 {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010943#endif
Fred Draked86ed291999-12-15 15:34:33 +000010944#ifdef _CS_HOSTNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010945 {"CS_HOSTNAME", _CS_HOSTNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010946#endif
10947#ifdef _CS_HW_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010948 {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010949#endif
10950#ifdef _CS_HW_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010951 {"CS_HW_SERIAL", _CS_HW_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010952#endif
10953#ifdef _CS_INITTAB_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010954 {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010955#endif
Fred Drakec9680921999-12-13 16:37:25 +000010956#ifdef _CS_LFS64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010957 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010958#endif
10959#ifdef _CS_LFS64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010960 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010961#endif
10962#ifdef _CS_LFS64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010963 {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010964#endif
10965#ifdef _CS_LFS64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010966 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010967#endif
10968#ifdef _CS_LFS_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010969 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010970#endif
10971#ifdef _CS_LFS_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010972 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010973#endif
10974#ifdef _CS_LFS_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010975 {"CS_LFS_LIBS", _CS_LFS_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010976#endif
10977#ifdef _CS_LFS_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010978 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010979#endif
Fred Draked86ed291999-12-15 15:34:33 +000010980#ifdef _CS_MACHINE
Victor Stinner8c62be82010-05-06 00:08:46 +000010981 {"CS_MACHINE", _CS_MACHINE},
Fred Draked86ed291999-12-15 15:34:33 +000010982#endif
Fred Drakec9680921999-12-13 16:37:25 +000010983#ifdef _CS_PATH
Victor Stinner8c62be82010-05-06 00:08:46 +000010984 {"CS_PATH", _CS_PATH},
Fred Drakec9680921999-12-13 16:37:25 +000010985#endif
Fred Draked86ed291999-12-15 15:34:33 +000010986#ifdef _CS_RELEASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010987 {"CS_RELEASE", _CS_RELEASE},
Fred Draked86ed291999-12-15 15:34:33 +000010988#endif
10989#ifdef _CS_SRPC_DOMAIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010990 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
Fred Draked86ed291999-12-15 15:34:33 +000010991#endif
10992#ifdef _CS_SYSNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010993 {"CS_SYSNAME", _CS_SYSNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010994#endif
10995#ifdef _CS_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010996 {"CS_VERSION", _CS_VERSION},
Fred Draked86ed291999-12-15 15:34:33 +000010997#endif
Fred Drakec9680921999-12-13 16:37:25 +000010998#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010999 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011000#endif
11001#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011002 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011003#endif
11004#ifdef _CS_XBS5_ILP32_OFF32_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011005 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011006#endif
11007#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011008 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011009#endif
11010#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011011 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011012#endif
11013#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011014 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011015#endif
11016#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011017 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011018#endif
11019#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011020 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011021#endif
11022#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011023 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011024#endif
11025#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011026 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011027#endif
11028#ifdef _CS_XBS5_LP64_OFF64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011029 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011030#endif
11031#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011032 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011033#endif
11034#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011035 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011036#endif
11037#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011038 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011039#endif
11040#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011041 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011042#endif
11043#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011044 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011045#endif
Fred Draked86ed291999-12-15 15:34:33 +000011046#ifdef _MIPS_CS_AVAIL_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000011047 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000011048#endif
11049#ifdef _MIPS_CS_BASE
Victor Stinner8c62be82010-05-06 00:08:46 +000011050 {"MIPS_CS_BASE", _MIPS_CS_BASE},
Fred Draked86ed291999-12-15 15:34:33 +000011051#endif
11052#ifdef _MIPS_CS_HOSTID
Victor Stinner8c62be82010-05-06 00:08:46 +000011053 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
Fred Draked86ed291999-12-15 15:34:33 +000011054#endif
11055#ifdef _MIPS_CS_HW_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011056 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000011057#endif
11058#ifdef _MIPS_CS_NUM_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000011059 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000011060#endif
11061#ifdef _MIPS_CS_OSREL_MAJ
Victor Stinner8c62be82010-05-06 00:08:46 +000011062 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
Fred Draked86ed291999-12-15 15:34:33 +000011063#endif
11064#ifdef _MIPS_CS_OSREL_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011065 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
Fred Draked86ed291999-12-15 15:34:33 +000011066#endif
11067#ifdef _MIPS_CS_OSREL_PATCH
Victor Stinner8c62be82010-05-06 00:08:46 +000011068 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
Fred Draked86ed291999-12-15 15:34:33 +000011069#endif
11070#ifdef _MIPS_CS_OS_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011071 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000011072#endif
11073#ifdef _MIPS_CS_OS_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000011074 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000011075#endif
11076#ifdef _MIPS_CS_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000011077 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000011078#endif
11079#ifdef _MIPS_CS_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000011080 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000011081#endif
11082#ifdef _MIPS_CS_VENDOR
Victor Stinner8c62be82010-05-06 00:08:46 +000011083 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
Fred Draked86ed291999-12-15 15:34:33 +000011084#endif
Fred Drakec9680921999-12-13 16:37:25 +000011085};
11086
11087static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011088conv_confstr_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011089{
11090 return conv_confname(arg, valuep, posix_constants_confstr,
11091 sizeof(posix_constants_confstr)
11092 / sizeof(struct constdef));
11093}
11094
Larry Hastings2f936352014-08-05 14:04:04 +100011095
11096/*[clinic input]
11097os.confstr
11098
11099 name: confstr_confname
11100 /
11101
11102Return a string-valued system configuration variable.
11103[clinic start generated code]*/
11104
Larry Hastings2f936352014-08-05 14:04:04 +100011105static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011106os_confstr_impl(PyObject *module, int name)
11107/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
Fred Drakec9680921999-12-13 16:37:25 +000011108{
11109 PyObject *result = NULL;
Victor Stinnercb043522010-09-10 23:49:04 +000011110 char buffer[255];
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011111 size_t len;
Fred Drakec9680921999-12-13 16:37:25 +000011112
Victor Stinnercb043522010-09-10 23:49:04 +000011113 errno = 0;
11114 len = confstr(name, buffer, sizeof(buffer));
11115 if (len == 0) {
11116 if (errno) {
11117 posix_error();
11118 return NULL;
Fred Drakec9680921999-12-13 16:37:25 +000011119 }
11120 else {
Victor Stinnercb043522010-09-10 23:49:04 +000011121 Py_RETURN_NONE;
Fred Drakec9680921999-12-13 16:37:25 +000011122 }
11123 }
Victor Stinnercb043522010-09-10 23:49:04 +000011124
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011125 if (len >= sizeof(buffer)) {
Victor Stinnercbc18f32014-12-05 22:51:51 +010011126 size_t len2;
Victor Stinnercb043522010-09-10 23:49:04 +000011127 char *buf = PyMem_Malloc(len);
11128 if (buf == NULL)
11129 return PyErr_NoMemory();
Victor Stinnercbc18f32014-12-05 22:51:51 +010011130 len2 = confstr(name, buf, len);
11131 assert(len == len2);
Christian Heimes8714cfd2015-04-21 10:57:41 +020011132 result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
Victor Stinnercb043522010-09-10 23:49:04 +000011133 PyMem_Free(buf);
11134 }
11135 else
11136 result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
Fred Drakec9680921999-12-13 16:37:25 +000011137 return result;
11138}
Larry Hastings2f936352014-08-05 14:04:04 +100011139#endif /* HAVE_CONFSTR */
Fred Drakec9680921999-12-13 16:37:25 +000011140
11141
11142#ifdef HAVE_SYSCONF
11143static struct constdef posix_constants_sysconf[] = {
11144#ifdef _SC_2_CHAR_TERM
Victor Stinner8c62be82010-05-06 00:08:46 +000011145 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
Fred Drakec9680921999-12-13 16:37:25 +000011146#endif
11147#ifdef _SC_2_C_BIND
Victor Stinner8c62be82010-05-06 00:08:46 +000011148 {"SC_2_C_BIND", _SC_2_C_BIND},
Fred Drakec9680921999-12-13 16:37:25 +000011149#endif
11150#ifdef _SC_2_C_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011151 {"SC_2_C_DEV", _SC_2_C_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011152#endif
11153#ifdef _SC_2_C_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011154 {"SC_2_C_VERSION", _SC_2_C_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011155#endif
11156#ifdef _SC_2_FORT_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011157 {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011158#endif
11159#ifdef _SC_2_FORT_RUN
Victor Stinner8c62be82010-05-06 00:08:46 +000011160 {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
Fred Drakec9680921999-12-13 16:37:25 +000011161#endif
11162#ifdef _SC_2_LOCALEDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000011163 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
Fred Drakec9680921999-12-13 16:37:25 +000011164#endif
11165#ifdef _SC_2_SW_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011166 {"SC_2_SW_DEV", _SC_2_SW_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011167#endif
11168#ifdef _SC_2_UPE
Victor Stinner8c62be82010-05-06 00:08:46 +000011169 {"SC_2_UPE", _SC_2_UPE},
Fred Drakec9680921999-12-13 16:37:25 +000011170#endif
11171#ifdef _SC_2_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011172 {"SC_2_VERSION", _SC_2_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011173#endif
Fred Draked86ed291999-12-15 15:34:33 +000011174#ifdef _SC_ABI_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011175 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
Fred Draked86ed291999-12-15 15:34:33 +000011176#endif
11177#ifdef _SC_ACL
Victor Stinner8c62be82010-05-06 00:08:46 +000011178 {"SC_ACL", _SC_ACL},
Fred Draked86ed291999-12-15 15:34:33 +000011179#endif
Fred Drakec9680921999-12-13 16:37:25 +000011180#ifdef _SC_AIO_LISTIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011181 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011182#endif
Fred Drakec9680921999-12-13 16:37:25 +000011183#ifdef _SC_AIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011184 {"SC_AIO_MAX", _SC_AIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011185#endif
11186#ifdef _SC_AIO_PRIO_DELTA_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011187 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011188#endif
11189#ifdef _SC_ARG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011190 {"SC_ARG_MAX", _SC_ARG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011191#endif
11192#ifdef _SC_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011193 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011194#endif
11195#ifdef _SC_ATEXIT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011196 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011197#endif
Fred Draked86ed291999-12-15 15:34:33 +000011198#ifdef _SC_AUDIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011199 {"SC_AUDIT", _SC_AUDIT},
Fred Draked86ed291999-12-15 15:34:33 +000011200#endif
Fred Drakec9680921999-12-13 16:37:25 +000011201#ifdef _SC_AVPHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011202 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011203#endif
11204#ifdef _SC_BC_BASE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011205 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011206#endif
11207#ifdef _SC_BC_DIM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011208 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011209#endif
11210#ifdef _SC_BC_SCALE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011211 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011212#endif
11213#ifdef _SC_BC_STRING_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011214 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011215#endif
Fred Draked86ed291999-12-15 15:34:33 +000011216#ifdef _SC_CAP
Victor Stinner8c62be82010-05-06 00:08:46 +000011217 {"SC_CAP", _SC_CAP},
Fred Draked86ed291999-12-15 15:34:33 +000011218#endif
Fred Drakec9680921999-12-13 16:37:25 +000011219#ifdef _SC_CHARCLASS_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011220 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011221#endif
11222#ifdef _SC_CHAR_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011223 {"SC_CHAR_BIT", _SC_CHAR_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011224#endif
11225#ifdef _SC_CHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011226 {"SC_CHAR_MAX", _SC_CHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011227#endif
11228#ifdef _SC_CHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011229 {"SC_CHAR_MIN", _SC_CHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011230#endif
11231#ifdef _SC_CHILD_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011232 {"SC_CHILD_MAX", _SC_CHILD_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011233#endif
11234#ifdef _SC_CLK_TCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011235 {"SC_CLK_TCK", _SC_CLK_TCK},
Fred Drakec9680921999-12-13 16:37:25 +000011236#endif
11237#ifdef _SC_COHER_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011238 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011239#endif
11240#ifdef _SC_COLL_WEIGHTS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011241 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011242#endif
11243#ifdef _SC_DCACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011244 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011245#endif
11246#ifdef _SC_DCACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011247 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011248#endif
11249#ifdef _SC_DCACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011250 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011251#endif
11252#ifdef _SC_DCACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011253 {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011254#endif
11255#ifdef _SC_DCACHE_TBLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011256 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011257#endif
11258#ifdef _SC_DELAYTIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011259 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011260#endif
11261#ifdef _SC_EQUIV_CLASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011262 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011263#endif
11264#ifdef _SC_EXPR_NEST_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011265 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011266#endif
11267#ifdef _SC_FSYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000011268 {"SC_FSYNC", _SC_FSYNC},
Fred Drakec9680921999-12-13 16:37:25 +000011269#endif
11270#ifdef _SC_GETGR_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011271 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011272#endif
11273#ifdef _SC_GETPW_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011274 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011275#endif
11276#ifdef _SC_ICACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011277 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011278#endif
11279#ifdef _SC_ICACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011280 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011281#endif
11282#ifdef _SC_ICACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011283 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011284#endif
11285#ifdef _SC_ICACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011286 {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011287#endif
Fred Draked86ed291999-12-15 15:34:33 +000011288#ifdef _SC_INF
Victor Stinner8c62be82010-05-06 00:08:46 +000011289 {"SC_INF", _SC_INF},
Fred Draked86ed291999-12-15 15:34:33 +000011290#endif
Fred Drakec9680921999-12-13 16:37:25 +000011291#ifdef _SC_INT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011292 {"SC_INT_MAX", _SC_INT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011293#endif
11294#ifdef _SC_INT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011295 {"SC_INT_MIN", _SC_INT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011296#endif
11297#ifdef _SC_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011298 {"SC_IOV_MAX", _SC_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011299#endif
Fred Draked86ed291999-12-15 15:34:33 +000011300#ifdef _SC_IP_SECOPTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011301 {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
Fred Draked86ed291999-12-15 15:34:33 +000011302#endif
Fred Drakec9680921999-12-13 16:37:25 +000011303#ifdef _SC_JOB_CONTROL
Victor Stinner8c62be82010-05-06 00:08:46 +000011304 {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
Fred Drakec9680921999-12-13 16:37:25 +000011305#endif
Fred Draked86ed291999-12-15 15:34:33 +000011306#ifdef _SC_KERN_POINTERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011307 {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
Fred Draked86ed291999-12-15 15:34:33 +000011308#endif
11309#ifdef _SC_KERN_SIM
Victor Stinner8c62be82010-05-06 00:08:46 +000011310 {"SC_KERN_SIM", _SC_KERN_SIM},
Fred Draked86ed291999-12-15 15:34:33 +000011311#endif
Fred Drakec9680921999-12-13 16:37:25 +000011312#ifdef _SC_LINE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011313 {"SC_LINE_MAX", _SC_LINE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011314#endif
11315#ifdef _SC_LOGIN_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011316 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011317#endif
11318#ifdef _SC_LOGNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011319 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011320#endif
11321#ifdef _SC_LONG_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011322 {"SC_LONG_BIT", _SC_LONG_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011323#endif
Fred Draked86ed291999-12-15 15:34:33 +000011324#ifdef _SC_MAC
Victor Stinner8c62be82010-05-06 00:08:46 +000011325 {"SC_MAC", _SC_MAC},
Fred Draked86ed291999-12-15 15:34:33 +000011326#endif
Fred Drakec9680921999-12-13 16:37:25 +000011327#ifdef _SC_MAPPED_FILES
Victor Stinner8c62be82010-05-06 00:08:46 +000011328 {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
Fred Drakec9680921999-12-13 16:37:25 +000011329#endif
11330#ifdef _SC_MAXPID
Victor Stinner8c62be82010-05-06 00:08:46 +000011331 {"SC_MAXPID", _SC_MAXPID},
Fred Drakec9680921999-12-13 16:37:25 +000011332#endif
11333#ifdef _SC_MB_LEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011334 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011335#endif
11336#ifdef _SC_MEMLOCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011337 {"SC_MEMLOCK", _SC_MEMLOCK},
Fred Drakec9680921999-12-13 16:37:25 +000011338#endif
11339#ifdef _SC_MEMLOCK_RANGE
Victor Stinner8c62be82010-05-06 00:08:46 +000011340 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
Fred Drakec9680921999-12-13 16:37:25 +000011341#endif
11342#ifdef _SC_MEMORY_PROTECTION
Victor Stinner8c62be82010-05-06 00:08:46 +000011343 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
Fred Drakec9680921999-12-13 16:37:25 +000011344#endif
11345#ifdef _SC_MESSAGE_PASSING
Victor Stinner8c62be82010-05-06 00:08:46 +000011346 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
Fred Drakec9680921999-12-13 16:37:25 +000011347#endif
Fred Draked86ed291999-12-15 15:34:33 +000011348#ifdef _SC_MMAP_FIXED_ALIGNMENT
Victor Stinner8c62be82010-05-06 00:08:46 +000011349 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
Fred Draked86ed291999-12-15 15:34:33 +000011350#endif
Fred Drakec9680921999-12-13 16:37:25 +000011351#ifdef _SC_MQ_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011352 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011353#endif
11354#ifdef _SC_MQ_PRIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011355 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011356#endif
Fred Draked86ed291999-12-15 15:34:33 +000011357#ifdef _SC_NACLS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011358 {"SC_NACLS_MAX", _SC_NACLS_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000011359#endif
Fred Drakec9680921999-12-13 16:37:25 +000011360#ifdef _SC_NGROUPS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011361 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011362#endif
11363#ifdef _SC_NL_ARGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011364 {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011365#endif
11366#ifdef _SC_NL_LANGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011367 {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011368#endif
11369#ifdef _SC_NL_MSGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011370 {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011371#endif
11372#ifdef _SC_NL_NMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011373 {"SC_NL_NMAX", _SC_NL_NMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011374#endif
11375#ifdef _SC_NL_SETMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011376 {"SC_NL_SETMAX", _SC_NL_SETMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011377#endif
11378#ifdef _SC_NL_TEXTMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011379 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011380#endif
11381#ifdef _SC_NPROCESSORS_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011382 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
Fred Drakec9680921999-12-13 16:37:25 +000011383#endif
11384#ifdef _SC_NPROCESSORS_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011385 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
Fred Drakec9680921999-12-13 16:37:25 +000011386#endif
Fred Draked86ed291999-12-15 15:34:33 +000011387#ifdef _SC_NPROC_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011388 {"SC_NPROC_CONF", _SC_NPROC_CONF},
Fred Draked86ed291999-12-15 15:34:33 +000011389#endif
11390#ifdef _SC_NPROC_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011391 {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
Fred Draked86ed291999-12-15 15:34:33 +000011392#endif
Fred Drakec9680921999-12-13 16:37:25 +000011393#ifdef _SC_NZERO
Victor Stinner8c62be82010-05-06 00:08:46 +000011394 {"SC_NZERO", _SC_NZERO},
Fred Drakec9680921999-12-13 16:37:25 +000011395#endif
11396#ifdef _SC_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011397 {"SC_OPEN_MAX", _SC_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011398#endif
11399#ifdef _SC_PAGESIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011400 {"SC_PAGESIZE", _SC_PAGESIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011401#endif
11402#ifdef _SC_PAGE_SIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011403 {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011404#endif
11405#ifdef _SC_PASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011406 {"SC_PASS_MAX", _SC_PASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011407#endif
11408#ifdef _SC_PHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011409 {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011410#endif
11411#ifdef _SC_PII
Victor Stinner8c62be82010-05-06 00:08:46 +000011412 {"SC_PII", _SC_PII},
Fred Drakec9680921999-12-13 16:37:25 +000011413#endif
11414#ifdef _SC_PII_INTERNET
Victor Stinner8c62be82010-05-06 00:08:46 +000011415 {"SC_PII_INTERNET", _SC_PII_INTERNET},
Fred Drakec9680921999-12-13 16:37:25 +000011416#endif
11417#ifdef _SC_PII_INTERNET_DGRAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011418 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
Fred Drakec9680921999-12-13 16:37:25 +000011419#endif
11420#ifdef _SC_PII_INTERNET_STREAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011421 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
Fred Drakec9680921999-12-13 16:37:25 +000011422#endif
11423#ifdef _SC_PII_OSI
Victor Stinner8c62be82010-05-06 00:08:46 +000011424 {"SC_PII_OSI", _SC_PII_OSI},
Fred Drakec9680921999-12-13 16:37:25 +000011425#endif
11426#ifdef _SC_PII_OSI_CLTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011427 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
Fred Drakec9680921999-12-13 16:37:25 +000011428#endif
11429#ifdef _SC_PII_OSI_COTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011430 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
Fred Drakec9680921999-12-13 16:37:25 +000011431#endif
11432#ifdef _SC_PII_OSI_M
Victor Stinner8c62be82010-05-06 00:08:46 +000011433 {"SC_PII_OSI_M", _SC_PII_OSI_M},
Fred Drakec9680921999-12-13 16:37:25 +000011434#endif
11435#ifdef _SC_PII_SOCKET
Victor Stinner8c62be82010-05-06 00:08:46 +000011436 {"SC_PII_SOCKET", _SC_PII_SOCKET},
Fred Drakec9680921999-12-13 16:37:25 +000011437#endif
11438#ifdef _SC_PII_XTI
Victor Stinner8c62be82010-05-06 00:08:46 +000011439 {"SC_PII_XTI", _SC_PII_XTI},
Fred Drakec9680921999-12-13 16:37:25 +000011440#endif
11441#ifdef _SC_POLL
Victor Stinner8c62be82010-05-06 00:08:46 +000011442 {"SC_POLL", _SC_POLL},
Fred Drakec9680921999-12-13 16:37:25 +000011443#endif
11444#ifdef _SC_PRIORITIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011445 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011446#endif
11447#ifdef _SC_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011448 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011449#endif
11450#ifdef _SC_REALTIME_SIGNALS
Victor Stinner8c62be82010-05-06 00:08:46 +000011451 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
Fred Drakec9680921999-12-13 16:37:25 +000011452#endif
11453#ifdef _SC_RE_DUP_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011454 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011455#endif
11456#ifdef _SC_RTSIG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011457 {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011458#endif
11459#ifdef _SC_SAVED_IDS
Victor Stinner8c62be82010-05-06 00:08:46 +000011460 {"SC_SAVED_IDS", _SC_SAVED_IDS},
Fred Drakec9680921999-12-13 16:37:25 +000011461#endif
11462#ifdef _SC_SCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011463 {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011464#endif
11465#ifdef _SC_SCHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011466 {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011467#endif
11468#ifdef _SC_SELECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011469 {"SC_SELECT", _SC_SELECT},
Fred Drakec9680921999-12-13 16:37:25 +000011470#endif
11471#ifdef _SC_SEMAPHORES
Victor Stinner8c62be82010-05-06 00:08:46 +000011472 {"SC_SEMAPHORES", _SC_SEMAPHORES},
Fred Drakec9680921999-12-13 16:37:25 +000011473#endif
11474#ifdef _SC_SEM_NSEMS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011475 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011476#endif
11477#ifdef _SC_SEM_VALUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011478 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011479#endif
11480#ifdef _SC_SHARED_MEMORY_OBJECTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011481 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
Fred Drakec9680921999-12-13 16:37:25 +000011482#endif
11483#ifdef _SC_SHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011484 {"SC_SHRT_MAX", _SC_SHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011485#endif
11486#ifdef _SC_SHRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011487 {"SC_SHRT_MIN", _SC_SHRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011488#endif
11489#ifdef _SC_SIGQUEUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011490 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011491#endif
11492#ifdef _SC_SIGRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011493 {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011494#endif
11495#ifdef _SC_SIGRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011496 {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011497#endif
Fred Draked86ed291999-12-15 15:34:33 +000011498#ifdef _SC_SOFTPOWER
Victor Stinner8c62be82010-05-06 00:08:46 +000011499 {"SC_SOFTPOWER", _SC_SOFTPOWER},
Fred Draked86ed291999-12-15 15:34:33 +000011500#endif
Fred Drakec9680921999-12-13 16:37:25 +000011501#ifdef _SC_SPLIT_CACHE
Victor Stinner8c62be82010-05-06 00:08:46 +000011502 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
Fred Drakec9680921999-12-13 16:37:25 +000011503#endif
11504#ifdef _SC_SSIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011505 {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011506#endif
11507#ifdef _SC_STACK_PROT
Victor Stinner8c62be82010-05-06 00:08:46 +000011508 {"SC_STACK_PROT", _SC_STACK_PROT},
Fred Drakec9680921999-12-13 16:37:25 +000011509#endif
11510#ifdef _SC_STREAM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011511 {"SC_STREAM_MAX", _SC_STREAM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011512#endif
11513#ifdef _SC_SYNCHRONIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011514 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011515#endif
11516#ifdef _SC_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011517 {"SC_THREADS", _SC_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011518#endif
11519#ifdef _SC_THREAD_ATTR_STACKADDR
Victor Stinner8c62be82010-05-06 00:08:46 +000011520 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
Fred Drakec9680921999-12-13 16:37:25 +000011521#endif
11522#ifdef _SC_THREAD_ATTR_STACKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011523 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011524#endif
11525#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011526 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011527#endif
11528#ifdef _SC_THREAD_KEYS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011529 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011530#endif
11531#ifdef _SC_THREAD_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011532 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011533#endif
11534#ifdef _SC_THREAD_PRIO_INHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011535 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
Fred Drakec9680921999-12-13 16:37:25 +000011536#endif
11537#ifdef _SC_THREAD_PRIO_PROTECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011538 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
Fred Drakec9680921999-12-13 16:37:25 +000011539#endif
11540#ifdef _SC_THREAD_PROCESS_SHARED
Victor Stinner8c62be82010-05-06 00:08:46 +000011541 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
Fred Drakec9680921999-12-13 16:37:25 +000011542#endif
11543#ifdef _SC_THREAD_SAFE_FUNCTIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011544 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011545#endif
11546#ifdef _SC_THREAD_STACK_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011547 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011548#endif
11549#ifdef _SC_THREAD_THREADS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011550 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011551#endif
11552#ifdef _SC_TIMERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011553 {"SC_TIMERS", _SC_TIMERS},
Fred Drakec9680921999-12-13 16:37:25 +000011554#endif
11555#ifdef _SC_TIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011556 {"SC_TIMER_MAX", _SC_TIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011557#endif
11558#ifdef _SC_TTY_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011559 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011560#endif
11561#ifdef _SC_TZNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011562 {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011563#endif
11564#ifdef _SC_T_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011565 {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011566#endif
11567#ifdef _SC_UCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011568 {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011569#endif
11570#ifdef _SC_UINT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011571 {"SC_UINT_MAX", _SC_UINT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011572#endif
11573#ifdef _SC_UIO_MAXIOV
Victor Stinner8c62be82010-05-06 00:08:46 +000011574 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
Fred Drakec9680921999-12-13 16:37:25 +000011575#endif
11576#ifdef _SC_ULONG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011577 {"SC_ULONG_MAX", _SC_ULONG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011578#endif
11579#ifdef _SC_USHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011580 {"SC_USHRT_MAX", _SC_USHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011581#endif
11582#ifdef _SC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011583 {"SC_VERSION", _SC_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011584#endif
11585#ifdef _SC_WORD_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011586 {"SC_WORD_BIT", _SC_WORD_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011587#endif
11588#ifdef _SC_XBS5_ILP32_OFF32
Victor Stinner8c62be82010-05-06 00:08:46 +000011589 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
Fred Drakec9680921999-12-13 16:37:25 +000011590#endif
11591#ifdef _SC_XBS5_ILP32_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011592 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011593#endif
11594#ifdef _SC_XBS5_LP64_OFF64
Victor Stinner8c62be82010-05-06 00:08:46 +000011595 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
Fred Drakec9680921999-12-13 16:37:25 +000011596#endif
11597#ifdef _SC_XBS5_LPBIG_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011598 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011599#endif
11600#ifdef _SC_XOPEN_CRYPT
Victor Stinner8c62be82010-05-06 00:08:46 +000011601 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
Fred Drakec9680921999-12-13 16:37:25 +000011602#endif
11603#ifdef _SC_XOPEN_ENH_I18N
Victor Stinner8c62be82010-05-06 00:08:46 +000011604 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
Fred Drakec9680921999-12-13 16:37:25 +000011605#endif
11606#ifdef _SC_XOPEN_LEGACY
Victor Stinner8c62be82010-05-06 00:08:46 +000011607 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
Fred Drakec9680921999-12-13 16:37:25 +000011608#endif
11609#ifdef _SC_XOPEN_REALTIME
Victor Stinner8c62be82010-05-06 00:08:46 +000011610 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
Fred Drakec9680921999-12-13 16:37:25 +000011611#endif
11612#ifdef _SC_XOPEN_REALTIME_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011613 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011614#endif
11615#ifdef _SC_XOPEN_SHM
Victor Stinner8c62be82010-05-06 00:08:46 +000011616 {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
Fred Drakec9680921999-12-13 16:37:25 +000011617#endif
11618#ifdef _SC_XOPEN_UNIX
Victor Stinner8c62be82010-05-06 00:08:46 +000011619 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
Fred Drakec9680921999-12-13 16:37:25 +000011620#endif
11621#ifdef _SC_XOPEN_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011622 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011623#endif
11624#ifdef _SC_XOPEN_XCU_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011625 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011626#endif
11627#ifdef _SC_XOPEN_XPG2
Victor Stinner8c62be82010-05-06 00:08:46 +000011628 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
Fred Drakec9680921999-12-13 16:37:25 +000011629#endif
11630#ifdef _SC_XOPEN_XPG3
Victor Stinner8c62be82010-05-06 00:08:46 +000011631 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
Fred Drakec9680921999-12-13 16:37:25 +000011632#endif
11633#ifdef _SC_XOPEN_XPG4
Victor Stinner8c62be82010-05-06 00:08:46 +000011634 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
Fred Drakec9680921999-12-13 16:37:25 +000011635#endif
11636};
11637
11638static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011639conv_sysconf_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011640{
11641 return conv_confname(arg, valuep, posix_constants_sysconf,
11642 sizeof(posix_constants_sysconf)
11643 / sizeof(struct constdef));
11644}
11645
Larry Hastings2f936352014-08-05 14:04:04 +100011646
11647/*[clinic input]
11648os.sysconf -> long
11649 name: sysconf_confname
11650 /
11651
11652Return an integer-valued system configuration variable.
11653[clinic start generated code]*/
11654
Larry Hastings2f936352014-08-05 14:04:04 +100011655static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011656os_sysconf_impl(PyObject *module, int name)
11657/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011658{
11659 long value;
11660
11661 errno = 0;
11662 value = sysconf(name);
11663 if (value == -1 && errno != 0)
11664 posix_error();
11665 return value;
11666}
11667#endif /* HAVE_SYSCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011668
11669
Fred Drakebec628d1999-12-15 18:31:10 +000011670/* This code is used to ensure that the tables of configuration value names
Serhiy Storchaka56a6d852014-12-01 18:28:43 +020011671 * are in sorted order as required by conv_confname(), and also to build
Fred Drakebec628d1999-12-15 18:31:10 +000011672 * the exported dictionaries that are used to publish information about the
11673 * names available on the host platform.
11674 *
11675 * Sorting the table at runtime ensures that the table is properly ordered
11676 * when used, even for platforms we're not able to test on. It also makes
11677 * it easier to add additional entries to the tables.
Fred Draked86ed291999-12-15 15:34:33 +000011678 */
Fred Drakebec628d1999-12-15 18:31:10 +000011679
11680static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011681cmp_constdefs(const void *v1, const void *v2)
Fred Drakebec628d1999-12-15 18:31:10 +000011682{
11683 const struct constdef *c1 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011684 (const struct constdef *) v1;
Fred Drakebec628d1999-12-15 18:31:10 +000011685 const struct constdef *c2 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011686 (const struct constdef *) v2;
Fred Drakebec628d1999-12-15 18:31:10 +000011687
11688 return strcmp(c1->name, c2->name);
11689}
11690
11691static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011692setup_confname_table(struct constdef *table, size_t tablesize,
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011693 const char *tablename, PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011694{
Fred Drakebec628d1999-12-15 18:31:10 +000011695 PyObject *d = NULL;
Barry Warsaw3155db32000-04-13 15:20:40 +000011696 size_t i;
Fred Drakebec628d1999-12-15 18:31:10 +000011697
11698 qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
11699 d = PyDict_New();
Barry Warsaw3155db32000-04-13 15:20:40 +000011700 if (d == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +000011701 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011702
Barry Warsaw3155db32000-04-13 15:20:40 +000011703 for (i=0; i < tablesize; ++i) {
Victor Stinner8c62be82010-05-06 00:08:46 +000011704 PyObject *o = PyLong_FromLong(table[i].value);
11705 if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
11706 Py_XDECREF(o);
11707 Py_DECREF(d);
11708 return -1;
11709 }
11710 Py_DECREF(o);
Fred Draked86ed291999-12-15 15:34:33 +000011711 }
Fred Drake4d1e64b2002-04-15 19:40:07 +000011712 return PyModule_AddObject(module, tablename, d);
Fred Draked86ed291999-12-15 15:34:33 +000011713}
11714
Fred Drakebec628d1999-12-15 18:31:10 +000011715/* Return -1 on failure, 0 on success. */
11716static int
Fred Drake4d1e64b2002-04-15 19:40:07 +000011717setup_confname_tables(PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011718{
11719#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
Fred Drakebec628d1999-12-15 18:31:10 +000011720 if (setup_confname_table(posix_constants_pathconf,
Fred Draked86ed291999-12-15 15:34:33 +000011721 sizeof(posix_constants_pathconf)
11722 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011723 "pathconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011724 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011725#endif
11726#ifdef HAVE_CONFSTR
Fred Drakebec628d1999-12-15 18:31:10 +000011727 if (setup_confname_table(posix_constants_confstr,
Fred Draked86ed291999-12-15 15:34:33 +000011728 sizeof(posix_constants_confstr)
11729 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011730 "confstr_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011731 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011732#endif
11733#ifdef HAVE_SYSCONF
Fred Drakebec628d1999-12-15 18:31:10 +000011734 if (setup_confname_table(posix_constants_sysconf,
Fred Draked86ed291999-12-15 15:34:33 +000011735 sizeof(posix_constants_sysconf)
11736 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011737 "sysconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011738 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011739#endif
Fred Drakebec628d1999-12-15 18:31:10 +000011740 return 0;
Fred Draked86ed291999-12-15 15:34:33 +000011741}
Fred Draked86ed291999-12-15 15:34:33 +000011742
11743
Larry Hastings2f936352014-08-05 14:04:04 +100011744/*[clinic input]
11745os.abort
11746
11747Abort the interpreter immediately.
11748
11749This function 'dumps core' or otherwise fails in the hardest way possible
11750on the hosting operating system. This function never returns.
11751[clinic start generated code]*/
11752
Larry Hastings2f936352014-08-05 14:04:04 +100011753static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011754os_abort_impl(PyObject *module)
11755/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011756{
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011757 abort();
11758 /*NOTREACHED*/
Victor Stinner9a2329f2016-12-05 17:56:36 +010011759#ifndef __clang__
11760 /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
11761 GCC emits a warning without "return NULL;" (compiler bug?), but Clang
11762 is smarter and emits a warning on the return. */
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011763 Py_FatalError("abort() called from Python code didn't abort!");
11764 return NULL;
Victor Stinner9a2329f2016-12-05 17:56:36 +010011765#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011766}
Fred Drakebec628d1999-12-15 18:31:10 +000011767
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011768#ifdef MS_WINDOWS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011769/* Grab ShellExecute dynamically from shell32 */
11770static int has_ShellExecute = -1;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011771static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
11772 LPCWSTR, INT);
11773static int
11774check_ShellExecute()
11775{
11776 HINSTANCE hShell32;
11777
11778 /* only recheck */
11779 if (-1 == has_ShellExecute) {
11780 Py_BEGIN_ALLOW_THREADS
Victor Stinnera9912152017-10-13 13:46:57 -070011781 /* Security note: this call is not vulnerable to "DLL hijacking".
11782 SHELL32 is part of "KnownDLLs" and so Windows always load
11783 the system SHELL32.DLL, even if there is another SHELL32.DLL
11784 in the DLL search path. */
Steve Dower7d0e0c92015-01-24 08:18:24 -080011785 hShell32 = LoadLibraryW(L"SHELL32");
Steve Dower7d0e0c92015-01-24 08:18:24 -080011786 if (hShell32) {
Steve Dower7d0e0c92015-01-24 08:18:24 -080011787 *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
11788 "ShellExecuteW");
Steve Dowercc16be82016-09-08 10:35:16 -070011789 has_ShellExecute = Py_ShellExecuteW != NULL;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011790 } else {
11791 has_ShellExecute = 0;
11792 }
Tony Roberts4860f012019-02-02 18:16:42 +010011793 Py_END_ALLOW_THREADS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011794 }
11795 return has_ShellExecute;
11796}
11797
11798
Steve Dowercc16be82016-09-08 10:35:16 -070011799/*[clinic input]
11800os.startfile
11801 filepath: path_t
11802 operation: Py_UNICODE = NULL
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +000011803
Steve Dowercc16be82016-09-08 10:35:16 -070011804Start a file with its associated application.
11805
11806When "operation" is not specified or "open", this acts like
11807double-clicking the file in Explorer, or giving the file name as an
11808argument to the DOS "start" command: the file is opened with whatever
11809application (if any) its extension is associated.
11810When another "operation" is given, it specifies what should be done with
11811the file. A typical operation is "print".
11812
11813startfile returns as soon as the associated application is launched.
11814There is no option to wait for the application to close, and no way
11815to retrieve the application's exit status.
11816
11817The filepath is relative to the current directory. If you want to use
11818an absolute path, make sure the first character is not a slash ("/");
11819the underlying Win32 ShellExecute function doesn't work if it is.
11820[clinic start generated code]*/
11821
11822static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +020011823os_startfile_impl(PyObject *module, path_t *filepath,
11824 const Py_UNICODE *operation)
Serhiy Storchaka279f4462019-09-14 12:24:05 +030011825/*[clinic end generated code: output=66dc311c94d50797 input=c940888a5390f039]*/
Steve Dowercc16be82016-09-08 10:35:16 -070011826{
11827 HINSTANCE rc;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011828
11829 if(!check_ShellExecute()) {
11830 /* If the OS doesn't have ShellExecute, return a
11831 NotImplementedError. */
11832 return PyErr_Format(PyExc_NotImplementedError,
11833 "startfile not available on this platform");
11834 }
11835
Saiyang Gou7514f4f2020-02-12 23:47:42 -080011836 if (PySys_Audit("os.startfile", "Ou", filepath->object, operation) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -080011837 return NULL;
11838 }
11839
Victor Stinner8c62be82010-05-06 00:08:46 +000011840 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -070011841 rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
Steve Dower7d0e0c92015-01-24 08:18:24 -080011842 NULL, NULL, SW_SHOWNORMAL);
Victor Stinner8c62be82010-05-06 00:08:46 +000011843 Py_END_ALLOW_THREADS
11844
Victor Stinner8c62be82010-05-06 00:08:46 +000011845 if (rc <= (HINSTANCE)32) {
Steve Dowercc16be82016-09-08 10:35:16 -070011846 win32_error_object("startfile", filepath->object);
Victor Stinnereb5657a2011-09-30 01:44:27 +020011847 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000011848 }
Steve Dowercc16be82016-09-08 10:35:16 -070011849 Py_RETURN_NONE;
Tim Petersf58a7aa2000-09-22 10:05:54 +000011850}
Larry Hastings2f936352014-08-05 14:04:04 +100011851#endif /* MS_WINDOWS */
11852
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011853
Martin v. Löwis438b5342002-12-27 10:16:42 +000011854#ifdef HAVE_GETLOADAVG
Larry Hastings2f936352014-08-05 14:04:04 +100011855/*[clinic input]
11856os.getloadavg
11857
11858Return average recent system load information.
11859
11860Return the number of processes in the system run queue averaged over
11861the last 1, 5, and 15 minutes as a tuple of three floats.
11862Raises OSError if the load average was unobtainable.
11863[clinic start generated code]*/
11864
Larry Hastings2f936352014-08-05 14:04:04 +100011865static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011866os_getloadavg_impl(PyObject *module)
11867/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
Martin v. Löwis438b5342002-12-27 10:16:42 +000011868{
11869 double loadavg[3];
Martin v. Löwis438b5342002-12-27 10:16:42 +000011870 if (getloadavg(loadavg, 3)!=3) {
Stefan Krah0e803b32010-11-26 16:16:47 +000011871 PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
11872 return NULL;
Martin v. Löwis438b5342002-12-27 10:16:42 +000011873 } else
Stefan Krah0e803b32010-11-26 16:16:47 +000011874 return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
Martin v. Löwis438b5342002-12-27 10:16:42 +000011875}
Larry Hastings2f936352014-08-05 14:04:04 +100011876#endif /* HAVE_GETLOADAVG */
Martin v. Löwis438b5342002-12-27 10:16:42 +000011877
Larry Hastings2f936352014-08-05 14:04:04 +100011878
11879/*[clinic input]
11880os.device_encoding
11881 fd: int
11882
11883Return a string describing the encoding of a terminal's file descriptor.
11884
11885The file descriptor must be attached to a terminal.
11886If the device is not a terminal, return None.
11887[clinic start generated code]*/
11888
Larry Hastings2f936352014-08-05 14:04:04 +100011889static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011890os_device_encoding_impl(PyObject *module, int fd)
11891/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011892{
Brett Cannonefb00c02012-02-29 18:31:31 -050011893 return _Py_device_encoding(fd);
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +000011894}
11895
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011896
Larry Hastings2f936352014-08-05 14:04:04 +100011897#ifdef HAVE_SETRESUID
11898/*[clinic input]
11899os.setresuid
11900
11901 ruid: uid_t
11902 euid: uid_t
11903 suid: uid_t
11904 /
11905
11906Set the current process's real, effective, and saved user ids.
11907[clinic start generated code]*/
11908
Larry Hastings2f936352014-08-05 14:04:04 +100011909static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011910os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
11911/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011912{
Victor Stinner8c62be82010-05-06 00:08:46 +000011913 if (setresuid(ruid, euid, suid) < 0)
11914 return posix_error();
11915 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011916}
Larry Hastings2f936352014-08-05 14:04:04 +100011917#endif /* HAVE_SETRESUID */
11918
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011919
11920#ifdef HAVE_SETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011921/*[clinic input]
11922os.setresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011923
Larry Hastings2f936352014-08-05 14:04:04 +100011924 rgid: gid_t
11925 egid: gid_t
11926 sgid: gid_t
11927 /
11928
11929Set the current process's real, effective, and saved group ids.
11930[clinic start generated code]*/
11931
Larry Hastings2f936352014-08-05 14:04:04 +100011932static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011933os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
11934/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011935{
Victor Stinner8c62be82010-05-06 00:08:46 +000011936 if (setresgid(rgid, egid, sgid) < 0)
11937 return posix_error();
11938 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011939}
Larry Hastings2f936352014-08-05 14:04:04 +100011940#endif /* HAVE_SETRESGID */
11941
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011942
11943#ifdef HAVE_GETRESUID
Larry Hastings2f936352014-08-05 14:04:04 +100011944/*[clinic input]
11945os.getresuid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011946
Larry Hastings2f936352014-08-05 14:04:04 +100011947Return a tuple of the current process's real, effective, and saved user ids.
11948[clinic start generated code]*/
11949
Larry Hastings2f936352014-08-05 14:04:04 +100011950static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011951os_getresuid_impl(PyObject *module)
11952/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011953{
Victor Stinner8c62be82010-05-06 00:08:46 +000011954 uid_t ruid, euid, suid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011955 if (getresuid(&ruid, &euid, &suid) < 0)
11956 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011957 return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
11958 _PyLong_FromUid(euid),
11959 _PyLong_FromUid(suid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011960}
Larry Hastings2f936352014-08-05 14:04:04 +100011961#endif /* HAVE_GETRESUID */
11962
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011963
11964#ifdef HAVE_GETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011965/*[clinic input]
11966os.getresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011967
Larry Hastings2f936352014-08-05 14:04:04 +100011968Return a tuple of the current process's real, effective, and saved group ids.
11969[clinic start generated code]*/
11970
Larry Hastings2f936352014-08-05 14:04:04 +100011971static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011972os_getresgid_impl(PyObject *module)
11973/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011974{
11975 gid_t rgid, egid, sgid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011976 if (getresgid(&rgid, &egid, &sgid) < 0)
11977 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011978 return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
11979 _PyLong_FromGid(egid),
11980 _PyLong_FromGid(sgid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011981}
Larry Hastings2f936352014-08-05 14:04:04 +100011982#endif /* HAVE_GETRESGID */
11983
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011984
Benjamin Peterson9428d532011-09-14 11:45:52 -040011985#ifdef USE_XATTRS
Larry Hastings2f936352014-08-05 14:04:04 +100011986/*[clinic input]
11987os.getxattr
Benjamin Peterson799bd802011-08-31 22:15:17 -040011988
Larry Hastings2f936352014-08-05 14:04:04 +100011989 path: path_t(allow_fd=True)
11990 attribute: path_t
11991 *
11992 follow_symlinks: bool = True
11993
11994Return the value of extended attribute attribute on path.
11995
BNMetricsb9427072018-11-02 15:20:19 +000011996path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011997If follow_symlinks is False, and the last element of the path is a symbolic
11998 link, getxattr will examine the symbolic link itself instead of the file
11999 the link points to.
12000
12001[clinic start generated code]*/
12002
Larry Hastings2f936352014-08-05 14:04:04 +100012003static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012004os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012005 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012006/*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012007{
12008 Py_ssize_t i;
12009 PyObject *buffer = NULL;
12010
12011 if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
12012 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012013
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012014 if (PySys_Audit("os.getxattr", "OO", path->object, attribute->object) < 0) {
12015 return NULL;
12016 }
12017
Larry Hastings9cf065c2012-06-22 16:30:09 -070012018 for (i = 0; ; i++) {
12019 void *ptr;
12020 ssize_t result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012021 static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
Larry Hastings9cf065c2012-06-22 16:30:09 -070012022 Py_ssize_t buffer_size = buffer_sizes[i];
12023 if (!buffer_size) {
Larry Hastings2f936352014-08-05 14:04:04 +100012024 path_error(path);
12025 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012026 }
12027 buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
12028 if (!buffer)
Larry Hastings2f936352014-08-05 14:04:04 +100012029 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012030 ptr = PyBytes_AS_STRING(buffer);
Benjamin Peterson799bd802011-08-31 22:15:17 -040012031
Larry Hastings9cf065c2012-06-22 16:30:09 -070012032 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012033 if (path->fd >= 0)
12034 result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012035 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100012036 result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012037 else
Larry Hastings2f936352014-08-05 14:04:04 +100012038 result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012039 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012040
Larry Hastings9cf065c2012-06-22 16:30:09 -070012041 if (result < 0) {
12042 Py_DECREF(buffer);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012043 if (errno == ERANGE)
12044 continue;
Larry Hastings2f936352014-08-05 14:04:04 +100012045 path_error(path);
12046 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012047 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012048
Larry Hastings9cf065c2012-06-22 16:30:09 -070012049 if (result != buffer_size) {
12050 /* Can only shrink. */
12051 _PyBytes_Resize(&buffer, result);
12052 }
12053 break;
12054 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012055
Larry Hastings9cf065c2012-06-22 16:30:09 -070012056 return buffer;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012057}
12058
Larry Hastings2f936352014-08-05 14:04:04 +100012059
12060/*[clinic input]
12061os.setxattr
12062
12063 path: path_t(allow_fd=True)
12064 attribute: path_t
12065 value: Py_buffer
12066 flags: int = 0
12067 *
12068 follow_symlinks: bool = True
12069
12070Set extended attribute attribute on path to value.
12071
BNMetricsb9427072018-11-02 15:20:19 +000012072path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012073If follow_symlinks is False, and the last element of the path is a symbolic
12074 link, setxattr will modify the symbolic link itself instead of the file
12075 the link points to.
12076
12077[clinic start generated code]*/
12078
Benjamin Peterson799bd802011-08-31 22:15:17 -040012079static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012080os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012081 Py_buffer *value, int flags, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012082/*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
Benjamin Peterson799bd802011-08-31 22:15:17 -040012083{
Larry Hastings2f936352014-08-05 14:04:04 +100012084 ssize_t result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012085
Larry Hastings2f936352014-08-05 14:04:04 +100012086 if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
Benjamin Peterson799bd802011-08-31 22:15:17 -040012087 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012088
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012089 if (PySys_Audit("os.setxattr", "OOy#i", path->object, attribute->object,
12090 value->buf, value->len, flags) < 0) {
12091 return NULL;
12092 }
12093
Benjamin Peterson799bd802011-08-31 22:15:17 -040012094 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012095 if (path->fd > -1)
12096 result = fsetxattr(path->fd, attribute->narrow,
12097 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012098 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100012099 result = setxattr(path->narrow, attribute->narrow,
12100 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012101 else
Larry Hastings2f936352014-08-05 14:04:04 +100012102 result = lsetxattr(path->narrow, attribute->narrow,
12103 value->buf, value->len, flags);
Benjamin Peterson799bd802011-08-31 22:15:17 -040012104 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012105
Larry Hastings9cf065c2012-06-22 16:30:09 -070012106 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100012107 path_error(path);
12108 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012109 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012110
Larry Hastings2f936352014-08-05 14:04:04 +100012111 Py_RETURN_NONE;
12112}
12113
12114
12115/*[clinic input]
12116os.removexattr
12117
12118 path: path_t(allow_fd=True)
12119 attribute: path_t
12120 *
12121 follow_symlinks: bool = True
12122
12123Remove extended attribute attribute on path.
12124
BNMetricsb9427072018-11-02 15:20:19 +000012125path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012126If follow_symlinks is False, and the last element of the path is a symbolic
12127 link, removexattr will modify the symbolic link itself instead of the file
12128 the link points to.
12129
12130[clinic start generated code]*/
12131
Larry Hastings2f936352014-08-05 14:04:04 +100012132static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012133os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012134 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012135/*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012136{
12137 ssize_t result;
12138
12139 if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
12140 return NULL;
12141
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012142 if (PySys_Audit("os.removexattr", "OO", path->object, attribute->object) < 0) {
12143 return NULL;
12144 }
12145
Larry Hastings2f936352014-08-05 14:04:04 +100012146 Py_BEGIN_ALLOW_THREADS;
12147 if (path->fd > -1)
12148 result = fremovexattr(path->fd, attribute->narrow);
12149 else if (follow_symlinks)
12150 result = removexattr(path->narrow, attribute->narrow);
12151 else
12152 result = lremovexattr(path->narrow, attribute->narrow);
12153 Py_END_ALLOW_THREADS;
12154
12155 if (result) {
12156 return path_error(path);
12157 }
12158
12159 Py_RETURN_NONE;
12160}
12161
12162
12163/*[clinic input]
12164os.listxattr
12165
12166 path: path_t(allow_fd=True, nullable=True) = None
12167 *
12168 follow_symlinks: bool = True
12169
12170Return a list of extended attributes on path.
12171
BNMetricsb9427072018-11-02 15:20:19 +000012172path may be either None, a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012173if path is None, listxattr will examine the current directory.
12174If follow_symlinks is False, and the last element of the path is a symbolic
12175 link, listxattr will examine the symbolic link itself instead of the file
12176 the link points to.
12177[clinic start generated code]*/
12178
Larry Hastings2f936352014-08-05 14:04:04 +100012179static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012180os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012181/*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012182{
Larry Hastings9cf065c2012-06-22 16:30:09 -070012183 Py_ssize_t i;
12184 PyObject *result = NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100012185 const char *name;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012186 char *buffer = NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012187
Larry Hastings2f936352014-08-05 14:04:04 +100012188 if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
Larry Hastings9cf065c2012-06-22 16:30:09 -070012189 goto exit;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012190
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012191 if (PySys_Audit("os.listxattr", "(O)",
12192 path->object ? path->object : Py_None) < 0) {
12193 return NULL;
12194 }
12195
Larry Hastings2f936352014-08-05 14:04:04 +100012196 name = path->narrow ? path->narrow : ".";
12197
Larry Hastings9cf065c2012-06-22 16:30:09 -070012198 for (i = 0; ; i++) {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012199 const char *start, *trace, *end;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012200 ssize_t length;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012201 static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
Larry Hastings9cf065c2012-06-22 16:30:09 -070012202 Py_ssize_t buffer_size = buffer_sizes[i];
12203 if (!buffer_size) {
Christian Heimes3b9493b2012-09-23 16:11:15 +020012204 /* ERANGE */
Larry Hastings2f936352014-08-05 14:04:04 +100012205 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012206 break;
12207 }
12208 buffer = PyMem_MALLOC(buffer_size);
12209 if (!buffer) {
12210 PyErr_NoMemory();
12211 break;
12212 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012213
Larry Hastings9cf065c2012-06-22 16:30:09 -070012214 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012215 if (path->fd > -1)
12216 length = flistxattr(path->fd, buffer, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012217 else if (follow_symlinks)
12218 length = listxattr(name, buffer, buffer_size);
12219 else
12220 length = llistxattr(name, buffer, buffer_size);
12221 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012222
Larry Hastings9cf065c2012-06-22 16:30:09 -070012223 if (length < 0) {
Antoine Pitrou7f987392013-05-13 19:46:29 +020012224 if (errno == ERANGE) {
12225 PyMem_FREE(buffer);
Benjamin Petersondedac522013-05-13 19:55:40 -050012226 buffer = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012227 continue;
Antoine Pitrou7f987392013-05-13 19:46:29 +020012228 }
Larry Hastings2f936352014-08-05 14:04:04 +100012229 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012230 break;
12231 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012232
Larry Hastings9cf065c2012-06-22 16:30:09 -070012233 result = PyList_New(0);
12234 if (!result) {
12235 goto exit;
12236 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012237
Larry Hastings9cf065c2012-06-22 16:30:09 -070012238 end = buffer + length;
12239 for (trace = start = buffer; trace != end; trace++) {
12240 if (!*trace) {
12241 int error;
12242 PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
12243 trace - start);
12244 if (!attribute) {
12245 Py_DECREF(result);
12246 result = NULL;
12247 goto exit;
12248 }
12249 error = PyList_Append(result, attribute);
12250 Py_DECREF(attribute);
12251 if (error) {
12252 Py_DECREF(result);
12253 result = NULL;
12254 goto exit;
12255 }
12256 start = trace + 1;
12257 }
12258 }
12259 break;
12260 }
12261exit:
Larry Hastings9cf065c2012-06-22 16:30:09 -070012262 if (buffer)
12263 PyMem_FREE(buffer);
12264 return result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012265}
Benjamin Peterson9428d532011-09-14 11:45:52 -040012266#endif /* USE_XATTRS */
Benjamin Peterson799bd802011-08-31 22:15:17 -040012267
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012268
Larry Hastings2f936352014-08-05 14:04:04 +100012269/*[clinic input]
12270os.urandom
12271
12272 size: Py_ssize_t
12273 /
12274
12275Return a bytes object containing random bytes suitable for cryptographic use.
12276[clinic start generated code]*/
12277
Larry Hastings2f936352014-08-05 14:04:04 +100012278static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012279os_urandom_impl(PyObject *module, Py_ssize_t size)
12280/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012281{
12282 PyObject *bytes;
12283 int result;
12284
Georg Brandl2fb477c2012-02-21 00:33:36 +010012285 if (size < 0)
12286 return PyErr_Format(PyExc_ValueError,
12287 "negative argument not allowed");
Larry Hastings2f936352014-08-05 14:04:04 +100012288 bytes = PyBytes_FromStringAndSize(NULL, size);
12289 if (bytes == NULL)
Georg Brandl2fb477c2012-02-21 00:33:36 +010012290 return NULL;
12291
Victor Stinnere66987e2016-09-06 16:33:52 -070012292 result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
Larry Hastings2f936352014-08-05 14:04:04 +100012293 if (result == -1) {
12294 Py_DECREF(bytes);
Georg Brandl2fb477c2012-02-21 00:33:36 +010012295 return NULL;
12296 }
Larry Hastings2f936352014-08-05 14:04:04 +100012297 return bytes;
Georg Brandl2fb477c2012-02-21 00:33:36 +010012298}
12299
Zackery Spytz43fdbd22019-05-29 13:57:07 -060012300#ifdef HAVE_MEMFD_CREATE
12301/*[clinic input]
12302os.memfd_create
12303
12304 name: FSConverter
12305 flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
12306
12307[clinic start generated code]*/
12308
12309static PyObject *
12310os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
12311/*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
12312{
12313 int fd;
12314 const char *bytes = PyBytes_AS_STRING(name);
12315 Py_BEGIN_ALLOW_THREADS
12316 fd = memfd_create(bytes, flags);
12317 Py_END_ALLOW_THREADS
12318 if (fd == -1) {
12319 return PyErr_SetFromErrno(PyExc_OSError);
12320 }
12321 return PyLong_FromLong(fd);
12322}
12323#endif
12324
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012325/* Terminal size querying */
12326
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012327PyDoc_STRVAR(TerminalSize_docstring,
12328 "A tuple of (columns, lines) for holding terminal window size");
12329
12330static PyStructSequence_Field TerminalSize_fields[] = {
12331 {"columns", "width of the terminal window in characters"},
12332 {"lines", "height of the terminal window in characters"},
12333 {NULL, NULL}
12334};
12335
12336static PyStructSequence_Desc TerminalSize_desc = {
12337 "os.terminal_size",
12338 TerminalSize_docstring,
12339 TerminalSize_fields,
12340 2,
12341};
12342
12343#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
Larry Hastings2f936352014-08-05 14:04:04 +100012344/* AC 3.5: fd should accept None */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012345PyDoc_STRVAR(termsize__doc__,
12346 "Return the size of the terminal window as (columns, lines).\n" \
12347 "\n" \
12348 "The optional argument fd (default standard output) specifies\n" \
12349 "which file descriptor should be queried.\n" \
12350 "\n" \
12351 "If the file descriptor is not connected to a terminal, an OSError\n" \
12352 "is thrown.\n" \
12353 "\n" \
12354 "This function will only be defined if an implementation is\n" \
12355 "available for this system.\n" \
12356 "\n" \
oldkaa0735f2018-02-02 16:52:55 +080012357 "shutil.get_terminal_size is the high-level function which should\n" \
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012358 "normally be used, os.get_terminal_size is the low-level implementation.");
12359
12360static PyObject*
12361get_terminal_size(PyObject *self, PyObject *args)
12362{
12363 int columns, lines;
12364 PyObject *termsize;
12365
12366 int fd = fileno(stdout);
12367 /* Under some conditions stdout may not be connected and
12368 * fileno(stdout) may point to an invalid file descriptor. For example
12369 * GUI apps don't have valid standard streams by default.
12370 *
12371 * If this happens, and the optional fd argument is not present,
12372 * the ioctl below will fail returning EBADF. This is what we want.
12373 */
12374
12375 if (!PyArg_ParseTuple(args, "|i", &fd))
12376 return NULL;
12377
12378#ifdef TERMSIZE_USE_IOCTL
12379 {
12380 struct winsize w;
12381 if (ioctl(fd, TIOCGWINSZ, &w))
12382 return PyErr_SetFromErrno(PyExc_OSError);
12383 columns = w.ws_col;
12384 lines = w.ws_row;
12385 }
12386#endif /* TERMSIZE_USE_IOCTL */
12387
12388#ifdef TERMSIZE_USE_CONIO
12389 {
12390 DWORD nhandle;
12391 HANDLE handle;
12392 CONSOLE_SCREEN_BUFFER_INFO csbi;
12393 switch (fd) {
12394 case 0: nhandle = STD_INPUT_HANDLE;
12395 break;
12396 case 1: nhandle = STD_OUTPUT_HANDLE;
12397 break;
12398 case 2: nhandle = STD_ERROR_HANDLE;
12399 break;
12400 default:
12401 return PyErr_Format(PyExc_ValueError, "bad file descriptor");
12402 }
12403 handle = GetStdHandle(nhandle);
12404 if (handle == NULL)
12405 return PyErr_Format(PyExc_OSError, "handle cannot be retrieved");
12406 if (handle == INVALID_HANDLE_VALUE)
12407 return PyErr_SetFromWindowsErr(0);
12408
12409 if (!GetConsoleScreenBufferInfo(handle, &csbi))
12410 return PyErr_SetFromWindowsErr(0);
12411
12412 columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
12413 lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
12414 }
12415#endif /* TERMSIZE_USE_CONIO */
12416
Hai Shif707d942020-03-16 21:15:01 +080012417 PyObject *TerminalSizeType = get_posix_state(self)->TerminalSizeType;
Eddie Elizondob3966632019-11-05 07:16:14 -080012418 termsize = PyStructSequence_New((PyTypeObject *)TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012419 if (termsize == NULL)
12420 return NULL;
12421 PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
12422 PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
12423 if (PyErr_Occurred()) {
12424 Py_DECREF(termsize);
12425 return NULL;
12426 }
12427 return termsize;
12428}
12429#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
12430
Larry Hastings2f936352014-08-05 14:04:04 +100012431
12432/*[clinic input]
12433os.cpu_count
12434
Charles-François Natali80d62e62015-08-13 20:37:08 +010012435Return the number of CPUs in the system; return None if indeterminable.
12436
12437This number is not equivalent to the number of CPUs the current process can
12438use. The number of usable CPUs can be obtained with
12439``len(os.sched_getaffinity(0))``
Larry Hastings2f936352014-08-05 14:04:04 +100012440[clinic start generated code]*/
12441
Larry Hastings2f936352014-08-05 14:04:04 +100012442static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012443os_cpu_count_impl(PyObject *module)
Serhiy Storchaka2954f832016-07-07 18:20:03 +030012444/*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012445{
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012446 int ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012447#ifdef MS_WINDOWS
Steve Doweraa929272019-09-11 16:15:39 +010012448 ncpu = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012449#elif defined(__hpux)
12450 ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
12451#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
12452 ncpu = sysconf(_SC_NPROCESSORS_ONLN);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012453#elif defined(__DragonFly__) || \
12454 defined(__OpenBSD__) || \
12455 defined(__FreeBSD__) || \
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012456 defined(__NetBSD__) || \
12457 defined(__APPLE__)
Charles-Francois Natali7c4f8da2013-05-20 17:40:32 +020012458 int mib[2];
12459 size_t len = sizeof(ncpu);
12460 mib[0] = CTL_HW;
12461 mib[1] = HW_NCPU;
12462 if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
12463 ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012464#endif
12465 if (ncpu >= 1)
12466 return PyLong_FromLong(ncpu);
12467 else
12468 Py_RETURN_NONE;
12469}
12470
Victor Stinnerdaf45552013-08-28 00:53:59 +020012471
Larry Hastings2f936352014-08-05 14:04:04 +100012472/*[clinic input]
12473os.get_inheritable -> bool
12474
12475 fd: int
12476 /
12477
12478Get the close-on-exe flag of the specified file descriptor.
12479[clinic start generated code]*/
12480
Larry Hastings2f936352014-08-05 14:04:04 +100012481static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012482os_get_inheritable_impl(PyObject *module, int fd)
12483/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012484{
Steve Dower8fc89802015-04-12 00:26:27 -040012485 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -040012486 _Py_BEGIN_SUPPRESS_IPH
12487 return_value = _Py_get_inheritable(fd);
12488 _Py_END_SUPPRESS_IPH
12489 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +100012490}
12491
12492
12493/*[clinic input]
12494os.set_inheritable
12495 fd: int
12496 inheritable: int
12497 /
12498
12499Set the inheritable flag of the specified file descriptor.
12500[clinic start generated code]*/
12501
Larry Hastings2f936352014-08-05 14:04:04 +100012502static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012503os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
12504/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
Victor Stinnerdaf45552013-08-28 00:53:59 +020012505{
Steve Dower8fc89802015-04-12 00:26:27 -040012506 int result;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012507
Steve Dower8fc89802015-04-12 00:26:27 -040012508 _Py_BEGIN_SUPPRESS_IPH
12509 result = _Py_set_inheritable(fd, inheritable, NULL);
12510 _Py_END_SUPPRESS_IPH
12511 if (result < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +020012512 return NULL;
12513 Py_RETURN_NONE;
12514}
12515
12516
12517#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100012518/*[clinic input]
12519os.get_handle_inheritable -> bool
Benjamin Petersonca470632016-09-06 13:47:26 -070012520 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012521 /
Victor Stinnerdaf45552013-08-28 00:53:59 +020012522
Larry Hastings2f936352014-08-05 14:04:04 +100012523Get the close-on-exe flag of the specified file descriptor.
12524[clinic start generated code]*/
12525
Larry Hastings2f936352014-08-05 14:04:04 +100012526static int
Benjamin Petersonca470632016-09-06 13:47:26 -070012527os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
Victor Stinner581139c2016-09-06 15:54:20 -070012528/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012529{
12530 DWORD flags;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012531
12532 if (!GetHandleInformation((HANDLE)handle, &flags)) {
12533 PyErr_SetFromWindowsErr(0);
Larry Hastings2f936352014-08-05 14:04:04 +100012534 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012535 }
12536
Larry Hastings2f936352014-08-05 14:04:04 +100012537 return flags & HANDLE_FLAG_INHERIT;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012538}
12539
Victor Stinnerdaf45552013-08-28 00:53:59 +020012540
Larry Hastings2f936352014-08-05 14:04:04 +100012541/*[clinic input]
12542os.set_handle_inheritable
Benjamin Petersonca470632016-09-06 13:47:26 -070012543 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012544 inheritable: bool
12545 /
12546
12547Set the inheritable flag of the specified handle.
12548[clinic start generated code]*/
12549
Larry Hastings2f936352014-08-05 14:04:04 +100012550static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -070012551os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
Larry Hastings89964c42015-04-14 18:07:59 -040012552 int inheritable)
Victor Stinner581139c2016-09-06 15:54:20 -070012553/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012554{
12555 DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012556 if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
12557 PyErr_SetFromWindowsErr(0);
12558 return NULL;
12559 }
12560 Py_RETURN_NONE;
12561}
Larry Hastings2f936352014-08-05 14:04:04 +100012562#endif /* MS_WINDOWS */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012563
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012564#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012565/*[clinic input]
12566os.get_blocking -> bool
12567 fd: int
12568 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012569
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012570Get the blocking mode of the file descriptor.
12571
12572Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
12573[clinic start generated code]*/
12574
12575static int
12576os_get_blocking_impl(PyObject *module, int fd)
12577/*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012578{
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012579 int blocking;
12580
Steve Dower8fc89802015-04-12 00:26:27 -040012581 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012582 blocking = _Py_get_blocking(fd);
Steve Dower8fc89802015-04-12 00:26:27 -040012583 _Py_END_SUPPRESS_IPH
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012584 return blocking;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012585}
12586
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012587/*[clinic input]
12588os.set_blocking
12589 fd: int
12590 blocking: bool(accept={int})
12591 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012592
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012593Set the blocking mode of the specified file descriptor.
12594
12595Set the O_NONBLOCK flag if blocking is False,
12596clear the O_NONBLOCK flag otherwise.
12597[clinic start generated code]*/
12598
12599static PyObject *
12600os_set_blocking_impl(PyObject *module, int fd, int blocking)
12601/*[clinic end generated code: output=384eb43aa0762a9d input=bf5c8efdc5860ff3]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012602{
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012603 int result;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012604
Steve Dower8fc89802015-04-12 00:26:27 -040012605 _Py_BEGIN_SUPPRESS_IPH
12606 result = _Py_set_blocking(fd, blocking);
12607 _Py_END_SUPPRESS_IPH
12608 if (result < 0)
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012609 return NULL;
12610 Py_RETURN_NONE;
12611}
12612#endif /* !MS_WINDOWS */
12613
12614
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012615/*[clinic input]
Eddie Elizondob3966632019-11-05 07:16:14 -080012616class os.DirEntry "DirEntry *" "DirEntryType"
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012617[clinic start generated code]*/
Eddie Elizondob3966632019-11-05 07:16:14 -080012618/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3c18c7a448247980]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012619
12620typedef struct {
12621 PyObject_HEAD
12622 PyObject *name;
12623 PyObject *path;
12624 PyObject *stat;
12625 PyObject *lstat;
12626#ifdef MS_WINDOWS
12627 struct _Py_stat_struct win32_lstat;
Victor Stinner0f6d7332017-03-09 17:34:28 +010012628 uint64_t win32_file_index;
Victor Stinner6036e442015-03-08 01:58:04 +010012629 int got_file_index;
12630#else /* POSIX */
Victor Stinner35a97c02015-03-08 02:59:09 +010012631#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012632 unsigned char d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012633#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012634 ino_t d_ino;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012635 int dir_fd;
Victor Stinner6036e442015-03-08 01:58:04 +010012636#endif
12637} DirEntry;
12638
Eddie Elizondob3966632019-11-05 07:16:14 -080012639static PyObject *
12640_disabled_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
12641{
12642 PyErr_Format(PyExc_TypeError,
12643 "cannot create '%.100s' instances", _PyType_Name(type));
12644 return NULL;
12645}
12646
Victor Stinner6036e442015-03-08 01:58:04 +010012647static void
12648DirEntry_dealloc(DirEntry *entry)
12649{
Eddie Elizondob3966632019-11-05 07:16:14 -080012650 PyTypeObject *tp = Py_TYPE(entry);
Victor Stinner6036e442015-03-08 01:58:04 +010012651 Py_XDECREF(entry->name);
12652 Py_XDECREF(entry->path);
12653 Py_XDECREF(entry->stat);
12654 Py_XDECREF(entry->lstat);
Eddie Elizondob3966632019-11-05 07:16:14 -080012655 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
12656 free_func(entry);
12657 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010012658}
12659
12660/* Forward reference */
12661static int
12662DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits);
12663
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012664/*[clinic input]
12665os.DirEntry.is_symlink -> bool
12666
12667Return True if the entry is a symbolic link; cached per entry.
12668[clinic start generated code]*/
12669
Victor Stinner6036e442015-03-08 01:58:04 +010012670static int
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012671os_DirEntry_is_symlink_impl(DirEntry *self)
12672/*[clinic end generated code: output=42244667d7bcfc25 input=1605a1b4b96976c3]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012673{
12674#ifdef MS_WINDOWS
12675 return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
Victor Stinner35a97c02015-03-08 02:59:09 +010012676#elif defined(HAVE_DIRENT_D_TYPE)
12677 /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010012678 if (self->d_type != DT_UNKNOWN)
12679 return self->d_type == DT_LNK;
12680 else
12681 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner35a97c02015-03-08 02:59:09 +010012682#else
12683 /* POSIX without d_type */
12684 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner6036e442015-03-08 01:58:04 +010012685#endif
12686}
12687
12688static PyObject *
Victor Stinner6036e442015-03-08 01:58:04 +010012689DirEntry_fetch_stat(DirEntry *self, int follow_symlinks)
12690{
12691 int result;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012692 STRUCT_STAT st;
12693 PyObject *ub;
Victor Stinner6036e442015-03-08 01:58:04 +010012694
12695#ifdef MS_WINDOWS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012696 if (!PyUnicode_FSDecoder(self->path, &ub))
12697 return NULL;
12698 const wchar_t *path = PyUnicode_AsUnicode(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012699#else /* POSIX */
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012700 if (!PyUnicode_FSConverter(self->path, &ub))
12701 return NULL;
12702 const char *path = PyBytes_AS_STRING(ub);
12703 if (self->dir_fd != DEFAULT_DIR_FD) {
12704#ifdef HAVE_FSTATAT
12705 result = fstatat(self->dir_fd, path, &st,
12706 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
12707#else
12708 PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
12709 return NULL;
12710#endif /* HAVE_FSTATAT */
12711 }
12712 else
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012713#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012714 {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012715 if (follow_symlinks)
12716 result = STAT(path, &st);
12717 else
12718 result = LSTAT(path, &st);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012719 }
12720 Py_DECREF(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012721
12722 if (result != 0)
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012723 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012724
12725 return _pystat_fromstructstat(&st);
12726}
12727
12728static PyObject *
12729DirEntry_get_lstat(DirEntry *self)
12730{
12731 if (!self->lstat) {
12732#ifdef MS_WINDOWS
12733 self->lstat = _pystat_fromstructstat(&self->win32_lstat);
12734#else /* POSIX */
12735 self->lstat = DirEntry_fetch_stat(self, 0);
12736#endif
12737 }
12738 Py_XINCREF(self->lstat);
12739 return self->lstat;
12740}
12741
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012742/*[clinic input]
12743os.DirEntry.stat
12744 *
12745 follow_symlinks: bool = True
12746
12747Return stat_result object for the entry; cached per entry.
12748[clinic start generated code]*/
12749
Victor Stinner6036e442015-03-08 01:58:04 +010012750static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012751os_DirEntry_stat_impl(DirEntry *self, int follow_symlinks)
12752/*[clinic end generated code: output=008593b3a6d01305 input=280d14c1d6f1d00d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012753{
12754 if (!follow_symlinks)
12755 return DirEntry_get_lstat(self);
12756
12757 if (!self->stat) {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012758 int result = os_DirEntry_is_symlink_impl(self);
Victor Stinner6036e442015-03-08 01:58:04 +010012759 if (result == -1)
12760 return NULL;
12761 else if (result)
12762 self->stat = DirEntry_fetch_stat(self, 1);
12763 else
12764 self->stat = DirEntry_get_lstat(self);
12765 }
12766
12767 Py_XINCREF(self->stat);
12768 return self->stat;
12769}
12770
Victor Stinner6036e442015-03-08 01:58:04 +010012771/* Set exception and return -1 on error, 0 for False, 1 for True */
12772static int
12773DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
12774{
12775 PyObject *stat = NULL;
12776 PyObject *st_mode = NULL;
12777 long mode;
12778 int result;
Victor Stinner35a97c02015-03-08 02:59:09 +010012779#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012780 int is_symlink;
12781 int need_stat;
Victor Stinner35a97c02015-03-08 02:59:09 +010012782#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012783#ifdef MS_WINDOWS
12784 unsigned long dir_bits;
12785#endif
12786
12787#ifdef MS_WINDOWS
12788 is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
12789 need_stat = follow_symlinks && is_symlink;
Victor Stinner35a97c02015-03-08 02:59:09 +010012790#elif defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012791 is_symlink = self->d_type == DT_LNK;
12792 need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
12793#endif
12794
Victor Stinner35a97c02015-03-08 02:59:09 +010012795#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012796 if (need_stat) {
Victor Stinner35a97c02015-03-08 02:59:09 +010012797#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012798 stat = os_DirEntry_stat_impl(self, follow_symlinks);
Victor Stinner6036e442015-03-08 01:58:04 +010012799 if (!stat) {
12800 if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
12801 /* If file doesn't exist (anymore), then return False
12802 (i.e., say it's not a file/directory) */
12803 PyErr_Clear();
12804 return 0;
12805 }
12806 goto error;
12807 }
Eddie Elizondob3966632019-11-05 07:16:14 -080012808 st_mode = PyObject_GetAttr(stat, _posixstate_global->st_mode);
Victor Stinner6036e442015-03-08 01:58:04 +010012809 if (!st_mode)
12810 goto error;
12811
12812 mode = PyLong_AsLong(st_mode);
12813 if (mode == -1 && PyErr_Occurred())
12814 goto error;
12815 Py_CLEAR(st_mode);
12816 Py_CLEAR(stat);
12817 result = (mode & S_IFMT) == mode_bits;
Victor Stinner35a97c02015-03-08 02:59:09 +010012818#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012819 }
12820 else if (is_symlink) {
12821 assert(mode_bits != S_IFLNK);
12822 result = 0;
12823 }
12824 else {
12825 assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
12826#ifdef MS_WINDOWS
12827 dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
12828 if (mode_bits == S_IFDIR)
12829 result = dir_bits != 0;
12830 else
12831 result = dir_bits == 0;
12832#else /* POSIX */
12833 if (mode_bits == S_IFDIR)
12834 result = self->d_type == DT_DIR;
12835 else
12836 result = self->d_type == DT_REG;
12837#endif
12838 }
Victor Stinner35a97c02015-03-08 02:59:09 +010012839#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012840
12841 return result;
12842
12843error:
12844 Py_XDECREF(st_mode);
12845 Py_XDECREF(stat);
12846 return -1;
12847}
12848
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012849/*[clinic input]
12850os.DirEntry.is_dir -> bool
12851 *
12852 follow_symlinks: bool = True
Victor Stinner6036e442015-03-08 01:58:04 +010012853
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012854Return True if the entry is a directory; cached per entry.
12855[clinic start generated code]*/
12856
12857static int
12858os_DirEntry_is_dir_impl(DirEntry *self, int follow_symlinks)
12859/*[clinic end generated code: output=ad2e8d54365da287 input=0135232766f53f58]*/
12860{
12861 return DirEntry_test_mode(self, follow_symlinks, S_IFDIR);
Victor Stinner6036e442015-03-08 01:58:04 +010012862}
12863
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012864/*[clinic input]
12865os.DirEntry.is_file -> bool
12866 *
12867 follow_symlinks: bool = True
12868
12869Return True if the entry is a file; cached per entry.
12870[clinic start generated code]*/
12871
12872static int
12873os_DirEntry_is_file_impl(DirEntry *self, int follow_symlinks)
12874/*[clinic end generated code: output=8462ade481d8a476 input=0dc90be168b041ee]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012875{
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012876 return DirEntry_test_mode(self, follow_symlinks, S_IFREG);
Victor Stinner6036e442015-03-08 01:58:04 +010012877}
12878
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012879/*[clinic input]
12880os.DirEntry.inode
Victor Stinner6036e442015-03-08 01:58:04 +010012881
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012882Return inode of the entry; cached per entry.
12883[clinic start generated code]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012884
12885static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012886os_DirEntry_inode_impl(DirEntry *self)
12887/*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012888{
12889#ifdef MS_WINDOWS
12890 if (!self->got_file_index) {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012891 PyObject *unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012892 const wchar_t *path;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012893 STRUCT_STAT stat;
12894 int result;
Victor Stinner6036e442015-03-08 01:58:04 +010012895
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012896 if (!PyUnicode_FSDecoder(self->path, &unicode))
Victor Stinner6036e442015-03-08 01:58:04 +010012897 return NULL;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012898 path = PyUnicode_AsUnicode(unicode);
12899 result = LSTAT(path, &stat);
12900 Py_DECREF(unicode);
Victor Stinner6036e442015-03-08 01:58:04 +010012901
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012902 if (result != 0)
12903 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012904
12905 self->win32_file_index = stat.st_ino;
12906 self->got_file_index = 1;
12907 }
Victor Stinner0f6d7332017-03-09 17:34:28 +010012908 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->win32_file_index));
12909 return PyLong_FromUnsignedLongLong(self->win32_file_index);
Victor Stinner6036e442015-03-08 01:58:04 +010012910#else /* POSIX */
xdegaye50e86032017-05-22 11:15:08 +020012911 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->d_ino));
12912 return PyLong_FromUnsignedLongLong(self->d_ino);
Victor Stinner6036e442015-03-08 01:58:04 +010012913#endif
12914}
12915
12916static PyObject *
12917DirEntry_repr(DirEntry *self)
12918{
12919 return PyUnicode_FromFormat("<DirEntry %R>", self->name);
12920}
12921
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012922/*[clinic input]
12923os.DirEntry.__fspath__
12924
12925Returns the path for the entry.
12926[clinic start generated code]*/
12927
Brett Cannon96881cd2016-06-10 14:37:21 -070012928static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012929os_DirEntry___fspath___impl(DirEntry *self)
12930/*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
Brett Cannon96881cd2016-06-10 14:37:21 -070012931{
12932 Py_INCREF(self->path);
12933 return self->path;
12934}
12935
Victor Stinner6036e442015-03-08 01:58:04 +010012936static PyMemberDef DirEntry_members[] = {
12937 {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
12938 "the entry's base filename, relative to scandir() \"path\" argument"},
12939 {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
12940 "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
12941 {NULL}
12942};
12943
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012944#include "clinic/posixmodule.c.h"
12945
Victor Stinner6036e442015-03-08 01:58:04 +010012946static PyMethodDef DirEntry_methods[] = {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012947 OS_DIRENTRY_IS_DIR_METHODDEF
12948 OS_DIRENTRY_IS_FILE_METHODDEF
12949 OS_DIRENTRY_IS_SYMLINK_METHODDEF
12950 OS_DIRENTRY_STAT_METHODDEF
12951 OS_DIRENTRY_INODE_METHODDEF
12952 OS_DIRENTRY___FSPATH___METHODDEF
Victor Stinner6036e442015-03-08 01:58:04 +010012953 {NULL}
12954};
12955
Eddie Elizondob3966632019-11-05 07:16:14 -080012956static PyType_Slot DirEntryType_slots[] = {
12957 {Py_tp_new, _disabled_new},
12958 {Py_tp_dealloc, DirEntry_dealloc},
12959 {Py_tp_repr, DirEntry_repr},
12960 {Py_tp_methods, DirEntry_methods},
12961 {Py_tp_members, DirEntry_members},
12962 {0, 0},
Victor Stinner6036e442015-03-08 01:58:04 +010012963};
12964
Eddie Elizondob3966632019-11-05 07:16:14 -080012965static PyType_Spec DirEntryType_spec = {
12966 MODNAME ".DirEntry",
12967 sizeof(DirEntry),
12968 0,
12969 Py_TPFLAGS_DEFAULT,
12970 DirEntryType_slots
12971};
12972
12973
Victor Stinner6036e442015-03-08 01:58:04 +010012974#ifdef MS_WINDOWS
12975
12976static wchar_t *
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012977join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
Victor Stinner6036e442015-03-08 01:58:04 +010012978{
12979 Py_ssize_t path_len;
12980 Py_ssize_t size;
12981 wchar_t *result;
12982 wchar_t ch;
12983
12984 if (!path_wide) { /* Default arg: "." */
12985 path_wide = L".";
12986 path_len = 1;
12987 }
12988 else {
12989 path_len = wcslen(path_wide);
12990 }
12991
12992 /* The +1's are for the path separator and the NUL */
12993 size = path_len + 1 + wcslen(filename) + 1;
12994 result = PyMem_New(wchar_t, size);
12995 if (!result) {
12996 PyErr_NoMemory();
12997 return NULL;
12998 }
12999 wcscpy(result, path_wide);
13000 if (path_len > 0) {
13001 ch = result[path_len - 1];
13002 if (ch != SEP && ch != ALTSEP && ch != L':')
13003 result[path_len++] = SEP;
13004 wcscpy(result + path_len, filename);
13005 }
13006 return result;
13007}
13008
13009static PyObject *
13010DirEntry_from_find_data(path_t *path, WIN32_FIND_DATAW *dataW)
13011{
13012 DirEntry *entry;
13013 BY_HANDLE_FILE_INFORMATION file_info;
13014 ULONG reparse_tag;
13015 wchar_t *joined_path;
13016
Eddie Elizondob3966632019-11-05 07:16:14 -080013017 PyObject *DirEntryType = _posixstate_global->DirEntryType;
13018 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010013019 if (!entry)
13020 return NULL;
13021 entry->name = NULL;
13022 entry->path = NULL;
13023 entry->stat = NULL;
13024 entry->lstat = NULL;
13025 entry->got_file_index = 0;
13026
13027 entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
13028 if (!entry->name)
13029 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070013030 if (path->narrow) {
13031 Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
13032 if (!entry->name)
13033 goto error;
13034 }
Victor Stinner6036e442015-03-08 01:58:04 +010013035
13036 joined_path = join_path_filenameW(path->wide, dataW->cFileName);
13037 if (!joined_path)
13038 goto error;
13039
13040 entry->path = PyUnicode_FromWideChar(joined_path, -1);
13041 PyMem_Free(joined_path);
13042 if (!entry->path)
13043 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070013044 if (path->narrow) {
13045 Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
13046 if (!entry->path)
13047 goto error;
13048 }
Victor Stinner6036e442015-03-08 01:58:04 +010013049
Steve Dowercc16be82016-09-08 10:35:16 -070013050 find_data_to_file_info(dataW, &file_info, &reparse_tag);
Victor Stinner6036e442015-03-08 01:58:04 +010013051 _Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
13052
13053 return (PyObject *)entry;
13054
13055error:
13056 Py_DECREF(entry);
13057 return NULL;
13058}
13059
13060#else /* POSIX */
13061
13062static char *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020013063join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
Victor Stinner6036e442015-03-08 01:58:04 +010013064{
13065 Py_ssize_t path_len;
13066 Py_ssize_t size;
13067 char *result;
13068
13069 if (!path_narrow) { /* Default arg: "." */
13070 path_narrow = ".";
13071 path_len = 1;
13072 }
13073 else {
13074 path_len = strlen(path_narrow);
13075 }
13076
13077 if (filename_len == -1)
13078 filename_len = strlen(filename);
13079
13080 /* The +1's are for the path separator and the NUL */
13081 size = path_len + 1 + filename_len + 1;
13082 result = PyMem_New(char, size);
13083 if (!result) {
13084 PyErr_NoMemory();
13085 return NULL;
13086 }
13087 strcpy(result, path_narrow);
13088 if (path_len > 0 && result[path_len - 1] != '/')
13089 result[path_len++] = '/';
13090 strcpy(result + path_len, filename);
13091 return result;
13092}
13093
13094static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020013095DirEntry_from_posix_info(path_t *path, const char *name, Py_ssize_t name_len,
Victor Stinner35a97c02015-03-08 02:59:09 +010013096 ino_t d_ino
13097#ifdef HAVE_DIRENT_D_TYPE
13098 , unsigned char d_type
13099#endif
13100 )
Victor Stinner6036e442015-03-08 01:58:04 +010013101{
13102 DirEntry *entry;
13103 char *joined_path;
13104
Eddie Elizondob3966632019-11-05 07:16:14 -080013105 PyObject *DirEntryType = _posixstate_global->DirEntryType;
13106 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010013107 if (!entry)
13108 return NULL;
13109 entry->name = NULL;
13110 entry->path = NULL;
13111 entry->stat = NULL;
13112 entry->lstat = NULL;
13113
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013114 if (path->fd != -1) {
13115 entry->dir_fd = path->fd;
13116 joined_path = NULL;
13117 }
13118 else {
13119 entry->dir_fd = DEFAULT_DIR_FD;
13120 joined_path = join_path_filename(path->narrow, name, name_len);
13121 if (!joined_path)
13122 goto error;
13123 }
Victor Stinner6036e442015-03-08 01:58:04 +010013124
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +030013125 if (!path->narrow || !PyObject_CheckBuffer(path->object)) {
Victor Stinner6036e442015-03-08 01:58:04 +010013126 entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013127 if (joined_path)
13128 entry->path = PyUnicode_DecodeFSDefault(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013129 }
13130 else {
13131 entry->name = PyBytes_FromStringAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013132 if (joined_path)
13133 entry->path = PyBytes_FromString(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013134 }
13135 PyMem_Free(joined_path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013136 if (!entry->name)
13137 goto error;
13138
13139 if (path->fd != -1) {
13140 entry->path = entry->name;
13141 Py_INCREF(entry->path);
13142 }
13143 else if (!entry->path)
Victor Stinner6036e442015-03-08 01:58:04 +010013144 goto error;
13145
Victor Stinner35a97c02015-03-08 02:59:09 +010013146#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010013147 entry->d_type = d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010013148#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013149 entry->d_ino = d_ino;
13150
13151 return (PyObject *)entry;
13152
13153error:
13154 Py_XDECREF(entry);
13155 return NULL;
13156}
13157
13158#endif
13159
13160
13161typedef struct {
13162 PyObject_HEAD
13163 path_t path;
13164#ifdef MS_WINDOWS
13165 HANDLE handle;
13166 WIN32_FIND_DATAW file_data;
13167 int first_time;
13168#else /* POSIX */
13169 DIR *dirp;
13170#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013171#ifdef HAVE_FDOPENDIR
13172 int fd;
13173#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013174} ScandirIterator;
13175
13176#ifdef MS_WINDOWS
13177
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013178static int
13179ScandirIterator_is_closed(ScandirIterator *iterator)
13180{
13181 return iterator->handle == INVALID_HANDLE_VALUE;
13182}
13183
Victor Stinner6036e442015-03-08 01:58:04 +010013184static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013185ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013186{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013187 HANDLE handle = iterator->handle;
13188
13189 if (handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013190 return;
13191
Victor Stinner6036e442015-03-08 01:58:04 +010013192 iterator->handle = INVALID_HANDLE_VALUE;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013193 Py_BEGIN_ALLOW_THREADS
13194 FindClose(handle);
13195 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013196}
13197
13198static PyObject *
13199ScandirIterator_iternext(ScandirIterator *iterator)
13200{
13201 WIN32_FIND_DATAW *file_data = &iterator->file_data;
13202 BOOL success;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013203 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013204
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013205 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013206 if (iterator->handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013207 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013208
13209 while (1) {
13210 if (!iterator->first_time) {
13211 Py_BEGIN_ALLOW_THREADS
13212 success = FindNextFileW(iterator->handle, file_data);
13213 Py_END_ALLOW_THREADS
13214 if (!success) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013215 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013216 if (GetLastError() != ERROR_NO_MORE_FILES)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013217 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013218 break;
13219 }
13220 }
13221 iterator->first_time = 0;
13222
13223 /* Skip over . and .. */
13224 if (wcscmp(file_data->cFileName, L".") != 0 &&
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013225 wcscmp(file_data->cFileName, L"..") != 0) {
13226 entry = DirEntry_from_find_data(&iterator->path, file_data);
13227 if (!entry)
13228 break;
13229 return entry;
13230 }
Victor Stinner6036e442015-03-08 01:58:04 +010013231
13232 /* Loop till we get a non-dot directory or finish iterating */
13233 }
13234
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013235 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013236 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013237 return NULL;
13238}
13239
13240#else /* POSIX */
13241
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013242static int
13243ScandirIterator_is_closed(ScandirIterator *iterator)
13244{
13245 return !iterator->dirp;
13246}
13247
Victor Stinner6036e442015-03-08 01:58:04 +010013248static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013249ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013250{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013251 DIR *dirp = iterator->dirp;
13252
13253 if (!dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013254 return;
13255
Victor Stinner6036e442015-03-08 01:58:04 +010013256 iterator->dirp = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013257 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013258#ifdef HAVE_FDOPENDIR
13259 if (iterator->path.fd != -1)
13260 rewinddir(dirp);
13261#endif
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013262 closedir(dirp);
13263 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013264 return;
13265}
13266
13267static PyObject *
13268ScandirIterator_iternext(ScandirIterator *iterator)
13269{
13270 struct dirent *direntp;
13271 Py_ssize_t name_len;
13272 int is_dot;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013273 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013274
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013275 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013276 if (!iterator->dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013277 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013278
13279 while (1) {
13280 errno = 0;
13281 Py_BEGIN_ALLOW_THREADS
13282 direntp = readdir(iterator->dirp);
13283 Py_END_ALLOW_THREADS
13284
13285 if (!direntp) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013286 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013287 if (errno != 0)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013288 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013289 break;
13290 }
13291
13292 /* Skip over . and .. */
13293 name_len = NAMLEN(direntp);
13294 is_dot = direntp->d_name[0] == '.' &&
13295 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
13296 if (!is_dot) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013297 entry = DirEntry_from_posix_info(&iterator->path, direntp->d_name,
Victor Stinner35a97c02015-03-08 02:59:09 +010013298 name_len, direntp->d_ino
13299#ifdef HAVE_DIRENT_D_TYPE
13300 , direntp->d_type
13301#endif
13302 );
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013303 if (!entry)
13304 break;
13305 return entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013306 }
13307
13308 /* Loop till we get a non-dot directory or finish iterating */
13309 }
13310
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013311 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013312 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013313 return NULL;
13314}
13315
13316#endif
13317
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013318static PyObject *
13319ScandirIterator_close(ScandirIterator *self, PyObject *args)
13320{
13321 ScandirIterator_closedir(self);
13322 Py_RETURN_NONE;
13323}
13324
13325static PyObject *
13326ScandirIterator_enter(PyObject *self, PyObject *args)
13327{
13328 Py_INCREF(self);
13329 return self;
13330}
13331
13332static PyObject *
13333ScandirIterator_exit(ScandirIterator *self, PyObject *args)
13334{
13335 ScandirIterator_closedir(self);
13336 Py_RETURN_NONE;
13337}
13338
Victor Stinner6036e442015-03-08 01:58:04 +010013339static void
Victor Stinner7bfa4092016-03-23 00:43:54 +010013340ScandirIterator_finalize(ScandirIterator *iterator)
13341{
13342 PyObject *error_type, *error_value, *error_traceback;
13343
13344 /* Save the current exception, if any. */
13345 PyErr_Fetch(&error_type, &error_value, &error_traceback);
13346
13347 if (!ScandirIterator_is_closed(iterator)) {
13348 ScandirIterator_closedir(iterator);
13349
13350 if (PyErr_ResourceWarning((PyObject *)iterator, 1,
13351 "unclosed scandir iterator %R", iterator)) {
13352 /* Spurious errors can appear at shutdown */
13353 if (PyErr_ExceptionMatches(PyExc_Warning)) {
13354 PyErr_WriteUnraisable((PyObject *) iterator);
13355 }
13356 }
13357 }
13358
Victor Stinner7bfa4092016-03-23 00:43:54 +010013359 path_cleanup(&iterator->path);
13360
13361 /* Restore the saved exception. */
13362 PyErr_Restore(error_type, error_value, error_traceback);
13363}
13364
13365static void
Victor Stinner6036e442015-03-08 01:58:04 +010013366ScandirIterator_dealloc(ScandirIterator *iterator)
13367{
Eddie Elizondob3966632019-11-05 07:16:14 -080013368 PyTypeObject *tp = Py_TYPE(iterator);
Victor Stinner7bfa4092016-03-23 00:43:54 +010013369 if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
13370 return;
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013371
Eddie Elizondob3966632019-11-05 07:16:14 -080013372 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
13373 free_func(iterator);
13374 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010013375}
13376
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013377static PyMethodDef ScandirIterator_methods[] = {
13378 {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
13379 {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
13380 {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
13381 {NULL}
13382};
13383
Eddie Elizondob3966632019-11-05 07:16:14 -080013384static PyType_Slot ScandirIteratorType_slots[] = {
13385 {Py_tp_new, _disabled_new},
13386 {Py_tp_dealloc, ScandirIterator_dealloc},
13387 {Py_tp_finalize, ScandirIterator_finalize},
13388 {Py_tp_iter, PyObject_SelfIter},
13389 {Py_tp_iternext, ScandirIterator_iternext},
13390 {Py_tp_methods, ScandirIterator_methods},
13391 {0, 0},
13392};
13393
13394static PyType_Spec ScandirIteratorType_spec = {
13395 MODNAME ".ScandirIterator",
13396 sizeof(ScandirIterator),
13397 0,
13398 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE,
13399 ScandirIteratorType_slots
Victor Stinner6036e442015-03-08 01:58:04 +010013400};
13401
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013402/*[clinic input]
13403os.scandir
13404
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013405 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013406
13407Return an iterator of DirEntry objects for given path.
13408
BNMetricsb9427072018-11-02 15:20:19 +000013409path can be specified as either str, bytes, or a path-like object. If path
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013410is bytes, the names of yielded DirEntry objects will also be bytes; in
13411all other circumstances they will be str.
13412
13413If path is None, uses the path='.'.
13414[clinic start generated code]*/
13415
Victor Stinner6036e442015-03-08 01:58:04 +010013416static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013417os_scandir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +000013418/*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013419{
13420 ScandirIterator *iterator;
Victor Stinner6036e442015-03-08 01:58:04 +010013421#ifdef MS_WINDOWS
13422 wchar_t *path_strW;
13423#else
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013424 const char *path_str;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013425#ifdef HAVE_FDOPENDIR
13426 int fd = -1;
13427#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013428#endif
13429
Steve Dower60419a72019-06-24 08:42:54 -070013430 if (PySys_Audit("os.scandir", "O",
13431 path->object ? path->object : Py_None) < 0) {
13432 return NULL;
13433 }
13434
Hai Shif707d942020-03-16 21:15:01 +080013435 PyObject *ScandirIteratorType = get_posix_state(module)->ScandirIteratorType;
Eddie Elizondob3966632019-11-05 07:16:14 -080013436 iterator = PyObject_New(ScandirIterator, (PyTypeObject *)ScandirIteratorType);
Victor Stinner6036e442015-03-08 01:58:04 +010013437 if (!iterator)
13438 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013439
13440#ifdef MS_WINDOWS
13441 iterator->handle = INVALID_HANDLE_VALUE;
13442#else
13443 iterator->dirp = NULL;
13444#endif
13445
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013446 memcpy(&iterator->path, path, sizeof(path_t));
Serhiy Storchaka095ef732017-02-09 20:05:51 +020013447 /* Move the ownership to iterator->path */
13448 path->object = NULL;
13449 path->cleanup = NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013450
13451#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +010013452 iterator->first_time = 1;
13453
13454 path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
13455 if (!path_strW)
13456 goto error;
13457
13458 Py_BEGIN_ALLOW_THREADS
13459 iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
13460 Py_END_ALLOW_THREADS
13461
13462 PyMem_Free(path_strW);
13463
13464 if (iterator->handle == INVALID_HANDLE_VALUE) {
13465 path_error(&iterator->path);
13466 goto error;
13467 }
13468#else /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010013469 errno = 0;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013470#ifdef HAVE_FDOPENDIR
13471 if (path->fd != -1) {
13472 /* closedir() closes the FD, so we duplicate it */
13473 fd = _Py_dup(path->fd);
13474 if (fd == -1)
13475 goto error;
13476
13477 Py_BEGIN_ALLOW_THREADS
13478 iterator->dirp = fdopendir(fd);
13479 Py_END_ALLOW_THREADS
13480 }
13481 else
13482#endif
13483 {
13484 if (iterator->path.narrow)
13485 path_str = iterator->path.narrow;
13486 else
13487 path_str = ".";
13488
13489 Py_BEGIN_ALLOW_THREADS
13490 iterator->dirp = opendir(path_str);
13491 Py_END_ALLOW_THREADS
13492 }
Victor Stinner6036e442015-03-08 01:58:04 +010013493
13494 if (!iterator->dirp) {
13495 path_error(&iterator->path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013496#ifdef HAVE_FDOPENDIR
13497 if (fd != -1) {
13498 Py_BEGIN_ALLOW_THREADS
13499 close(fd);
13500 Py_END_ALLOW_THREADS
13501 }
13502#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013503 goto error;
13504 }
13505#endif
13506
13507 return (PyObject *)iterator;
13508
13509error:
13510 Py_DECREF(iterator);
13511 return NULL;
13512}
13513
Ethan Furman410ef8e2016-06-04 12:06:26 -070013514/*
13515 Return the file system path representation of the object.
13516
13517 If the object is str or bytes, then allow it to pass through with
13518 an incremented refcount. If the object defines __fspath__(), then
13519 return the result of that method. All other types raise a TypeError.
13520*/
13521PyObject *
13522PyOS_FSPath(PyObject *path)
13523{
Brett Cannon3f9183b2016-08-26 14:44:48 -070013524 /* For error message reasons, this function is manually inlined in
13525 path_converter(). */
Ethan Furman410ef8e2016-06-04 12:06:26 -070013526 PyObject *func = NULL;
13527 PyObject *path_repr = NULL;
13528
13529 if (PyUnicode_Check(path) || PyBytes_Check(path)) {
13530 Py_INCREF(path);
13531 return path;
13532 }
13533
13534 func = _PyObject_LookupSpecial(path, &PyId___fspath__);
13535 if (NULL == func) {
13536 return PyErr_Format(PyExc_TypeError,
13537 "expected str, bytes or os.PathLike object, "
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013538 "not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -080013539 _PyType_Name(Py_TYPE(path)));
Ethan Furman410ef8e2016-06-04 12:06:26 -070013540 }
13541
Victor Stinnerf17c3de2016-12-06 18:46:19 +010013542 path_repr = _PyObject_CallNoArg(func);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013543 Py_DECREF(func);
Brett Cannon044283a2016-07-15 10:41:49 -070013544 if (NULL == path_repr) {
13545 return NULL;
13546 }
13547
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013548 if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
13549 PyErr_Format(PyExc_TypeError,
13550 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -080013551 "not %.200s", _PyType_Name(Py_TYPE(path)),
13552 _PyType_Name(Py_TYPE(path_repr)));
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013553 Py_DECREF(path_repr);
13554 return NULL;
13555 }
13556
Ethan Furman410ef8e2016-06-04 12:06:26 -070013557 return path_repr;
13558}
13559
13560/*[clinic input]
13561os.fspath
13562
13563 path: object
13564
13565Return the file system path representation of the object.
13566
Brett Cannonb4f43e92016-06-09 14:32:08 -070013567If the object is str or bytes, then allow it to pass through as-is. If the
13568object defines __fspath__(), then return the result of that method. All other
13569types raise a TypeError.
Ethan Furman410ef8e2016-06-04 12:06:26 -070013570[clinic start generated code]*/
13571
13572static PyObject *
Serhiy Storchaka2954f832016-07-07 18:20:03 +030013573os_fspath_impl(PyObject *module, PyObject *path)
13574/*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
Ethan Furman410ef8e2016-06-04 12:06:26 -070013575{
13576 return PyOS_FSPath(path);
13577}
Victor Stinner6036e442015-03-08 01:58:04 +010013578
Victor Stinner9b1f4742016-09-06 16:18:52 -070013579#ifdef HAVE_GETRANDOM_SYSCALL
13580/*[clinic input]
13581os.getrandom
13582
13583 size: Py_ssize_t
13584 flags: int=0
13585
13586Obtain a series of random bytes.
13587[clinic start generated code]*/
13588
13589static PyObject *
13590os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
13591/*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
13592{
Victor Stinner9b1f4742016-09-06 16:18:52 -070013593 PyObject *bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013594 Py_ssize_t n;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013595
13596 if (size < 0) {
13597 errno = EINVAL;
13598 return posix_error();
13599 }
13600
Victor Stinnerec2319c2016-09-20 23:00:59 +020013601 bytes = PyBytes_FromStringAndSize(NULL, size);
13602 if (bytes == NULL) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013603 PyErr_NoMemory();
13604 return NULL;
13605 }
13606
13607 while (1) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013608 n = syscall(SYS_getrandom,
13609 PyBytes_AS_STRING(bytes),
13610 PyBytes_GET_SIZE(bytes),
13611 flags);
Victor Stinner9b1f4742016-09-06 16:18:52 -070013612 if (n < 0 && errno == EINTR) {
13613 if (PyErr_CheckSignals() < 0) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013614 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013615 }
Victor Stinnerec2319c2016-09-20 23:00:59 +020013616
13617 /* getrandom() was interrupted by a signal: retry */
Victor Stinner9b1f4742016-09-06 16:18:52 -070013618 continue;
13619 }
13620 break;
13621 }
13622
13623 if (n < 0) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013624 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerec2319c2016-09-20 23:00:59 +020013625 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013626 }
13627
Victor Stinnerec2319c2016-09-20 23:00:59 +020013628 if (n != size) {
13629 _PyBytes_Resize(&bytes, n);
13630 }
Victor Stinner9b1f4742016-09-06 16:18:52 -070013631
13632 return bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013633
13634error:
13635 Py_DECREF(bytes);
13636 return NULL;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013637}
13638#endif /* HAVE_GETRANDOM_SYSCALL */
13639
Steve Dower2438cdf2019-03-29 16:37:16 -070013640#ifdef MS_WINDOWS
13641/* bpo-36085: Helper functions for managing DLL search directories
13642 * on win32
13643 */
13644
13645typedef DLL_DIRECTORY_COOKIE (WINAPI *PAddDllDirectory)(PCWSTR newDirectory);
13646typedef BOOL (WINAPI *PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE cookie);
13647
13648/*[clinic input]
13649os._add_dll_directory
13650
13651 path: path_t
13652
13653Add a path to the DLL search path.
13654
13655This search path is used when resolving dependencies for imported
13656extension modules (the module itself is resolved through sys.path),
13657and also by ctypes.
13658
13659Returns an opaque value that may be passed to os.remove_dll_directory
13660to remove this directory from the search path.
13661[clinic start generated code]*/
13662
13663static PyObject *
13664os__add_dll_directory_impl(PyObject *module, path_t *path)
13665/*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
13666{
13667 HMODULE hKernel32;
13668 PAddDllDirectory AddDllDirectory;
13669 DLL_DIRECTORY_COOKIE cookie = 0;
13670 DWORD err = 0;
13671
Saiyang Gou7514f4f2020-02-12 23:47:42 -080013672 if (PySys_Audit("os.add_dll_directory", "(O)", path->object) < 0) {
13673 return NULL;
13674 }
13675
Steve Dower2438cdf2019-03-29 16:37:16 -070013676 /* For Windows 7, we have to load this. As this will be a fairly
13677 infrequent operation, just do it each time. Kernel32 is always
13678 loaded. */
13679 Py_BEGIN_ALLOW_THREADS
13680 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13681 !(AddDllDirectory = (PAddDllDirectory)GetProcAddress(
13682 hKernel32, "AddDllDirectory")) ||
13683 !(cookie = (*AddDllDirectory)(path->wide))) {
13684 err = GetLastError();
13685 }
13686 Py_END_ALLOW_THREADS
13687
13688 if (err) {
13689 return win32_error_object_err("add_dll_directory",
13690 path->object, err);
13691 }
13692
13693 return PyCapsule_New(cookie, "DLL directory cookie", NULL);
13694}
13695
13696/*[clinic input]
13697os._remove_dll_directory
13698
13699 cookie: object
13700
13701Removes a path from the DLL search path.
13702
13703The parameter is an opaque value that was returned from
13704os.add_dll_directory. You can only remove directories that you added
13705yourself.
13706[clinic start generated code]*/
13707
13708static PyObject *
13709os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
13710/*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
13711{
13712 HMODULE hKernel32;
13713 PRemoveDllDirectory RemoveDllDirectory;
13714 DLL_DIRECTORY_COOKIE cookieValue;
13715 DWORD err = 0;
13716
13717 if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
13718 PyErr_SetString(PyExc_TypeError,
13719 "Provided cookie was not returned from os.add_dll_directory");
13720 return NULL;
13721 }
13722
13723 cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
13724 cookie, "DLL directory cookie");
13725
13726 /* For Windows 7, we have to load this. As this will be a fairly
13727 infrequent operation, just do it each time. Kernel32 is always
13728 loaded. */
13729 Py_BEGIN_ALLOW_THREADS
13730 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13731 !(RemoveDllDirectory = (PRemoveDllDirectory)GetProcAddress(
13732 hKernel32, "RemoveDllDirectory")) ||
13733 !(*RemoveDllDirectory)(cookieValue)) {
13734 err = GetLastError();
13735 }
13736 Py_END_ALLOW_THREADS
13737
13738 if (err) {
13739 return win32_error_object_err("remove_dll_directory",
13740 NULL, err);
13741 }
13742
13743 if (PyCapsule_SetName(cookie, NULL)) {
13744 return NULL;
13745 }
13746
13747 Py_RETURN_NONE;
13748}
13749
13750#endif
Larry Hastings31826802013-10-19 00:09:25 -070013751
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013752static PyMethodDef posix_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -070013753
13754 OS_STAT_METHODDEF
13755 OS_ACCESS_METHODDEF
13756 OS_TTYNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013757 OS_CHDIR_METHODDEF
13758 OS_CHFLAGS_METHODDEF
13759 OS_CHMOD_METHODDEF
13760 OS_FCHMOD_METHODDEF
13761 OS_LCHMOD_METHODDEF
13762 OS_CHOWN_METHODDEF
13763 OS_FCHOWN_METHODDEF
13764 OS_LCHOWN_METHODDEF
13765 OS_LCHFLAGS_METHODDEF
13766 OS_CHROOT_METHODDEF
13767 OS_CTERMID_METHODDEF
13768 OS_GETCWD_METHODDEF
13769 OS_GETCWDB_METHODDEF
13770 OS_LINK_METHODDEF
13771 OS_LISTDIR_METHODDEF
13772 OS_LSTAT_METHODDEF
13773 OS_MKDIR_METHODDEF
13774 OS_NICE_METHODDEF
13775 OS_GETPRIORITY_METHODDEF
13776 OS_SETPRIORITY_METHODDEF
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000013777 OS_POSIX_SPAWN_METHODDEF
Joannah Nanjekye92b83222019-01-16 16:29:26 +030013778 OS_POSIX_SPAWNP_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013779 OS_READLINK_METHODDEF
Pablo Galindoaac4d032019-05-31 19:39:47 +010013780 OS_COPY_FILE_RANGE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013781 OS_RENAME_METHODDEF
13782 OS_REPLACE_METHODDEF
13783 OS_RMDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013784 OS_SYMLINK_METHODDEF
13785 OS_SYSTEM_METHODDEF
13786 OS_UMASK_METHODDEF
13787 OS_UNAME_METHODDEF
13788 OS_UNLINK_METHODDEF
13789 OS_REMOVE_METHODDEF
13790 OS_UTIME_METHODDEF
13791 OS_TIMES_METHODDEF
13792 OS__EXIT_METHODDEF
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020013793 OS__FCOPYFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013794 OS_EXECV_METHODDEF
13795 OS_EXECVE_METHODDEF
13796 OS_SPAWNV_METHODDEF
13797 OS_SPAWNVE_METHODDEF
13798 OS_FORK1_METHODDEF
13799 OS_FORK_METHODDEF
Antoine Pitrou346cbd32017-05-27 17:50:54 +020013800 OS_REGISTER_AT_FORK_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013801 OS_SCHED_GET_PRIORITY_MAX_METHODDEF
13802 OS_SCHED_GET_PRIORITY_MIN_METHODDEF
13803 OS_SCHED_GETPARAM_METHODDEF
13804 OS_SCHED_GETSCHEDULER_METHODDEF
13805 OS_SCHED_RR_GET_INTERVAL_METHODDEF
13806 OS_SCHED_SETPARAM_METHODDEF
13807 OS_SCHED_SETSCHEDULER_METHODDEF
13808 OS_SCHED_YIELD_METHODDEF
13809 OS_SCHED_SETAFFINITY_METHODDEF
13810 OS_SCHED_GETAFFINITY_METHODDEF
13811 OS_OPENPTY_METHODDEF
13812 OS_FORKPTY_METHODDEF
13813 OS_GETEGID_METHODDEF
13814 OS_GETEUID_METHODDEF
13815 OS_GETGID_METHODDEF
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +020013816#ifdef HAVE_GETGROUPLIST
13817 {"getgrouplist", posix_getgrouplist, METH_VARARGS, posix_getgrouplist__doc__},
13818#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013819 OS_GETGROUPS_METHODDEF
13820 OS_GETPID_METHODDEF
13821 OS_GETPGRP_METHODDEF
13822 OS_GETPPID_METHODDEF
13823 OS_GETUID_METHODDEF
13824 OS_GETLOGIN_METHODDEF
13825 OS_KILL_METHODDEF
13826 OS_KILLPG_METHODDEF
13827 OS_PLOCK_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013828#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -070013829 OS_STARTFILE_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013830#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013831 OS_SETUID_METHODDEF
13832 OS_SETEUID_METHODDEF
13833 OS_SETREUID_METHODDEF
13834 OS_SETGID_METHODDEF
13835 OS_SETEGID_METHODDEF
13836 OS_SETREGID_METHODDEF
13837 OS_SETGROUPS_METHODDEF
Antoine Pitroub7572f02009-12-02 20:46:48 +000013838#ifdef HAVE_INITGROUPS
Victor Stinner8c62be82010-05-06 00:08:46 +000013839 {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__},
Antoine Pitroub7572f02009-12-02 20:46:48 +000013840#endif /* HAVE_INITGROUPS */
Larry Hastings2f936352014-08-05 14:04:04 +100013841 OS_GETPGID_METHODDEF
13842 OS_SETPGRP_METHODDEF
13843 OS_WAIT_METHODDEF
13844 OS_WAIT3_METHODDEF
13845 OS_WAIT4_METHODDEF
13846 OS_WAITID_METHODDEF
13847 OS_WAITPID_METHODDEF
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -080013848 OS_PIDFD_OPEN_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013849 OS_GETSID_METHODDEF
13850 OS_SETSID_METHODDEF
13851 OS_SETPGID_METHODDEF
13852 OS_TCGETPGRP_METHODDEF
13853 OS_TCSETPGRP_METHODDEF
13854 OS_OPEN_METHODDEF
13855 OS_CLOSE_METHODDEF
13856 OS_CLOSERANGE_METHODDEF
13857 OS_DEVICE_ENCODING_METHODDEF
13858 OS_DUP_METHODDEF
13859 OS_DUP2_METHODDEF
13860 OS_LOCKF_METHODDEF
13861 OS_LSEEK_METHODDEF
13862 OS_READ_METHODDEF
13863 OS_READV_METHODDEF
13864 OS_PREAD_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013865 OS_PREADV_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013866 OS_WRITE_METHODDEF
13867 OS_WRITEV_METHODDEF
13868 OS_PWRITE_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013869 OS_PWRITEV_METHODDEF
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013870#ifdef HAVE_SENDFILE
Serhiy Storchaka62be7422018-11-27 13:27:31 +020013871 {"sendfile", (PyCFunction)(void(*)(void))posix_sendfile, METH_VARARGS | METH_KEYWORDS,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013872 posix_sendfile__doc__},
13873#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013874 OS_FSTAT_METHODDEF
13875 OS_ISATTY_METHODDEF
13876 OS_PIPE_METHODDEF
13877 OS_PIPE2_METHODDEF
13878 OS_MKFIFO_METHODDEF
13879 OS_MKNOD_METHODDEF
13880 OS_MAJOR_METHODDEF
13881 OS_MINOR_METHODDEF
13882 OS_MAKEDEV_METHODDEF
13883 OS_FTRUNCATE_METHODDEF
13884 OS_TRUNCATE_METHODDEF
13885 OS_POSIX_FALLOCATE_METHODDEF
13886 OS_POSIX_FADVISE_METHODDEF
13887 OS_PUTENV_METHODDEF
13888 OS_UNSETENV_METHODDEF
13889 OS_STRERROR_METHODDEF
13890 OS_FCHDIR_METHODDEF
13891 OS_FSYNC_METHODDEF
13892 OS_SYNC_METHODDEF
13893 OS_FDATASYNC_METHODDEF
13894 OS_WCOREDUMP_METHODDEF
13895 OS_WIFCONTINUED_METHODDEF
13896 OS_WIFSTOPPED_METHODDEF
13897 OS_WIFSIGNALED_METHODDEF
13898 OS_WIFEXITED_METHODDEF
13899 OS_WEXITSTATUS_METHODDEF
13900 OS_WTERMSIG_METHODDEF
13901 OS_WSTOPSIG_METHODDEF
13902 OS_FSTATVFS_METHODDEF
13903 OS_STATVFS_METHODDEF
13904 OS_CONFSTR_METHODDEF
13905 OS_SYSCONF_METHODDEF
13906 OS_FPATHCONF_METHODDEF
13907 OS_PATHCONF_METHODDEF
13908 OS_ABORT_METHODDEF
Serhiy Storchakaf0b50152015-05-13 00:52:39 +030013909 OS__GETFULLPATHNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013910 OS__GETDISKUSAGE_METHODDEF
13911 OS__GETFINALPATHNAME_METHODDEF
13912 OS__GETVOLUMEPATHNAME_METHODDEF
13913 OS_GETLOADAVG_METHODDEF
13914 OS_URANDOM_METHODDEF
13915 OS_SETRESUID_METHODDEF
13916 OS_SETRESGID_METHODDEF
13917 OS_GETRESUID_METHODDEF
13918 OS_GETRESGID_METHODDEF
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000013919
Larry Hastings2f936352014-08-05 14:04:04 +100013920 OS_GETXATTR_METHODDEF
13921 OS_SETXATTR_METHODDEF
13922 OS_REMOVEXATTR_METHODDEF
13923 OS_LISTXATTR_METHODDEF
13924
Antoine Pitroubcf2b592012-02-08 23:28:36 +010013925#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
13926 {"get_terminal_size", get_terminal_size, METH_VARARGS, termsize__doc__},
13927#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013928 OS_CPU_COUNT_METHODDEF
13929 OS_GET_INHERITABLE_METHODDEF
13930 OS_SET_INHERITABLE_METHODDEF
13931 OS_GET_HANDLE_INHERITABLE_METHODDEF
13932 OS_SET_HANDLE_INHERITABLE_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013933#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013934 OS_GET_BLOCKING_METHODDEF
13935 OS_SET_BLOCKING_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013936#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013937 OS_SCANDIR_METHODDEF
Ethan Furman410ef8e2016-06-04 12:06:26 -070013938 OS_FSPATH_METHODDEF
Victor Stinner9b1f4742016-09-06 16:18:52 -070013939 OS_GETRANDOM_METHODDEF
Zackery Spytz43fdbd22019-05-29 13:57:07 -060013940 OS_MEMFD_CREATE_METHODDEF
Steve Dower2438cdf2019-03-29 16:37:16 -070013941#ifdef MS_WINDOWS
13942 OS__ADD_DLL_DIRECTORY_METHODDEF
13943 OS__REMOVE_DLL_DIRECTORY_METHODDEF
13944#endif
Victor Stinner8c62be82010-05-06 00:08:46 +000013945 {NULL, NULL} /* Sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013946};
13947
Barry Warsaw4a342091996-12-19 23:50:02 +000013948static int
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013949all_ins(PyObject *m)
Barry Warsaw4a342091996-12-19 23:50:02 +000013950{
Guido van Rossum94f6f721999-01-06 18:42:14 +000013951#ifdef F_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013952 if (PyModule_AddIntMacro(m, F_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013953#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013954#ifdef R_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013955 if (PyModule_AddIntMacro(m, R_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013956#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013957#ifdef W_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013958 if (PyModule_AddIntMacro(m, W_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013959#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013960#ifdef X_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013961 if (PyModule_AddIntMacro(m, X_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013962#endif
Fred Drakec9680921999-12-13 16:37:25 +000013963#ifdef NGROUPS_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013964 if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
Fred Drakec9680921999-12-13 16:37:25 +000013965#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013966#ifdef TMP_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013967 if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013968#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013969#ifdef WCONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013970 if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013971#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013972#ifdef WNOHANG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013973 if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013974#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013975#ifdef WUNTRACED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013976 if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013977#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013978#ifdef O_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013979 if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013980#endif
13981#ifdef O_WRONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013982 if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013983#endif
13984#ifdef O_RDWR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013985 if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013986#endif
13987#ifdef O_NDELAY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013988 if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013989#endif
13990#ifdef O_NONBLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013991 if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013992#endif
13993#ifdef O_APPEND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013994 if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013995#endif
13996#ifdef O_DSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013997 if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013998#endif
13999#ifdef O_RSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014000 if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014001#endif
14002#ifdef O_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014003 if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014004#endif
14005#ifdef O_NOCTTY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014006 if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014007#endif
14008#ifdef O_CREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014009 if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014010#endif
14011#ifdef O_EXCL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014012 if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014013#endif
14014#ifdef O_TRUNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014015 if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014016#endif
Guido van Rossum98d9d091997-08-08 21:48:51 +000014017#ifdef O_BINARY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014018 if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000014019#endif
14020#ifdef O_TEXT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014021 if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000014022#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020014023#ifdef O_XATTR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014024 if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020014025#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014026#ifdef O_LARGEFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014027 if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014028#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020014029#ifndef __GNU__
Skip Montanaro5ff14922005-05-16 02:42:22 +000014030#ifdef O_SHLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014031 if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000014032#endif
14033#ifdef O_EXLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014034 if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000014035#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020014036#endif
Jesus Ceacf381202012-04-24 20:44:40 +020014037#ifdef O_EXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014038 if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020014039#endif
14040#ifdef O_SEARCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014041 if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020014042#endif
Benjamin Peterson3b965a22013-03-13 10:27:41 -050014043#ifdef O_PATH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014044 if (PyModule_AddIntMacro(m, O_PATH)) return -1;
Benjamin Peterson3b965a22013-03-13 10:27:41 -050014045#endif
Jesus Ceacf381202012-04-24 20:44:40 +020014046#ifdef O_TTY_INIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014047 if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020014048#endif
Christian Heimes177b3f92013-08-16 14:35:09 +020014049#ifdef O_TMPFILE
14050 if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
14051#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014052#ifdef PRIO_PROCESS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014053 if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014054#endif
14055#ifdef PRIO_PGRP
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014056 if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014057#endif
14058#ifdef PRIO_USER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014059 if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014060#endif
Charles-François Natali1e045b12011-05-22 20:42:32 +020014061#ifdef O_CLOEXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014062 if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
Charles-François Natali1e045b12011-05-22 20:42:32 +020014063#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020014064#ifdef O_ACCMODE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014065 if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020014066#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014067
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014068
Jesus Cea94363612012-06-22 18:32:07 +020014069#ifdef SEEK_HOLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014070 if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020014071#endif
14072#ifdef SEEK_DATA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014073 if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020014074#endif
14075
Tim Peters5aa91602002-01-30 05:46:57 +000014076/* MS Windows */
14077#ifdef O_NOINHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000014078 /* Don't inherit in child processes. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014079 if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014080#endif
14081#ifdef _O_SHORT_LIVED
Victor Stinner8c62be82010-05-06 00:08:46 +000014082 /* Optimize for short life (keep in memory). */
14083 /* MS forgot to define this one with a non-underscore form too. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014084 if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014085#endif
14086#ifdef O_TEMPORARY
Victor Stinner8c62be82010-05-06 00:08:46 +000014087 /* Automatically delete when last handle is closed. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014088 if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014089#endif
14090#ifdef O_RANDOM
Victor Stinner8c62be82010-05-06 00:08:46 +000014091 /* Optimize for random access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014092 if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014093#endif
14094#ifdef O_SEQUENTIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000014095 /* Optimize for sequential access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014096 if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014097#endif
14098
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014099/* GNU extensions. */
Alexandre Vassalottibee32532008-05-16 18:15:12 +000014100#ifdef O_ASYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000014101 /* Send a SIGIO signal whenever input or output
14102 becomes available on file descriptor */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014103 if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
Alexandre Vassalottibee32532008-05-16 18:15:12 +000014104#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014105#ifdef O_DIRECT
Victor Stinner8c62be82010-05-06 00:08:46 +000014106 /* Direct disk access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014107 if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014108#endif
14109#ifdef O_DIRECTORY
Victor Stinner8c62be82010-05-06 00:08:46 +000014110 /* Must be a directory. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014111 if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014112#endif
14113#ifdef O_NOFOLLOW
Victor Stinner8c62be82010-05-06 00:08:46 +000014114 /* Do not follow links. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014115 if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014116#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020014117#ifdef O_NOLINKS
14118 /* Fails if link count of the named file is greater than 1 */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014119 if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020014120#endif
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000014121#ifdef O_NOATIME
Victor Stinner8c62be82010-05-06 00:08:46 +000014122 /* Do not update the access time. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014123 if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000014124#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +000014125
Victor Stinner8c62be82010-05-06 00:08:46 +000014126 /* These come from sysexits.h */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014127#ifdef EX_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014128 if (PyModule_AddIntMacro(m, EX_OK)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014129#endif /* EX_OK */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014130#ifdef EX_USAGE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014131 if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014132#endif /* EX_USAGE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014133#ifdef EX_DATAERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014134 if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014135#endif /* EX_DATAERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014136#ifdef EX_NOINPUT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014137 if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014138#endif /* EX_NOINPUT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014139#ifdef EX_NOUSER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014140 if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014141#endif /* EX_NOUSER */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014142#ifdef EX_NOHOST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014143 if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014144#endif /* EX_NOHOST */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014145#ifdef EX_UNAVAILABLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014146 if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014147#endif /* EX_UNAVAILABLE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014148#ifdef EX_SOFTWARE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014149 if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014150#endif /* EX_SOFTWARE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014151#ifdef EX_OSERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014152 if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014153#endif /* EX_OSERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014154#ifdef EX_OSFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014155 if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014156#endif /* EX_OSFILE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014157#ifdef EX_CANTCREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014158 if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014159#endif /* EX_CANTCREAT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014160#ifdef EX_IOERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014161 if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014162#endif /* EX_IOERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014163#ifdef EX_TEMPFAIL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014164 if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014165#endif /* EX_TEMPFAIL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014166#ifdef EX_PROTOCOL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014167 if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014168#endif /* EX_PROTOCOL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014169#ifdef EX_NOPERM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014170 if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014171#endif /* EX_NOPERM */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014172#ifdef EX_CONFIG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014173 if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014174#endif /* EX_CONFIG */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014175#ifdef EX_NOTFOUND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014176 if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014177#endif /* EX_NOTFOUND */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014178
Amaury Forgeot d'Arc66d00ad2010-09-10 18:11:45 +000014179 /* statvfs */
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014180#ifdef ST_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014181 if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014182#endif /* ST_RDONLY */
14183#ifdef ST_NOSUID
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014184 if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014185#endif /* ST_NOSUID */
14186
doko@ubuntu.comca616a22013-12-08 15:23:07 +010014187 /* GNU extensions */
14188#ifdef ST_NODEV
14189 if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
14190#endif /* ST_NODEV */
14191#ifdef ST_NOEXEC
14192 if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
14193#endif /* ST_NOEXEC */
14194#ifdef ST_SYNCHRONOUS
14195 if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
14196#endif /* ST_SYNCHRONOUS */
14197#ifdef ST_MANDLOCK
14198 if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
14199#endif /* ST_MANDLOCK */
14200#ifdef ST_WRITE
14201 if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
14202#endif /* ST_WRITE */
14203#ifdef ST_APPEND
14204 if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
14205#endif /* ST_APPEND */
14206#ifdef ST_NOATIME
14207 if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
14208#endif /* ST_NOATIME */
14209#ifdef ST_NODIRATIME
14210 if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
14211#endif /* ST_NODIRATIME */
14212#ifdef ST_RELATIME
14213 if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
14214#endif /* ST_RELATIME */
14215
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014216 /* FreeBSD sendfile() constants */
14217#ifdef SF_NODISKIO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014218 if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014219#endif
14220#ifdef SF_MNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014221 if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014222#endif
14223#ifdef SF_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014224 if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014225#endif
14226
Ross Lagerwall7807c352011-03-17 20:20:30 +020014227 /* constants for posix_fadvise */
14228#ifdef POSIX_FADV_NORMAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014229 if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014230#endif
14231#ifdef POSIX_FADV_SEQUENTIAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014232 if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014233#endif
14234#ifdef POSIX_FADV_RANDOM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014235 if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014236#endif
14237#ifdef POSIX_FADV_NOREUSE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014238 if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014239#endif
14240#ifdef POSIX_FADV_WILLNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014241 if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014242#endif
14243#ifdef POSIX_FADV_DONTNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014244 if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014245#endif
14246
14247 /* constants for waitid */
14248#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014249 if (PyModule_AddIntMacro(m, P_PID)) return -1;
14250 if (PyModule_AddIntMacro(m, P_PGID)) return -1;
14251 if (PyModule_AddIntMacro(m, P_ALL)) return -1;
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080014252#ifdef P_PIDFD
14253 if (PyModule_AddIntMacro(m, P_PIDFD)) return -1;
14254#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014255#endif
14256#ifdef WEXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014257 if (PyModule_AddIntMacro(m, WEXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014258#endif
14259#ifdef WNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014260 if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014261#endif
14262#ifdef WSTOPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014263 if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014264#endif
14265#ifdef CLD_EXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014266 if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014267#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014268#ifdef CLD_KILLED
14269 if (PyModule_AddIntMacro(m, CLD_KILLED)) return -1;
14270#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014271#ifdef CLD_DUMPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014272 if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014273#endif
14274#ifdef CLD_TRAPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014275 if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014276#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014277#ifdef CLD_STOPPED
14278 if (PyModule_AddIntMacro(m, CLD_STOPPED)) return -1;
14279#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014280#ifdef CLD_CONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014281 if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014282#endif
14283
14284 /* constants for lockf */
14285#ifdef F_LOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014286 if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014287#endif
14288#ifdef F_TLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014289 if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014290#endif
14291#ifdef F_ULOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014292 if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014293#endif
14294#ifdef F_TEST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014295 if (PyModule_AddIntMacro(m, F_TEST)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014296#endif
14297
Pablo Galindo4defba32018-01-27 16:16:37 +000014298#ifdef RWF_DSYNC
14299 if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
14300#endif
14301#ifdef RWF_HIPRI
14302 if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
14303#endif
14304#ifdef RWF_SYNC
14305 if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
14306#endif
14307#ifdef RWF_NOWAIT
14308 if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
14309#endif
14310
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000014311/* constants for posix_spawn */
14312#ifdef HAVE_POSIX_SPAWN
14313 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
14314 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
14315 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
14316#endif
14317
pxinwrf2d7ac72019-05-21 18:46:37 +080014318#if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014319 if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
14320 if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014321 if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
pxinwrf2d7ac72019-05-21 18:46:37 +080014322#endif
14323#ifdef HAVE_SPAWNV
14324 if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014325 if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
Guido van Rossum246bc171999-02-01 23:54:31 +000014326#endif
14327
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014328#ifdef HAVE_SCHED_H
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014329#ifdef SCHED_OTHER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014330 if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014331#endif
14332#ifdef SCHED_FIFO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014333 if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014334#endif
14335#ifdef SCHED_RR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014336 if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014337#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014338#ifdef SCHED_SPORADIC
messi Liao0d322182017-06-13 22:30:43 +080014339 if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014340#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014341#ifdef SCHED_BATCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014342 if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014343#endif
14344#ifdef SCHED_IDLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014345 if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014346#endif
14347#ifdef SCHED_RESET_ON_FORK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014348 if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014349#endif
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014350#ifdef SCHED_SYS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014351 if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014352#endif
14353#ifdef SCHED_IA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014354 if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014355#endif
14356#ifdef SCHED_FSS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014357 if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014358#endif
14359#ifdef SCHED_FX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014360 if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014361#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014362#endif
14363
Benjamin Peterson9428d532011-09-14 11:45:52 -040014364#ifdef USE_XATTRS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014365 if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
14366 if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
14367 if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
Benjamin Peterson799bd802011-08-31 22:15:17 -040014368#endif
14369
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014370#if HAVE_DECL_RTLD_LAZY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014371 if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014372#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014373#if HAVE_DECL_RTLD_NOW
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014374 if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014375#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014376#if HAVE_DECL_RTLD_GLOBAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014377 if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014378#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014379#if HAVE_DECL_RTLD_LOCAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014380 if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014381#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014382#if HAVE_DECL_RTLD_NODELETE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014383 if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014384#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014385#if HAVE_DECL_RTLD_NOLOAD
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014386 if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014387#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014388#if HAVE_DECL_RTLD_DEEPBIND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014389 if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014390#endif
Michael Feltc5ae1692017-12-19 13:58:49 +010014391#if HAVE_DECL_RTLD_MEMBER
14392 if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
14393#endif
Victor Stinner8b905bd2011-10-25 13:34:04 +020014394
Victor Stinner9b1f4742016-09-06 16:18:52 -070014395#ifdef HAVE_GETRANDOM_SYSCALL
14396 if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
14397 if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
14398#endif
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014399#ifdef HAVE_MEMFD_CREATE
14400 if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
14401 if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
14402#ifdef MFD_HUGETLB
14403 if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014404#endif
14405#ifdef MFD_HUGE_SHIFT
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014406 if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014407#endif
14408#ifdef MFD_HUGE_MASK
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014409 if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014410#endif
14411#ifdef MFD_HUGE_64KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014412 if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014413#endif
14414#ifdef MFD_HUGE_512KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014415 if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014416#endif
14417#ifdef MFD_HUGE_1MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014418 if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014419#endif
14420#ifdef MFD_HUGE_2MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014421 if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014422#endif
14423#ifdef MFD_HUGE_8MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014424 if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014425#endif
14426#ifdef MFD_HUGE_16MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014427 if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014428#endif
14429#ifdef MFD_HUGE_32MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014430 if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014431#endif
14432#ifdef MFD_HUGE_256MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014433 if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014434#endif
14435#ifdef MFD_HUGE_512MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014436 if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014437#endif
14438#ifdef MFD_HUGE_1GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014439 if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014440#endif
14441#ifdef MFD_HUGE_2GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014442 if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014443#endif
14444#ifdef MFD_HUGE_16GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014445 if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
14446#endif
14447#endif
Victor Stinner9b1f4742016-09-06 16:18:52 -070014448
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020014449#if defined(__APPLE__)
14450 if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
14451#endif
14452
Steve Dower2438cdf2019-03-29 16:37:16 -070014453#ifdef MS_WINDOWS
14454 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
14455 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
14456 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
14457 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
14458 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
14459#endif
14460
Victor Stinner8c62be82010-05-06 00:08:46 +000014461 return 0;
Barry Warsaw4a342091996-12-19 23:50:02 +000014462}
14463
14464
Martin v. Löwis1a214512008-06-11 05:26:20 +000014465static struct PyModuleDef posixmodule = {
Victor Stinner8c62be82010-05-06 00:08:46 +000014466 PyModuleDef_HEAD_INIT,
14467 MODNAME,
14468 posix__doc__,
Eddie Elizondob3966632019-11-05 07:16:14 -080014469 sizeof(_posixstate),
Victor Stinner8c62be82010-05-06 00:08:46 +000014470 posix_methods,
14471 NULL,
Eddie Elizondob3966632019-11-05 07:16:14 -080014472 _posix_traverse,
14473 _posix_clear,
14474 _posix_free,
Martin v. Löwis1a214512008-06-11 05:26:20 +000014475};
14476
14477
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014478static const char * const have_functions[] = {
Larry Hastings9cf065c2012-06-22 16:30:09 -070014479
14480#ifdef HAVE_FACCESSAT
14481 "HAVE_FACCESSAT",
14482#endif
14483
14484#ifdef HAVE_FCHDIR
14485 "HAVE_FCHDIR",
14486#endif
14487
14488#ifdef HAVE_FCHMOD
14489 "HAVE_FCHMOD",
14490#endif
14491
14492#ifdef HAVE_FCHMODAT
14493 "HAVE_FCHMODAT",
14494#endif
14495
14496#ifdef HAVE_FCHOWN
14497 "HAVE_FCHOWN",
14498#endif
14499
Larry Hastings00964ed2013-08-12 13:49:30 -040014500#ifdef HAVE_FCHOWNAT
14501 "HAVE_FCHOWNAT",
14502#endif
14503
Larry Hastings9cf065c2012-06-22 16:30:09 -070014504#ifdef HAVE_FEXECVE
14505 "HAVE_FEXECVE",
14506#endif
14507
14508#ifdef HAVE_FDOPENDIR
14509 "HAVE_FDOPENDIR",
14510#endif
14511
Georg Brandl306336b2012-06-24 12:55:33 +020014512#ifdef HAVE_FPATHCONF
14513 "HAVE_FPATHCONF",
14514#endif
14515
Larry Hastings9cf065c2012-06-22 16:30:09 -070014516#ifdef HAVE_FSTATAT
14517 "HAVE_FSTATAT",
14518#endif
14519
14520#ifdef HAVE_FSTATVFS
14521 "HAVE_FSTATVFS",
14522#endif
14523
Steve Dowerfe0a41a2015-03-20 19:50:46 -070014524#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Georg Brandl306336b2012-06-24 12:55:33 +020014525 "HAVE_FTRUNCATE",
14526#endif
14527
Larry Hastings9cf065c2012-06-22 16:30:09 -070014528#ifdef HAVE_FUTIMENS
14529 "HAVE_FUTIMENS",
14530#endif
14531
14532#ifdef HAVE_FUTIMES
14533 "HAVE_FUTIMES",
14534#endif
14535
14536#ifdef HAVE_FUTIMESAT
14537 "HAVE_FUTIMESAT",
14538#endif
14539
14540#ifdef HAVE_LINKAT
14541 "HAVE_LINKAT",
14542#endif
14543
14544#ifdef HAVE_LCHFLAGS
14545 "HAVE_LCHFLAGS",
14546#endif
14547
14548#ifdef HAVE_LCHMOD
14549 "HAVE_LCHMOD",
14550#endif
14551
14552#ifdef HAVE_LCHOWN
14553 "HAVE_LCHOWN",
14554#endif
14555
14556#ifdef HAVE_LSTAT
14557 "HAVE_LSTAT",
14558#endif
14559
14560#ifdef HAVE_LUTIMES
14561 "HAVE_LUTIMES",
14562#endif
14563
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014564#ifdef HAVE_MEMFD_CREATE
14565 "HAVE_MEMFD_CREATE",
14566#endif
14567
Larry Hastings9cf065c2012-06-22 16:30:09 -070014568#ifdef HAVE_MKDIRAT
14569 "HAVE_MKDIRAT",
14570#endif
14571
14572#ifdef HAVE_MKFIFOAT
14573 "HAVE_MKFIFOAT",
14574#endif
14575
14576#ifdef HAVE_MKNODAT
14577 "HAVE_MKNODAT",
14578#endif
14579
14580#ifdef HAVE_OPENAT
14581 "HAVE_OPENAT",
14582#endif
14583
14584#ifdef HAVE_READLINKAT
14585 "HAVE_READLINKAT",
14586#endif
14587
14588#ifdef HAVE_RENAMEAT
14589 "HAVE_RENAMEAT",
14590#endif
14591
14592#ifdef HAVE_SYMLINKAT
14593 "HAVE_SYMLINKAT",
14594#endif
14595
14596#ifdef HAVE_UNLINKAT
14597 "HAVE_UNLINKAT",
14598#endif
14599
14600#ifdef HAVE_UTIMENSAT
14601 "HAVE_UTIMENSAT",
14602#endif
14603
14604#ifdef MS_WINDOWS
14605 "MS_WINDOWS",
14606#endif
14607
14608 NULL
14609};
14610
14611
Mark Hammondfe51c6d2002-08-02 02:27:13 +000014612PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +000014613INITFUNC(void)
Guido van Rossumb6775db1994-08-01 11:34:53 +000014614{
Victor Stinner8c62be82010-05-06 00:08:46 +000014615 PyObject *m, *v;
Larry Hastings9cf065c2012-06-22 16:30:09 -070014616 PyObject *list;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014617 const char * const *trace;
Tim Peters5aa91602002-01-30 05:46:57 +000014618
Eddie Elizondob3966632019-11-05 07:16:14 -080014619 m = PyState_FindModule(&posixmodule);
14620 if (m != NULL) {
14621 Py_INCREF(m);
14622 return m;
14623 }
14624
Victor Stinner8c62be82010-05-06 00:08:46 +000014625 m = PyModule_Create(&posixmodule);
14626 if (m == NULL)
14627 return NULL;
Tim Peters5aa91602002-01-30 05:46:57 +000014628
Victor Stinner8c62be82010-05-06 00:08:46 +000014629 /* Initialize environ dictionary */
14630 v = convertenviron();
14631 Py_XINCREF(v);
14632 if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
14633 return NULL;
14634 Py_DECREF(v);
Fred Drakec9680921999-12-13 16:37:25 +000014635
Victor Stinner8c62be82010-05-06 00:08:46 +000014636 if (all_ins(m))
14637 return NULL;
Barry Warsaw4a342091996-12-19 23:50:02 +000014638
Victor Stinner8c62be82010-05-06 00:08:46 +000014639 if (setup_confname_tables(m))
14640 return NULL;
Fred Drakebec628d1999-12-15 18:31:10 +000014641
Victor Stinner8c62be82010-05-06 00:08:46 +000014642 Py_INCREF(PyExc_OSError);
14643 PyModule_AddObject(m, "error", PyExc_OSError);
Fred Drake762e2061999-08-26 17:23:54 +000014644
Ross Lagerwall7807c352011-03-17 20:20:30 +020014645#if defined(HAVE_WAITID) && !defined(__APPLE__)
Eddie Elizondob3966632019-11-05 07:16:14 -080014646 waitid_result_desc.name = MODNAME ".waitid_result";
14647 PyObject *WaitidResultType = (PyObject *)PyStructSequence_NewType(&waitid_result_desc);
14648 if (WaitidResultType == NULL) {
14649 return NULL;
14650 }
14651 Py_INCREF(WaitidResultType);
14652 PyModule_AddObject(m, "waitid_result", WaitidResultType);
Hai Shif707d942020-03-16 21:15:01 +080014653 get_posix_state(m)->WaitidResultType = WaitidResultType;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014654#endif
14655
Eddie Elizondob3966632019-11-05 07:16:14 -080014656 stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
14657 stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
14658 stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
14659 stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
14660 PyObject *StatResultType = (PyObject *)PyStructSequence_NewType(&stat_result_desc);
14661 if (StatResultType == NULL) {
14662 return NULL;
14663 }
14664 Py_INCREF(StatResultType);
14665 PyModule_AddObject(m, "stat_result", StatResultType);
Hai Shif707d942020-03-16 21:15:01 +080014666 get_posix_state(m)->StatResultType = StatResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014667 structseq_new = ((PyTypeObject *)StatResultType)->tp_new;
14668 ((PyTypeObject *)StatResultType)->tp_new = statresult_new;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014669
Eddie Elizondob3966632019-11-05 07:16:14 -080014670 statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
14671 PyObject *StatVFSResultType = (PyObject *)PyStructSequence_NewType(&statvfs_result_desc);
14672 if (StatVFSResultType == NULL) {
14673 return NULL;
14674 }
14675 Py_INCREF(StatVFSResultType);
14676 PyModule_AddObject(m, "statvfs_result", StatVFSResultType);
Hai Shif707d942020-03-16 21:15:01 +080014677 get_posix_state(m)->StatVFSResultType = StatVFSResultType;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014678#ifdef NEED_TICKS_PER_SECOND
14679# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Eddie Elizondob3966632019-11-05 07:16:14 -080014680 ticks_per_second = sysconf(_SC_CLK_TCK);
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014681# elif defined(HZ)
Eddie Elizondob3966632019-11-05 07:16:14 -080014682 ticks_per_second = HZ;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014683# else
Eddie Elizondob3966632019-11-05 07:16:14 -080014684 ticks_per_second = 60; /* magic fallback value; may be bogus */
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014685# endif
14686#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014687
William Orr81574b82018-10-01 22:19:56 -070014688#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Eddie Elizondob3966632019-11-05 07:16:14 -080014689 sched_param_desc.name = MODNAME ".sched_param";
14690 PyObject *SchedParamType = (PyObject *)PyStructSequence_NewType(&sched_param_desc);
14691 if (SchedParamType == NULL) {
14692 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000014693 }
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014694 Py_INCREF(SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -080014695 PyModule_AddObject(m, "sched_param", SchedParamType);
Hai Shif707d942020-03-16 21:15:01 +080014696 get_posix_state(m)->SchedParamType = SchedParamType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014697 ((PyTypeObject *)SchedParamType)->tp_new = os_sched_param;
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014698#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +000014699
Eddie Elizondob3966632019-11-05 07:16:14 -080014700 /* initialize TerminalSize_info */
14701 PyObject *TerminalSizeType = (PyObject *)PyStructSequence_NewType(&TerminalSize_desc);
14702 if (TerminalSizeType == NULL) {
14703 return NULL;
14704 }
14705 Py_INCREF(TerminalSizeType);
14706 PyModule_AddObject(m, "terminal_size", TerminalSizeType);
Hai Shif707d942020-03-16 21:15:01 +080014707 get_posix_state(m)->TerminalSizeType = TerminalSizeType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014708
14709 /* initialize scandir types */
14710 PyObject *ScandirIteratorType = PyType_FromSpec(&ScandirIteratorType_spec);
14711 if (ScandirIteratorType == NULL) {
14712 return NULL;
14713 }
Hai Shif707d942020-03-16 21:15:01 +080014714 get_posix_state(m)->ScandirIteratorType = ScandirIteratorType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014715
14716 PyObject *DirEntryType = PyType_FromSpec(&DirEntryType_spec);
14717 if (DirEntryType == NULL) {
14718 return NULL;
14719 }
14720 Py_INCREF(DirEntryType);
14721 PyModule_AddObject(m, "DirEntry", DirEntryType);
Hai Shif707d942020-03-16 21:15:01 +080014722 get_posix_state(m)->DirEntryType = DirEntryType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014723
Larry Hastings605a62d2012-06-24 04:33:36 -070014724 times_result_desc.name = MODNAME ".times_result";
Eddie Elizondob3966632019-11-05 07:16:14 -080014725 PyObject *TimesResultType = (PyObject *)PyStructSequence_NewType(&times_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014726 if (TimesResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014727 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014728 }
Eddie Elizondob3966632019-11-05 07:16:14 -080014729 Py_INCREF(TimesResultType);
14730 PyModule_AddObject(m, "times_result", TimesResultType);
Hai Shif707d942020-03-16 21:15:01 +080014731 get_posix_state(m)->TimesResultType = TimesResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070014732
Eddie Elizondob3966632019-11-05 07:16:14 -080014733 PyTypeObject *UnameResultType = PyStructSequence_NewType(&uname_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014734 if (UnameResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014735 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014736 }
Eddie Elizondob3966632019-11-05 07:16:14 -080014737 Py_INCREF(UnameResultType);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014738 PyModule_AddObject(m, "uname_result", (PyObject *)UnameResultType);
Hai Shif707d942020-03-16 21:15:01 +080014739 get_posix_state(m)->UnameResultType = (PyObject *)UnameResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070014740
Thomas Wouters477c8d52006-05-27 19:21:47 +000014741#ifdef __APPLE__
Victor Stinner8c62be82010-05-06 00:08:46 +000014742 /*
14743 * Step 2 of weak-linking support on Mac OS X.
14744 *
14745 * The code below removes functions that are not available on the
14746 * currently active platform.
14747 *
14748 * This block allow one to use a python binary that was build on
Larry Hastings9cf065c2012-06-22 16:30:09 -070014749 * OSX 10.4 on OSX 10.3, without losing access to new APIs on
Victor Stinner8c62be82010-05-06 00:08:46 +000014750 * OSX 10.4.
14751 */
Thomas Wouters477c8d52006-05-27 19:21:47 +000014752#ifdef HAVE_FSTATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014753 if (fstatvfs == NULL) {
14754 if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
14755 return NULL;
14756 }
14757 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014758#endif /* HAVE_FSTATVFS */
14759
14760#ifdef HAVE_STATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014761 if (statvfs == NULL) {
14762 if (PyObject_DelAttrString(m, "statvfs") == -1) {
14763 return NULL;
14764 }
14765 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014766#endif /* HAVE_STATVFS */
14767
14768# ifdef HAVE_LCHOWN
Victor Stinner8c62be82010-05-06 00:08:46 +000014769 if (lchown == NULL) {
14770 if (PyObject_DelAttrString(m, "lchown") == -1) {
14771 return NULL;
14772 }
14773 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014774#endif /* HAVE_LCHOWN */
14775
14776
14777#endif /* __APPLE__ */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014778
Hai Shif707d942020-03-16 21:15:01 +080014779 if ((get_posix_state(m)->billion = PyLong_FromLong(1000000000)) == NULL)
Eddie Elizondob3966632019-11-05 07:16:14 -080014780 return NULL;
14781#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
Hai Shif707d942020-03-16 21:15:01 +080014782 get_posix_state(m)->struct_rusage = PyUnicode_InternFromString("struct_rusage");
14783 if (get_posix_state(m)->struct_rusage == NULL)
Eddie Elizondob3966632019-11-05 07:16:14 -080014784 return NULL;
14785#endif
Hai Shif707d942020-03-16 21:15:01 +080014786 get_posix_state(m)->st_mode = PyUnicode_InternFromString("st_mode");
14787 if (get_posix_state(m)->st_mode == NULL)
Larry Hastings6fe20b32012-04-19 15:07:49 -070014788 return NULL;
14789
Larry Hastings9cf065c2012-06-22 16:30:09 -070014790 /* suppress "function not used" warnings */
14791 {
14792 int ignored;
14793 fd_specified("", -1);
14794 follow_symlinks_specified("", 1);
14795 dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
14796 dir_fd_converter(Py_None, &ignored);
14797 dir_fd_unavailable(Py_None, &ignored);
14798 }
14799
14800 /*
14801 * provide list of locally available functions
14802 * so os.py can populate support_* lists
14803 */
14804 list = PyList_New(0);
14805 if (!list)
14806 return NULL;
14807 for (trace = have_functions; *trace; trace++) {
14808 PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
14809 if (!unicode)
14810 return NULL;
14811 if (PyList_Append(list, unicode))
14812 return NULL;
14813 Py_DECREF(unicode);
14814 }
14815 PyModule_AddObject(m, "_have_functions", list);
Ned Deilyeb3be662016-08-15 14:40:38 -040014816
Victor Stinner8c62be82010-05-06 00:08:46 +000014817 return m;
Guido van Rossumb6775db1994-08-01 11:34:53 +000014818}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014819
14820#ifdef __cplusplus
14821}
14822#endif