blob: e489b74ec70f50f4f38ea24bce965071000010c0 [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
Victor Stinner8ec73702020-03-23 20:00:57 +01007002#ifdef __APPLE__
7003 while (getgrouplist(user, basegid, groups, &ngroups)) {
7004 /* On macOS, getgrouplist() returns a non-zero value without setting
7005 errno if the group list is too small. Double the list size and call
7006 it again in this case. */
7007 PyMem_Free(groups);
7008
7009 if (ngroups > INT_MAX / 2) {
7010 return PyErr_NoMemory();
7011 }
7012 ngroups *= 2;
7013
7014 groups = PyMem_New(int, ngroups);
7015 if (groups == NULL) {
7016 return PyErr_NoMemory();
7017 }
7018 }
7019#else
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007020 if (getgrouplist(user, basegid, groups, &ngroups) == -1) {
7021 PyMem_Del(groups);
7022 return posix_error();
7023 }
Victor Stinner8ec73702020-03-23 20:00:57 +01007024#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007025
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08007026#ifdef _Py_MEMORY_SANITIZER
7027 /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
7028 __msan_unpoison(&ngroups, sizeof(ngroups));
7029 __msan_unpoison(groups, ngroups*sizeof(*groups));
7030#endif
7031
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007032 list = PyList_New(ngroups);
7033 if (list == NULL) {
7034 PyMem_Del(groups);
7035 return NULL;
7036 }
7037
7038 for (i = 0; i < ngroups; i++) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007039#ifdef __APPLE__
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007040 PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007041#else
7042 PyObject *o = _PyLong_FromGid(groups[i]);
7043#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02007044 if (o == NULL) {
7045 Py_DECREF(list);
7046 PyMem_Del(groups);
7047 return NULL;
7048 }
7049 PyList_SET_ITEM(list, i, o);
7050 }
7051
7052 PyMem_Del(groups);
7053
7054 return list;
7055}
Larry Hastings2f936352014-08-05 14:04:04 +10007056#endif /* HAVE_GETGROUPLIST */
7057
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007058
Fred Drakec9680921999-12-13 16:37:25 +00007059#ifdef HAVE_GETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007060/*[clinic input]
7061os.getgroups
7062
7063Return list of supplemental group IDs for the process.
7064[clinic start generated code]*/
7065
Larry Hastings2f936352014-08-05 14:04:04 +10007066static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007067os_getgroups_impl(PyObject *module)
7068/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
Fred Drakec9680921999-12-13 16:37:25 +00007069{
7070 PyObject *result = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00007071 gid_t grouplist[MAX_GROUPS];
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007072
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007073 /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007074 * This is a helper variable to store the intermediate result when
7075 * that happens.
7076 *
7077 * To keep the code readable the OSX behaviour is unconditional,
7078 * according to the POSIX spec this should be safe on all unix-y
7079 * systems.
7080 */
7081 gid_t* alt_grouplist = grouplist;
Victor Stinner8c62be82010-05-06 00:08:46 +00007082 int n;
Fred Drakec9680921999-12-13 16:37:25 +00007083
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007084#ifdef __APPLE__
7085 /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
7086 * there are more groups than can fit in grouplist. Therefore, on OS X
7087 * always first call getgroups with length 0 to get the actual number
7088 * of groups.
7089 */
7090 n = getgroups(0, NULL);
7091 if (n < 0) {
7092 return posix_error();
7093 } else if (n <= MAX_GROUPS) {
7094 /* groups will fit in existing array */
7095 alt_grouplist = grouplist;
7096 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02007097 alt_grouplist = PyMem_New(gid_t, n);
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007098 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07007099 return PyErr_NoMemory();
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007100 }
7101 }
7102
7103 n = getgroups(n, alt_grouplist);
7104 if (n == -1) {
7105 if (alt_grouplist != grouplist) {
7106 PyMem_Free(alt_grouplist);
7107 }
7108 return posix_error();
7109 }
7110#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007111 n = getgroups(MAX_GROUPS, grouplist);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007112 if (n < 0) {
7113 if (errno == EINVAL) {
7114 n = getgroups(0, NULL);
7115 if (n == -1) {
7116 return posix_error();
7117 }
7118 if (n == 0) {
7119 /* Avoid malloc(0) */
7120 alt_grouplist = grouplist;
7121 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02007122 alt_grouplist = PyMem_New(gid_t, n);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007123 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07007124 return PyErr_NoMemory();
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007125 }
7126 n = getgroups(n, alt_grouplist);
7127 if (n == -1) {
7128 PyMem_Free(alt_grouplist);
7129 return posix_error();
7130 }
7131 }
7132 } else {
7133 return posix_error();
7134 }
7135 }
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007136#endif
7137
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007138 result = PyList_New(n);
7139 if (result != NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007140 int i;
7141 for (i = 0; i < n; ++i) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007142 PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
Victor Stinner8c62be82010-05-06 00:08:46 +00007143 if (o == NULL) {
Stefan Krah0e803b32010-11-26 16:16:47 +00007144 Py_DECREF(result);
7145 result = NULL;
7146 break;
Fred Drakec9680921999-12-13 16:37:25 +00007147 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007148 PyList_SET_ITEM(result, i, o);
Fred Drakec9680921999-12-13 16:37:25 +00007149 }
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007150 }
7151
7152 if (alt_grouplist != grouplist) {
7153 PyMem_Free(alt_grouplist);
Victor Stinner8c62be82010-05-06 00:08:46 +00007154 }
Neal Norwitze241ce82003-02-17 18:17:05 +00007155
Fred Drakec9680921999-12-13 16:37:25 +00007156 return result;
7157}
Larry Hastings2f936352014-08-05 14:04:04 +10007158#endif /* HAVE_GETGROUPS */
Fred Drakec9680921999-12-13 16:37:25 +00007159
Antoine Pitroub7572f02009-12-02 20:46:48 +00007160#ifdef HAVE_INITGROUPS
7161PyDoc_STRVAR(posix_initgroups__doc__,
7162"initgroups(username, gid) -> None\n\n\
7163Call the system initgroups() to initialize the group access list with all of\n\
7164the groups of which the specified username is a member, plus the specified\n\
7165group id.");
7166
Larry Hastings2f936352014-08-05 14:04:04 +10007167/* AC 3.5: funny apple logic */
Antoine Pitroub7572f02009-12-02 20:46:48 +00007168static PyObject *
7169posix_initgroups(PyObject *self, PyObject *args)
7170{
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007171 PyObject *oname;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03007172 const char *username;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007173 int res;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007174#ifdef __APPLE__
7175 int gid;
7176#else
7177 gid_t gid;
7178#endif
Antoine Pitroub7572f02009-12-02 20:46:48 +00007179
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007180#ifdef __APPLE__
7181 if (!PyArg_ParseTuple(args, "O&i:initgroups",
7182 PyUnicode_FSConverter, &oname,
7183 &gid))
7184#else
7185 if (!PyArg_ParseTuple(args, "O&O&:initgroups",
7186 PyUnicode_FSConverter, &oname,
7187 _Py_Gid_Converter, &gid))
7188#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00007189 return NULL;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007190 username = PyBytes_AS_STRING(oname);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007191
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007192 res = initgroups(username, gid);
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007193 Py_DECREF(oname);
7194 if (res == -1)
Victor Stinner8c62be82010-05-06 00:08:46 +00007195 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007196
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007197 Py_RETURN_NONE;
Antoine Pitroub7572f02009-12-02 20:46:48 +00007198}
Larry Hastings2f936352014-08-05 14:04:04 +10007199#endif /* HAVE_INITGROUPS */
7200
Antoine Pitroub7572f02009-12-02 20:46:48 +00007201
Martin v. Löwis606edc12002-06-13 21:09:11 +00007202#ifdef HAVE_GETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10007203/*[clinic input]
7204os.getpgid
7205
7206 pid: pid_t
7207
7208Call the system call getpgid(), and return the result.
7209[clinic start generated code]*/
7210
Larry Hastings2f936352014-08-05 14:04:04 +10007211static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007212os_getpgid_impl(PyObject *module, pid_t pid)
7213/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007214{
7215 pid_t pgid = getpgid(pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007216 if (pgid < 0)
7217 return posix_error();
7218 return PyLong_FromPid(pgid);
Martin v. Löwis606edc12002-06-13 21:09:11 +00007219}
7220#endif /* HAVE_GETPGID */
7221
7222
Guido van Rossumb6775db1994-08-01 11:34:53 +00007223#ifdef HAVE_GETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007224/*[clinic input]
7225os.getpgrp
7226
7227Return the current process group id.
7228[clinic start generated code]*/
7229
Larry Hastings2f936352014-08-05 14:04:04 +10007230static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007231os_getpgrp_impl(PyObject *module)
7232/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
Guido van Rossum04814471991-06-04 20:23:49 +00007233{
Guido van Rossumb6775db1994-08-01 11:34:53 +00007234#ifdef GETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007235 return PyLong_FromPid(getpgrp(0));
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007236#else /* GETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007237 return PyLong_FromPid(getpgrp());
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007238#endif /* GETPGRP_HAVE_ARG */
Guido van Rossum04814471991-06-04 20:23:49 +00007239}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007240#endif /* HAVE_GETPGRP */
Guido van Rossum04814471991-06-04 20:23:49 +00007241
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007242
Guido van Rossumb6775db1994-08-01 11:34:53 +00007243#ifdef HAVE_SETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007244/*[clinic input]
7245os.setpgrp
7246
7247Make the current process the leader of its process group.
7248[clinic start generated code]*/
7249
Larry Hastings2f936352014-08-05 14:04:04 +10007250static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007251os_setpgrp_impl(PyObject *module)
7252/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00007253{
Guido van Rossum64933891994-10-20 21:56:42 +00007254#ifdef SETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007255 if (setpgrp(0, 0) < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007256#else /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007257 if (setpgrp() < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007258#endif /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007259 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007260 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00007261}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007262#endif /* HAVE_SETPGRP */
7263
Guido van Rossumad0ee831995-03-01 10:34:45 +00007264#ifdef HAVE_GETPPID
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007265
7266#ifdef MS_WINDOWS
7267#include <tlhelp32.h>
7268
7269static PyObject*
7270win32_getppid()
7271{
7272 HANDLE snapshot;
7273 pid_t mypid;
7274 PyObject* result = NULL;
7275 BOOL have_record;
7276 PROCESSENTRY32 pe;
7277
7278 mypid = getpid(); /* This function never fails */
7279
7280 snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
7281 if (snapshot == INVALID_HANDLE_VALUE)
7282 return PyErr_SetFromWindowsErr(GetLastError());
7283
7284 pe.dwSize = sizeof(pe);
7285 have_record = Process32First(snapshot, &pe);
7286 while (have_record) {
7287 if (mypid == (pid_t)pe.th32ProcessID) {
7288 /* We could cache the ulong value in a static variable. */
7289 result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
7290 break;
7291 }
7292
7293 have_record = Process32Next(snapshot, &pe);
7294 }
7295
7296 /* If our loop exits and our pid was not found (result will be NULL)
7297 * then GetLastError will return ERROR_NO_MORE_FILES. This is an
7298 * error anyway, so let's raise it. */
7299 if (!result)
7300 result = PyErr_SetFromWindowsErr(GetLastError());
7301
7302 CloseHandle(snapshot);
7303
7304 return result;
7305}
7306#endif /*MS_WINDOWS*/
7307
Larry Hastings2f936352014-08-05 14:04:04 +10007308
7309/*[clinic input]
7310os.getppid
7311
7312Return the parent's process id.
7313
7314If the parent process has already exited, Windows machines will still
7315return its id; others systems will return the id of the 'init' process (1).
7316[clinic start generated code]*/
7317
Larry Hastings2f936352014-08-05 14:04:04 +10007318static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007319os_getppid_impl(PyObject *module)
7320/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00007321{
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007322#ifdef MS_WINDOWS
7323 return win32_getppid();
7324#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007325 return PyLong_FromPid(getppid());
Guido van Rossumad0ee831995-03-01 10:34:45 +00007326#endif
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007327}
7328#endif /* HAVE_GETPPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007329
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007330
Fred Drake12c6e2d1999-12-14 21:25:03 +00007331#ifdef HAVE_GETLOGIN
Larry Hastings2f936352014-08-05 14:04:04 +10007332/*[clinic input]
7333os.getlogin
7334
7335Return the actual login name.
7336[clinic start generated code]*/
7337
Larry Hastings2f936352014-08-05 14:04:04 +10007338static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007339os_getlogin_impl(PyObject *module)
7340/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
Fred Drake12c6e2d1999-12-14 21:25:03 +00007341{
Victor Stinner8c62be82010-05-06 00:08:46 +00007342 PyObject *result = NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007343#ifdef MS_WINDOWS
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007344 wchar_t user_name[UNLEN + 1];
Victor Stinner63941882011-09-29 00:42:28 +02007345 DWORD num_chars = Py_ARRAY_LENGTH(user_name);
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007346
7347 if (GetUserNameW(user_name, &num_chars)) {
7348 /* num_chars is the number of unicode chars plus null terminator */
7349 result = PyUnicode_FromWideChar(user_name, num_chars - 1);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007350 }
7351 else
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007352 result = PyErr_SetFromWindowsErr(GetLastError());
7353#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007354 char *name;
7355 int old_errno = errno;
Fred Drake12c6e2d1999-12-14 21:25:03 +00007356
Victor Stinner8c62be82010-05-06 00:08:46 +00007357 errno = 0;
7358 name = getlogin();
7359 if (name == NULL) {
7360 if (errno)
Victor Stinnere039ffe2010-08-15 09:33:08 +00007361 posix_error();
Fred Drake12c6e2d1999-12-14 21:25:03 +00007362 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007363 PyErr_SetString(PyExc_OSError, "unable to determine login name");
Victor Stinner8c62be82010-05-06 00:08:46 +00007364 }
7365 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007366 result = PyUnicode_DecodeFSDefault(name);
Victor Stinner8c62be82010-05-06 00:08:46 +00007367 errno = old_errno;
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007368#endif
Fred Drake12c6e2d1999-12-14 21:25:03 +00007369 return result;
7370}
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007371#endif /* HAVE_GETLOGIN */
Fred Drake12c6e2d1999-12-14 21:25:03 +00007372
Larry Hastings2f936352014-08-05 14:04:04 +10007373
Guido van Rossumad0ee831995-03-01 10:34:45 +00007374#ifdef HAVE_GETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007375/*[clinic input]
7376os.getuid
7377
7378Return the current process's user id.
7379[clinic start generated code]*/
7380
Larry Hastings2f936352014-08-05 14:04:04 +10007381static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007382os_getuid_impl(PyObject *module)
7383/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00007384{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007385 return _PyLong_FromUid(getuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00007386}
Larry Hastings2f936352014-08-05 14:04:04 +10007387#endif /* HAVE_GETUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00007388
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007389
Brian Curtineb24d742010-04-12 17:16:38 +00007390#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007391#define HAVE_KILL
7392#endif /* MS_WINDOWS */
7393
7394#ifdef HAVE_KILL
7395/*[clinic input]
7396os.kill
7397
7398 pid: pid_t
7399 signal: Py_ssize_t
7400 /
7401
7402Kill a process with a signal.
7403[clinic start generated code]*/
7404
Larry Hastings2f936352014-08-05 14:04:04 +10007405static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007406os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
7407/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007408{
Saiyang Gou7514f4f2020-02-12 23:47:42 -08007409 if (PySys_Audit("os.kill", "in", pid, signal) < 0) {
7410 return NULL;
7411 }
7412#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007413 if (kill(pid, (int)signal) == -1)
7414 return posix_error();
7415 Py_RETURN_NONE;
Larry Hastings2f936352014-08-05 14:04:04 +10007416#else /* !MS_WINDOWS */
Amaury Forgeot d'Arc0a589c92010-05-15 20:35:12 +00007417 PyObject *result;
Larry Hastings2f936352014-08-05 14:04:04 +10007418 DWORD sig = (DWORD)signal;
7419 DWORD err;
Victor Stinner8c62be82010-05-06 00:08:46 +00007420 HANDLE handle;
Brian Curtineb24d742010-04-12 17:16:38 +00007421
Victor Stinner8c62be82010-05-06 00:08:46 +00007422 /* Console processes which share a common console can be sent CTRL+C or
7423 CTRL+BREAK events, provided they handle said events. */
7424 if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007425 if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007426 err = GetLastError();
7427 PyErr_SetFromWindowsErr(err);
7428 }
7429 else
7430 Py_RETURN_NONE;
7431 }
Brian Curtineb24d742010-04-12 17:16:38 +00007432
Victor Stinner8c62be82010-05-06 00:08:46 +00007433 /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
7434 attempt to open and terminate the process. */
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007435 handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007436 if (handle == NULL) {
7437 err = GetLastError();
7438 return PyErr_SetFromWindowsErr(err);
7439 }
Brian Curtineb24d742010-04-12 17:16:38 +00007440
Victor Stinner8c62be82010-05-06 00:08:46 +00007441 if (TerminateProcess(handle, sig) == 0) {
7442 err = GetLastError();
7443 result = PyErr_SetFromWindowsErr(err);
7444 } else {
7445 Py_INCREF(Py_None);
7446 result = Py_None;
7447 }
Brian Curtineb24d742010-04-12 17:16:38 +00007448
Victor Stinner8c62be82010-05-06 00:08:46 +00007449 CloseHandle(handle);
7450 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10007451#endif /* !MS_WINDOWS */
Saiyang Gou7514f4f2020-02-12 23:47:42 -08007452}
Larry Hastings2f936352014-08-05 14:04:04 +10007453#endif /* HAVE_KILL */
7454
7455
7456#ifdef HAVE_KILLPG
7457/*[clinic input]
7458os.killpg
7459
7460 pgid: pid_t
7461 signal: int
7462 /
7463
7464Kill a process group with a signal.
7465[clinic start generated code]*/
7466
Larry Hastings2f936352014-08-05 14:04:04 +10007467static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007468os_killpg_impl(PyObject *module, pid_t pgid, int signal)
7469/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007470{
Saiyang Gou7514f4f2020-02-12 23:47:42 -08007471 if (PySys_Audit("os.killpg", "ii", pgid, signal) < 0) {
7472 return NULL;
7473 }
Larry Hastings2f936352014-08-05 14:04:04 +10007474 /* XXX some man pages make the `pgid` parameter an int, others
7475 a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
7476 take the same type. Moreover, pid_t is always at least as wide as
7477 int (else compilation of this module fails), which is safe. */
7478 if (killpg(pgid, signal) == -1)
7479 return posix_error();
7480 Py_RETURN_NONE;
7481}
7482#endif /* HAVE_KILLPG */
7483
Brian Curtineb24d742010-04-12 17:16:38 +00007484
Guido van Rossumc0125471996-06-28 18:55:32 +00007485#ifdef HAVE_PLOCK
Guido van Rossumc0125471996-06-28 18:55:32 +00007486#ifdef HAVE_SYS_LOCK_H
7487#include <sys/lock.h>
7488#endif
7489
Larry Hastings2f936352014-08-05 14:04:04 +10007490/*[clinic input]
7491os.plock
7492 op: int
7493 /
7494
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007495Lock program segments into memory.");
Larry Hastings2f936352014-08-05 14:04:04 +10007496[clinic start generated code]*/
7497
Larry Hastings2f936352014-08-05 14:04:04 +10007498static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007499os_plock_impl(PyObject *module, int op)
7500/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007501{
Victor Stinner8c62be82010-05-06 00:08:46 +00007502 if (plock(op) == -1)
7503 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007504 Py_RETURN_NONE;
Guido van Rossumc0125471996-06-28 18:55:32 +00007505}
Larry Hastings2f936352014-08-05 14:04:04 +10007506#endif /* HAVE_PLOCK */
7507
Guido van Rossumc0125471996-06-28 18:55:32 +00007508
Guido van Rossumb6775db1994-08-01 11:34:53 +00007509#ifdef HAVE_SETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007510/*[clinic input]
7511os.setuid
7512
7513 uid: uid_t
7514 /
7515
7516Set the current process's user id.
7517[clinic start generated code]*/
7518
Larry Hastings2f936352014-08-05 14:04:04 +10007519static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007520os_setuid_impl(PyObject *module, uid_t uid)
7521/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007522{
Victor Stinner8c62be82010-05-06 00:08:46 +00007523 if (setuid(uid) < 0)
7524 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007525 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007526}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007527#endif /* HAVE_SETUID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007528
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007529
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007530#ifdef HAVE_SETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10007531/*[clinic input]
7532os.seteuid
7533
7534 euid: uid_t
7535 /
7536
7537Set the current process's effective user id.
7538[clinic start generated code]*/
7539
Larry Hastings2f936352014-08-05 14:04:04 +10007540static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007541os_seteuid_impl(PyObject *module, uid_t euid)
7542/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007543{
7544 if (seteuid(euid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007545 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007546 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007547}
7548#endif /* HAVE_SETEUID */
7549
Larry Hastings2f936352014-08-05 14:04:04 +10007550
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007551#ifdef HAVE_SETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10007552/*[clinic input]
7553os.setegid
7554
7555 egid: gid_t
7556 /
7557
7558Set the current process's effective group id.
7559[clinic start generated code]*/
7560
Larry Hastings2f936352014-08-05 14:04:04 +10007561static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007562os_setegid_impl(PyObject *module, gid_t egid)
7563/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007564{
7565 if (setegid(egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007566 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007567 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007568}
7569#endif /* HAVE_SETEGID */
7570
Larry Hastings2f936352014-08-05 14:04:04 +10007571
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007572#ifdef HAVE_SETREUID
Larry Hastings2f936352014-08-05 14:04:04 +10007573/*[clinic input]
7574os.setreuid
7575
7576 ruid: uid_t
7577 euid: uid_t
7578 /
7579
7580Set the current process's real and effective user ids.
7581[clinic start generated code]*/
7582
Larry Hastings2f936352014-08-05 14:04:04 +10007583static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007584os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
7585/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007586{
Victor Stinner8c62be82010-05-06 00:08:46 +00007587 if (setreuid(ruid, euid) < 0) {
7588 return posix_error();
7589 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007590 Py_RETURN_NONE;
Victor Stinner8c62be82010-05-06 00:08:46 +00007591 }
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007592}
7593#endif /* HAVE_SETREUID */
7594
Larry Hastings2f936352014-08-05 14:04:04 +10007595
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007596#ifdef HAVE_SETREGID
Larry Hastings2f936352014-08-05 14:04:04 +10007597/*[clinic input]
7598os.setregid
7599
7600 rgid: gid_t
7601 egid: gid_t
7602 /
7603
7604Set the current process's real and effective group ids.
7605[clinic start generated code]*/
7606
Larry Hastings2f936352014-08-05 14:04:04 +10007607static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007608os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
7609/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007610{
7611 if (setregid(rgid, egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007612 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007613 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007614}
7615#endif /* HAVE_SETREGID */
7616
Larry Hastings2f936352014-08-05 14:04:04 +10007617
Guido van Rossumb6775db1994-08-01 11:34:53 +00007618#ifdef HAVE_SETGID
Larry Hastings2f936352014-08-05 14:04:04 +10007619/*[clinic input]
7620os.setgid
7621 gid: gid_t
7622 /
7623
7624Set the current process's group id.
7625[clinic start generated code]*/
7626
Larry Hastings2f936352014-08-05 14:04:04 +10007627static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007628os_setgid_impl(PyObject *module, gid_t gid)
7629/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007630{
Victor Stinner8c62be82010-05-06 00:08:46 +00007631 if (setgid(gid) < 0)
7632 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007633 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007634}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007635#endif /* HAVE_SETGID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007636
Larry Hastings2f936352014-08-05 14:04:04 +10007637
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007638#ifdef HAVE_SETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007639/*[clinic input]
7640os.setgroups
7641
7642 groups: object
7643 /
7644
7645Set the groups of the current process to list.
7646[clinic start generated code]*/
7647
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007648static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007649os_setgroups(PyObject *module, PyObject *groups)
7650/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007651{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007652 Py_ssize_t i, len;
Victor Stinner8c62be82010-05-06 00:08:46 +00007653 gid_t grouplist[MAX_GROUPS];
Tim Peters5aa91602002-01-30 05:46:57 +00007654
Victor Stinner8c62be82010-05-06 00:08:46 +00007655 if (!PySequence_Check(groups)) {
7656 PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
7657 return NULL;
7658 }
7659 len = PySequence_Size(groups);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007660 if (len < 0) {
7661 return NULL;
7662 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007663 if (len > MAX_GROUPS) {
7664 PyErr_SetString(PyExc_ValueError, "too many groups");
7665 return NULL;
7666 }
7667 for(i = 0; i < len; i++) {
7668 PyObject *elem;
7669 elem = PySequence_GetItem(groups, i);
7670 if (!elem)
7671 return NULL;
7672 if (!PyLong_Check(elem)) {
7673 PyErr_SetString(PyExc_TypeError,
7674 "groups must be integers");
7675 Py_DECREF(elem);
7676 return NULL;
7677 } else {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007678 if (!_Py_Gid_Converter(elem, &grouplist[i])) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007679 Py_DECREF(elem);
7680 return NULL;
7681 }
7682 }
7683 Py_DECREF(elem);
7684 }
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007685
Victor Stinner8c62be82010-05-06 00:08:46 +00007686 if (setgroups(len, grouplist) < 0)
7687 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007688 Py_RETURN_NONE;
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007689}
7690#endif /* HAVE_SETGROUPS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007691
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007692#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
7693static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +01007694wait_helper(pid_t pid, int status, struct rusage *ru)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007695{
Victor Stinner8c62be82010-05-06 00:08:46 +00007696 PyObject *result;
Eddie Elizondob3966632019-11-05 07:16:14 -08007697 PyObject *struct_rusage;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007698
Victor Stinner8c62be82010-05-06 00:08:46 +00007699 if (pid == -1)
7700 return posix_error();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007701
Zackery Spytz682107c2019-09-09 09:48:32 -06007702 // If wait succeeded but no child was ready to report status, ru will not
7703 // have been populated.
7704 if (pid == 0) {
7705 memset(ru, 0, sizeof(*ru));
7706 }
7707
Eddie Elizondob3966632019-11-05 07:16:14 -08007708 PyObject *m = PyImport_ImportModuleNoBlock("resource");
7709 if (m == NULL)
7710 return NULL;
7711 struct_rusage = PyObject_GetAttr(m, _posixstate_global->struct_rusage);
7712 Py_DECREF(m);
7713 if (struct_rusage == NULL)
7714 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007715
Victor Stinner8c62be82010-05-06 00:08:46 +00007716 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
7717 result = PyStructSequence_New((PyTypeObject*) struct_rusage);
Eddie Elizondoe4db1f02019-11-25 19:07:37 -08007718 Py_DECREF(struct_rusage);
Victor Stinner8c62be82010-05-06 00:08:46 +00007719 if (!result)
7720 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007721
7722#ifndef doubletime
7723#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
7724#endif
7725
Victor Stinner8c62be82010-05-06 00:08:46 +00007726 PyStructSequence_SET_ITEM(result, 0,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007727 PyFloat_FromDouble(doubletime(ru->ru_utime)));
Victor Stinner8c62be82010-05-06 00:08:46 +00007728 PyStructSequence_SET_ITEM(result, 1,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007729 PyFloat_FromDouble(doubletime(ru->ru_stime)));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007730#define SET_INT(result, index, value)\
Victor Stinner8c62be82010-05-06 00:08:46 +00007731 PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
7732 SET_INT(result, 2, ru->ru_maxrss);
7733 SET_INT(result, 3, ru->ru_ixrss);
7734 SET_INT(result, 4, ru->ru_idrss);
7735 SET_INT(result, 5, ru->ru_isrss);
7736 SET_INT(result, 6, ru->ru_minflt);
7737 SET_INT(result, 7, ru->ru_majflt);
7738 SET_INT(result, 8, ru->ru_nswap);
7739 SET_INT(result, 9, ru->ru_inblock);
7740 SET_INT(result, 10, ru->ru_oublock);
7741 SET_INT(result, 11, ru->ru_msgsnd);
7742 SET_INT(result, 12, ru->ru_msgrcv);
7743 SET_INT(result, 13, ru->ru_nsignals);
7744 SET_INT(result, 14, ru->ru_nvcsw);
7745 SET_INT(result, 15, ru->ru_nivcsw);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007746#undef SET_INT
7747
Victor Stinner8c62be82010-05-06 00:08:46 +00007748 if (PyErr_Occurred()) {
7749 Py_DECREF(result);
7750 return NULL;
7751 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007752
Victor Stinner8c62be82010-05-06 00:08:46 +00007753 return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007754}
7755#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
7756
Larry Hastings2f936352014-08-05 14:04:04 +10007757
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007758#ifdef HAVE_WAIT3
Larry Hastings2f936352014-08-05 14:04:04 +10007759/*[clinic input]
7760os.wait3
7761
7762 options: int
7763Wait for completion of a child process.
7764
7765Returns a tuple of information about the child process:
7766 (pid, status, rusage)
7767[clinic start generated code]*/
7768
Larry Hastings2f936352014-08-05 14:04:04 +10007769static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007770os_wait3_impl(PyObject *module, int options)
7771/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007772{
Victor Stinner8c62be82010-05-06 00:08:46 +00007773 pid_t pid;
Victor Stinner8c62be82010-05-06 00:08:46 +00007774 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007775 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007776 WAIT_TYPE status;
7777 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007778
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007779 do {
7780 Py_BEGIN_ALLOW_THREADS
7781 pid = wait3(&status, options, &ru);
7782 Py_END_ALLOW_THREADS
7783 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7784 if (pid < 0)
7785 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007786
Victor Stinner4195b5c2012-02-08 23:03:19 +01007787 return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007788}
7789#endif /* HAVE_WAIT3 */
7790
Larry Hastings2f936352014-08-05 14:04:04 +10007791
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007792#ifdef HAVE_WAIT4
Larry Hastings2f936352014-08-05 14:04:04 +10007793/*[clinic input]
7794
7795os.wait4
7796
7797 pid: pid_t
7798 options: int
7799
7800Wait for completion of a specific child process.
7801
7802Returns a tuple of information about the child process:
7803 (pid, status, rusage)
7804[clinic start generated code]*/
7805
Larry Hastings2f936352014-08-05 14:04:04 +10007806static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007807os_wait4_impl(PyObject *module, pid_t pid, int options)
7808/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007809{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007810 pid_t res;
Victor Stinner8c62be82010-05-06 00:08:46 +00007811 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007812 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007813 WAIT_TYPE status;
7814 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007815
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007816 do {
7817 Py_BEGIN_ALLOW_THREADS
7818 res = wait4(pid, &status, options, &ru);
7819 Py_END_ALLOW_THREADS
7820 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7821 if (res < 0)
7822 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007823
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007824 return wait_helper(res, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007825}
7826#endif /* HAVE_WAIT4 */
7827
Larry Hastings2f936352014-08-05 14:04:04 +10007828
Ross Lagerwall7807c352011-03-17 20:20:30 +02007829#if defined(HAVE_WAITID) && !defined(__APPLE__)
Larry Hastings2f936352014-08-05 14:04:04 +10007830/*[clinic input]
7831os.waitid
7832
7833 idtype: idtype_t
7834 Must be one of be P_PID, P_PGID or P_ALL.
7835 id: id_t
7836 The id to wait on.
7837 options: int
7838 Constructed from the ORing of one or more of WEXITED, WSTOPPED
7839 or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
7840 /
7841
7842Returns the result of waiting for a process or processes.
7843
7844Returns either waitid_result or None if WNOHANG is specified and there are
7845no children in a waitable state.
7846[clinic start generated code]*/
7847
Larry Hastings2f936352014-08-05 14:04:04 +10007848static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007849os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
7850/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007851{
7852 PyObject *result;
7853 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007854 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007855 siginfo_t si;
7856 si.si_pid = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007857
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007858 do {
7859 Py_BEGIN_ALLOW_THREADS
7860 res = waitid(idtype, id, &si, options);
7861 Py_END_ALLOW_THREADS
7862 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7863 if (res < 0)
7864 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007865
7866 if (si.si_pid == 0)
7867 Py_RETURN_NONE;
7868
Hai Shif707d942020-03-16 21:15:01 +08007869 PyObject *WaitidResultType = get_posix_state(module)->WaitidResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -08007870 result = PyStructSequence_New((PyTypeObject *)WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +02007871 if (!result)
7872 return NULL;
7873
7874 PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007875 PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
Ross Lagerwall7807c352011-03-17 20:20:30 +02007876 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
7877 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
7878 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
7879 if (PyErr_Occurred()) {
7880 Py_DECREF(result);
7881 return NULL;
7882 }
7883
7884 return result;
7885}
Larry Hastings2f936352014-08-05 14:04:04 +10007886#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
Ross Lagerwall7807c352011-03-17 20:20:30 +02007887
Larry Hastings2f936352014-08-05 14:04:04 +10007888
7889#if defined(HAVE_WAITPID)
7890/*[clinic input]
7891os.waitpid
7892 pid: pid_t
7893 options: int
7894 /
7895
7896Wait for completion of a given child process.
7897
7898Returns a tuple of information regarding the child process:
7899 (pid, status)
7900
7901The options argument is ignored on Windows.
7902[clinic start generated code]*/
7903
Larry Hastings2f936352014-08-05 14:04:04 +10007904static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007905os_waitpid_impl(PyObject *module, pid_t pid, int options)
7906/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007907{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007908 pid_t res;
7909 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007910 WAIT_TYPE status;
7911 WAIT_STATUS_INT(status) = 0;
Guido van Rossum54ecc3d1999-01-27 17:53:11 +00007912
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007913 do {
7914 Py_BEGIN_ALLOW_THREADS
7915 res = waitpid(pid, &status, options);
7916 Py_END_ALLOW_THREADS
7917 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7918 if (res < 0)
7919 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007920
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007921 return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
Guido van Rossum21803b81992-08-09 12:55:27 +00007922}
Tim Petersab034fa2002-02-01 11:27:43 +00007923#elif defined(HAVE_CWAIT)
Tim Petersab034fa2002-02-01 11:27:43 +00007924/* MS C has a variant of waitpid() that's usable for most purposes. */
Larry Hastings2f936352014-08-05 14:04:04 +10007925/*[clinic input]
7926os.waitpid
Benjamin Petersonca470632016-09-06 13:47:26 -07007927 pid: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +10007928 options: int
7929 /
7930
7931Wait for completion of a given process.
7932
7933Returns a tuple of information regarding the process:
7934 (pid, status << 8)
7935
7936The options argument is ignored on Windows.
7937[clinic start generated code]*/
7938
Larry Hastings2f936352014-08-05 14:04:04 +10007939static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -07007940os_waitpid_impl(PyObject *module, intptr_t pid, int options)
Victor Stinner581139c2016-09-06 15:54:20 -07007941/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007942{
7943 int status;
Benjamin Petersonca470632016-09-06 13:47:26 -07007944 intptr_t res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007945 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007946
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007947 do {
7948 Py_BEGIN_ALLOW_THREADS
Steve Dower11f43262016-11-19 18:33:39 -08007949 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007950 res = _cwait(&status, pid, options);
Steve Dower11f43262016-11-19 18:33:39 -08007951 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007952 Py_END_ALLOW_THREADS
7953 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinnerd3ffd322015-09-15 10:11:03 +02007954 if (res < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007955 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007956
Victor Stinner8c62be82010-05-06 00:08:46 +00007957 /* shift the status left a byte so this is more like the POSIX waitpid */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007958 return Py_BuildValue(_Py_PARSE_INTPTR "i", res, status << 8);
Tim Petersab034fa2002-02-01 11:27:43 +00007959}
Larry Hastings2f936352014-08-05 14:04:04 +10007960#endif
7961
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007962
Guido van Rossumad0ee831995-03-01 10:34:45 +00007963#ifdef HAVE_WAIT
Larry Hastings2f936352014-08-05 14:04:04 +10007964/*[clinic input]
7965os.wait
7966
7967Wait for completion of a child process.
7968
7969Returns a tuple of information about the child process:
7970 (pid, status)
7971[clinic start generated code]*/
7972
Larry Hastings2f936352014-08-05 14:04:04 +10007973static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007974os_wait_impl(PyObject *module)
7975/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
Guido van Rossum21803b81992-08-09 12:55:27 +00007976{
Victor Stinner8c62be82010-05-06 00:08:46 +00007977 pid_t pid;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007978 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007979 WAIT_TYPE status;
7980 WAIT_STATUS_INT(status) = 0;
Neal Norwitze241ce82003-02-17 18:17:05 +00007981
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007982 do {
7983 Py_BEGIN_ALLOW_THREADS
7984 pid = wait(&status);
7985 Py_END_ALLOW_THREADS
7986 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7987 if (pid < 0)
7988 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007989
Victor Stinner8c62be82010-05-06 00:08:46 +00007990 return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
Guido van Rossum85e3b011991-06-03 12:42:10 +00007991}
Larry Hastings2f936352014-08-05 14:04:04 +10007992#endif /* HAVE_WAIT */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007993
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -08007994#if defined(__linux__) && defined(__NR_pidfd_open)
7995/*[clinic input]
7996os.pidfd_open
7997 pid: pid_t
7998 flags: unsigned_int = 0
7999
8000Return a file descriptor referring to the process *pid*.
8001
8002The descriptor can be used to perform process management without races and
8003signals.
8004[clinic start generated code]*/
8005
8006static PyObject *
8007os_pidfd_open_impl(PyObject *module, pid_t pid, unsigned int flags)
8008/*[clinic end generated code: output=5c7252698947dc41 input=c3fd99ce947ccfef]*/
8009{
8010 int fd = syscall(__NR_pidfd_open, pid, flags);
8011 if (fd < 0) {
8012 return posix_error();
8013 }
8014 return PyLong_FromLong(fd);
8015}
8016#endif
8017
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008018
Larry Hastings9cf065c2012-06-22 16:30:09 -07008019#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008020/*[clinic input]
8021os.readlink
8022
8023 path: path_t
8024 *
8025 dir_fd: dir_fd(requires='readlinkat') = None
8026
8027Return a string representing the path to which the symbolic link points.
8028
8029If dir_fd is not None, it should be a file descriptor open to a directory,
8030and path should be relative; path will then be relative to that directory.
8031
8032dir_fd may not be implemented on your platform. If it is unavailable,
8033using it will raise a NotImplementedError.
8034[clinic start generated code]*/
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008035
Barry Warsaw53699e91996-12-10 23:23:01 +00008036static PyObject *
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008037os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
8038/*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008039{
Berker Peksage0b5b202018-08-15 13:03:41 +03008040#if defined(HAVE_READLINK)
Christian Heimes3cb091e2016-09-23 20:24:28 +02008041 char buffer[MAXPATHLEN+1];
Larry Hastings9cf065c2012-06-22 16:30:09 -07008042 ssize_t length;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008043
8044 Py_BEGIN_ALLOW_THREADS
8045#ifdef HAVE_READLINKAT
8046 if (dir_fd != DEFAULT_DIR_FD)
8047 length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
8048 else
8049#endif
8050 length = readlink(path->narrow, buffer, MAXPATHLEN);
8051 Py_END_ALLOW_THREADS
8052
8053 if (length < 0) {
8054 return path_error(path);
8055 }
8056 buffer[length] = '\0';
8057
8058 if (PyUnicode_Check(path->object))
8059 return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
8060 else
8061 return PyBytes_FromStringAndSize(buffer, length);
Berker Peksage0b5b202018-08-15 13:03:41 +03008062#elif defined(MS_WINDOWS)
8063 DWORD n_bytes_returned;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008064 DWORD io_result = 0;
Berker Peksage0b5b202018-08-15 13:03:41 +03008065 HANDLE reparse_point_handle;
Berker Peksage0b5b202018-08-15 13:03:41 +03008066 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
8067 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Steve Dower993ac922019-09-03 12:50:51 -07008068 PyObject *result = NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00008069
Larry Hastings2f936352014-08-05 14:04:04 +10008070 /* First get a handle to the reparse point */
8071 Py_BEGIN_ALLOW_THREADS
8072 reparse_point_handle = CreateFileW(
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008073 path->wide,
Larry Hastings2f936352014-08-05 14:04:04 +10008074 0,
8075 0,
8076 0,
8077 OPEN_EXISTING,
8078 FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
8079 0);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008080 if (reparse_point_handle != INVALID_HANDLE_VALUE) {
8081 /* New call DeviceIoControl to read the reparse point */
8082 io_result = DeviceIoControl(
8083 reparse_point_handle,
8084 FSCTL_GET_REPARSE_POINT,
8085 0, 0, /* in buffer */
8086 target_buffer, sizeof(target_buffer),
8087 &n_bytes_returned,
8088 0 /* we're not using OVERLAPPED_IO */
8089 );
8090 CloseHandle(reparse_point_handle);
Berker Peksage0b5b202018-08-15 13:03:41 +03008091 }
Larry Hastings2f936352014-08-05 14:04:04 +10008092 Py_END_ALLOW_THREADS
8093
Berker Peksage0b5b202018-08-15 13:03:41 +03008094 if (io_result == 0) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008095 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03008096 }
Larry Hastings2f936352014-08-05 14:04:04 +10008097
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008098 wchar_t *name = NULL;
8099 Py_ssize_t nameLen = 0;
8100 if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
Larry Hastings2f936352014-08-05 14:04:04 +10008101 {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008102 name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
8103 rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
8104 nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
Larry Hastings2f936352014-08-05 14:04:04 +10008105 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008106 else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
8107 {
8108 name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
8109 rdb->MountPointReparseBuffer.SubstituteNameOffset);
8110 nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
8111 }
8112 else
8113 {
8114 PyErr_SetString(PyExc_ValueError, "not a symbolic link");
8115 }
8116 if (name) {
8117 if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
8118 /* Our buffer is mutable, so this is okay */
8119 name[1] = L'\\';
8120 }
8121 result = PyUnicode_FromWideChar(name, nameLen);
Steve Dower993ac922019-09-03 12:50:51 -07008122 if (result && path->narrow) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008123 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
8124 }
Berker Peksage0b5b202018-08-15 13:03:41 +03008125 }
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008126 return result;
Berker Peksage0b5b202018-08-15 13:03:41 +03008127#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008128}
Berker Peksage0b5b202018-08-15 13:03:41 +03008129#endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008130
Larry Hastings9cf065c2012-06-22 16:30:09 -07008131#ifdef HAVE_SYMLINK
Larry Hastings9cf065c2012-06-22 16:30:09 -07008132
8133#if defined(MS_WINDOWS)
8134
Steve Dower6921e732018-03-05 14:26:08 -08008135/* Remove the last portion of the path - return 0 on success */
8136static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008137_dirnameW(WCHAR *path)
8138{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008139 WCHAR *ptr;
Steve Dower6921e732018-03-05 14:26:08 -08008140 size_t length = wcsnlen_s(path, MAX_PATH);
8141 if (length == MAX_PATH) {
8142 return -1;
8143 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008144
8145 /* walk the path from the end until a backslash is encountered */
Steve Dower6921e732018-03-05 14:26:08 -08008146 for(ptr = path + length; ptr != path; ptr--) {
8147 if (*ptr == L'\\' || *ptr == L'/') {
Jason R. Coombs3a092862013-05-27 23:21:28 -04008148 break;
Steve Dower6921e732018-03-05 14:26:08 -08008149 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008150 }
8151 *ptr = 0;
Steve Dower6921e732018-03-05 14:26:08 -08008152 return 0;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008153}
8154
Victor Stinner31b3b922013-06-05 01:49:17 +02008155/* Is this path absolute? */
8156static int
8157_is_absW(const WCHAR *path)
8158{
Steve Dower6921e732018-03-05 14:26:08 -08008159 return path[0] == L'\\' || path[0] == L'/' ||
8160 (path[0] && path[1] == L':');
Jason R. Coombs3a092862013-05-27 23:21:28 -04008161}
8162
Steve Dower6921e732018-03-05 14:26:08 -08008163/* join root and rest with a backslash - return 0 on success */
8164static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008165_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
8166{
Victor Stinner31b3b922013-06-05 01:49:17 +02008167 if (_is_absW(rest)) {
Steve Dower6921e732018-03-05 14:26:08 -08008168 return wcscpy_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008169 }
8170
Steve Dower6921e732018-03-05 14:26:08 -08008171 if (wcscpy_s(dest_path, MAX_PATH, root)) {
8172 return -1;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008173 }
Steve Dower6921e732018-03-05 14:26:08 -08008174
8175 if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
8176 return -1;
8177 }
8178
8179 return wcscat_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008180}
8181
Victor Stinner31b3b922013-06-05 01:49:17 +02008182/* Return True if the path at src relative to dest is a directory */
8183static int
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03008184_check_dirW(LPCWSTR src, LPCWSTR dest)
Jason R. Coombs3a092862013-05-27 23:21:28 -04008185{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008186 WIN32_FILE_ATTRIBUTE_DATA src_info;
8187 WCHAR dest_parent[MAX_PATH];
8188 WCHAR src_resolved[MAX_PATH] = L"";
8189
8190 /* dest_parent = os.path.dirname(dest) */
Steve Dower6921e732018-03-05 14:26:08 -08008191 if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
8192 _dirnameW(dest_parent)) {
8193 return 0;
8194 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008195 /* src_resolved = os.path.join(dest_parent, src) */
Steve Dower6921e732018-03-05 14:26:08 -08008196 if (_joinW(src_resolved, dest_parent, src)) {
8197 return 0;
8198 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008199 return (
8200 GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
8201 && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
8202 );
8203}
Larry Hastings9cf065c2012-06-22 16:30:09 -07008204#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008205
Larry Hastings2f936352014-08-05 14:04:04 +10008206
8207/*[clinic input]
8208os.symlink
8209 src: path_t
8210 dst: path_t
8211 target_is_directory: bool = False
8212 *
8213 dir_fd: dir_fd(requires='symlinkat')=None
8214
8215# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
8216
8217Create a symbolic link pointing to src named dst.
8218
8219target_is_directory is required on Windows if the target is to be
8220 interpreted as a directory. (On Windows, symlink requires
8221 Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
8222 target_is_directory is ignored on non-Windows platforms.
8223
8224If dir_fd is not None, it should be a file descriptor open to a directory,
8225 and path should be relative; path will then be relative to that directory.
8226dir_fd may not be implemented on your platform.
8227 If it is unavailable, using it will raise a NotImplementedError.
8228
8229[clinic start generated code]*/
8230
Larry Hastings2f936352014-08-05 14:04:04 +10008231static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008232os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
Larry Hastings89964c42015-04-14 18:07:59 -04008233 int target_is_directory, int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008234/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008235{
Larry Hastings9cf065c2012-06-22 16:30:09 -07008236#ifdef MS_WINDOWS
8237 DWORD result;
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008238 DWORD flags = 0;
8239
8240 /* Assumed true, set to false if detected to not be available. */
8241 static int windows_has_symlink_unprivileged_flag = TRUE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008242#else
8243 int result;
8244#endif
8245
Saiyang Gou7514f4f2020-02-12 23:47:42 -08008246 if (PySys_Audit("os.symlink", "OOi", src->object, dst->object,
8247 dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
8248 return NULL;
8249 }
8250
Larry Hastings9cf065c2012-06-22 16:30:09 -07008251#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008252
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008253 if (windows_has_symlink_unprivileged_flag) {
8254 /* Allow non-admin symlinks if system allows it. */
8255 flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
8256 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008257
Larry Hastings9cf065c2012-06-22 16:30:09 -07008258 Py_BEGIN_ALLOW_THREADS
Steve Dower6921e732018-03-05 14:26:08 -08008259 _Py_BEGIN_SUPPRESS_IPH
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008260 /* if src is a directory, ensure flags==1 (target_is_directory bit) */
8261 if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
8262 flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
8263 }
8264
8265 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
Steve Dower6921e732018-03-05 14:26:08 -08008266 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07008267 Py_END_ALLOW_THREADS
8268
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008269 if (windows_has_symlink_unprivileged_flag && !result &&
8270 ERROR_INVALID_PARAMETER == GetLastError()) {
8271
8272 Py_BEGIN_ALLOW_THREADS
8273 _Py_BEGIN_SUPPRESS_IPH
8274 /* This error might be caused by
8275 SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
8276 Try again, and update windows_has_symlink_unprivileged_flag if we
8277 are successful this time.
8278
8279 NOTE: There is a risk of a race condition here if there are other
8280 conditions than the flag causing ERROR_INVALID_PARAMETER, and
8281 another process (or thread) changes that condition in between our
8282 calls to CreateSymbolicLink.
8283 */
8284 flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
8285 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
8286 _Py_END_SUPPRESS_IPH
8287 Py_END_ALLOW_THREADS
8288
8289 if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
8290 windows_has_symlink_unprivileged_flag = FALSE;
8291 }
8292 }
8293
Larry Hastings2f936352014-08-05 14:04:04 +10008294 if (!result)
8295 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008296
8297#else
8298
Steve Dower6921e732018-03-05 14:26:08 -08008299 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
8300 PyErr_SetString(PyExc_ValueError,
8301 "symlink: src and dst must be the same type");
8302 return NULL;
8303 }
8304
Larry Hastings9cf065c2012-06-22 16:30:09 -07008305 Py_BEGIN_ALLOW_THREADS
8306#if HAVE_SYMLINKAT
8307 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10008308 result = symlinkat(src->narrow, dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008309 else
8310#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008311 result = symlink(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008312 Py_END_ALLOW_THREADS
8313
Larry Hastings2f936352014-08-05 14:04:04 +10008314 if (result)
8315 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008316#endif
8317
Larry Hastings2f936352014-08-05 14:04:04 +10008318 Py_RETURN_NONE;
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008319}
8320#endif /* HAVE_SYMLINK */
8321
Larry Hastings9cf065c2012-06-22 16:30:09 -07008322
Brian Curtind40e6f72010-07-08 21:39:08 +00008323
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008324
Larry Hastings605a62d2012-06-24 04:33:36 -07008325static PyStructSequence_Field times_result_fields[] = {
8326 {"user", "user time"},
8327 {"system", "system time"},
8328 {"children_user", "user time of children"},
8329 {"children_system", "system time of children"},
8330 {"elapsed", "elapsed time since an arbitrary point in the past"},
8331 {NULL}
8332};
8333
8334PyDoc_STRVAR(times_result__doc__,
8335"times_result: Result from os.times().\n\n\
8336This object may be accessed either as a tuple of\n\
8337 (user, system, children_user, children_system, elapsed),\n\
8338or via the attributes user, system, children_user, children_system,\n\
8339and elapsed.\n\
8340\n\
8341See os.times for more information.");
8342
8343static PyStructSequence_Desc times_result_desc = {
8344 "times_result", /* name */
8345 times_result__doc__, /* doc */
8346 times_result_fields,
8347 5
8348};
8349
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008350#ifdef MS_WINDOWS
8351#define HAVE_TIMES /* mandatory, for the method table */
8352#endif
Larry Hastings605a62d2012-06-24 04:33:36 -07008353
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008354#ifdef HAVE_TIMES
Larry Hastings605a62d2012-06-24 04:33:36 -07008355
8356static PyObject *
8357build_times_result(double user, double system,
8358 double children_user, double children_system,
8359 double elapsed)
8360{
Eddie Elizondob3966632019-11-05 07:16:14 -08008361 PyObject *TimesResultType = _posixstate_global->TimesResultType;
8362 PyObject *value = PyStructSequence_New((PyTypeObject *)TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07008363 if (value == NULL)
8364 return NULL;
8365
8366#define SET(i, field) \
8367 { \
8368 PyObject *o = PyFloat_FromDouble(field); \
8369 if (!o) { \
8370 Py_DECREF(value); \
8371 return NULL; \
8372 } \
8373 PyStructSequence_SET_ITEM(value, i, o); \
8374 } \
8375
8376 SET(0, user);
8377 SET(1, system);
8378 SET(2, children_user);
8379 SET(3, children_system);
8380 SET(4, elapsed);
8381
8382#undef SET
8383
8384 return value;
8385}
8386
Larry Hastings605a62d2012-06-24 04:33:36 -07008387
Larry Hastings2f936352014-08-05 14:04:04 +10008388#ifndef MS_WINDOWS
8389#define NEED_TICKS_PER_SECOND
8390static long ticks_per_second = -1;
8391#endif /* MS_WINDOWS */
8392
8393/*[clinic input]
8394os.times
8395
8396Return a collection containing process timing information.
8397
8398The object returned behaves like a named tuple with these fields:
8399 (utime, stime, cutime, cstime, elapsed_time)
8400All fields are floating point numbers.
8401[clinic start generated code]*/
8402
Larry Hastings2f936352014-08-05 14:04:04 +10008403static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008404os_times_impl(PyObject *module)
8405/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008406#ifdef MS_WINDOWS
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008407{
Victor Stinner8c62be82010-05-06 00:08:46 +00008408 FILETIME create, exit, kernel, user;
8409 HANDLE hProc;
8410 hProc = GetCurrentProcess();
8411 GetProcessTimes(hProc, &create, &exit, &kernel, &user);
8412 /* The fields of a FILETIME structure are the hi and lo part
8413 of a 64-bit value expressed in 100 nanosecond units.
8414 1e7 is one second in such units; 1e-7 the inverse.
8415 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
8416 */
Larry Hastings605a62d2012-06-24 04:33:36 -07008417 return build_times_result(
Victor Stinner8c62be82010-05-06 00:08:46 +00008418 (double)(user.dwHighDateTime*429.4967296 +
8419 user.dwLowDateTime*1e-7),
8420 (double)(kernel.dwHighDateTime*429.4967296 +
8421 kernel.dwLowDateTime*1e-7),
8422 (double)0,
8423 (double)0,
8424 (double)0);
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008425}
Larry Hastings2f936352014-08-05 14:04:04 +10008426#else /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008427{
Larry Hastings2f936352014-08-05 14:04:04 +10008428
8429
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008430 struct tms t;
8431 clock_t c;
8432 errno = 0;
8433 c = times(&t);
8434 if (c == (clock_t) -1)
8435 return posix_error();
8436 return build_times_result(
8437 (double)t.tms_utime / ticks_per_second,
8438 (double)t.tms_stime / ticks_per_second,
8439 (double)t.tms_cutime / ticks_per_second,
8440 (double)t.tms_cstime / ticks_per_second,
8441 (double)c / ticks_per_second);
8442}
Larry Hastings2f936352014-08-05 14:04:04 +10008443#endif /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008444#endif /* HAVE_TIMES */
8445
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008446
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008447#ifdef HAVE_GETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008448/*[clinic input]
8449os.getsid
8450
8451 pid: pid_t
8452 /
8453
8454Call the system call getsid(pid) and return the result.
8455[clinic start generated code]*/
8456
Larry Hastings2f936352014-08-05 14:04:04 +10008457static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008458os_getsid_impl(PyObject *module, pid_t pid)
8459/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008460{
Victor Stinner8c62be82010-05-06 00:08:46 +00008461 int sid;
Victor Stinner8c62be82010-05-06 00:08:46 +00008462 sid = getsid(pid);
8463 if (sid < 0)
8464 return posix_error();
8465 return PyLong_FromLong((long)sid);
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008466}
8467#endif /* HAVE_GETSID */
8468
8469
Guido van Rossumb6775db1994-08-01 11:34:53 +00008470#ifdef HAVE_SETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008471/*[clinic input]
8472os.setsid
8473
8474Call the system call setsid().
8475[clinic start generated code]*/
8476
Larry Hastings2f936352014-08-05 14:04:04 +10008477static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008478os_setsid_impl(PyObject *module)
8479/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00008480{
Victor Stinner8c62be82010-05-06 00:08:46 +00008481 if (setsid() < 0)
8482 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008483 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008484}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008485#endif /* HAVE_SETSID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008486
Larry Hastings2f936352014-08-05 14:04:04 +10008487
Guido van Rossumb6775db1994-08-01 11:34:53 +00008488#ifdef HAVE_SETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10008489/*[clinic input]
8490os.setpgid
8491
8492 pid: pid_t
8493 pgrp: pid_t
8494 /
8495
8496Call the system call setpgid(pid, pgrp).
8497[clinic start generated code]*/
8498
Larry Hastings2f936352014-08-05 14:04:04 +10008499static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008500os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
8501/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008502{
Victor Stinner8c62be82010-05-06 00:08:46 +00008503 if (setpgid(pid, pgrp) < 0)
8504 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008505 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008506}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008507#endif /* HAVE_SETPGID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008508
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008509
Guido van Rossumb6775db1994-08-01 11:34:53 +00008510#ifdef HAVE_TCGETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008511/*[clinic input]
8512os.tcgetpgrp
8513
8514 fd: int
8515 /
8516
8517Return the process group associated with the terminal specified by fd.
8518[clinic start generated code]*/
8519
Larry Hastings2f936352014-08-05 14:04:04 +10008520static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008521os_tcgetpgrp_impl(PyObject *module, int fd)
8522/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008523{
8524 pid_t pgid = tcgetpgrp(fd);
Victor Stinner8c62be82010-05-06 00:08:46 +00008525 if (pgid < 0)
8526 return posix_error();
8527 return PyLong_FromPid(pgid);
Guido van Rossum7066dd71992-09-17 17:54:56 +00008528}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008529#endif /* HAVE_TCGETPGRP */
Guido van Rossum7066dd71992-09-17 17:54:56 +00008530
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008531
Guido van Rossumb6775db1994-08-01 11:34:53 +00008532#ifdef HAVE_TCSETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008533/*[clinic input]
8534os.tcsetpgrp
8535
8536 fd: int
8537 pgid: pid_t
8538 /
8539
8540Set the process group associated with the terminal specified by fd.
8541[clinic start generated code]*/
8542
Larry Hastings2f936352014-08-05 14:04:04 +10008543static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008544os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
8545/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008546{
Victor Stinner8c62be82010-05-06 00:08:46 +00008547 if (tcsetpgrp(fd, pgid) < 0)
8548 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008549 Py_RETURN_NONE;
Guido van Rossum7066dd71992-09-17 17:54:56 +00008550}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008551#endif /* HAVE_TCSETPGRP */
Guido van Rossum22db57e1992-04-05 14:25:30 +00008552
Guido van Rossum687dd131993-05-17 08:34:16 +00008553/* Functions acting on file descriptors */
8554
Victor Stinnerdaf45552013-08-28 00:53:59 +02008555#ifdef O_CLOEXEC
8556extern int _Py_open_cloexec_works;
8557#endif
8558
Larry Hastings2f936352014-08-05 14:04:04 +10008559
8560/*[clinic input]
8561os.open -> int
8562 path: path_t
8563 flags: int
8564 mode: int = 0o777
8565 *
8566 dir_fd: dir_fd(requires='openat') = None
8567
8568# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
8569
8570Open a file for low level IO. Returns a file descriptor (integer).
8571
8572If dir_fd is not None, it should be a file descriptor open to a directory,
8573 and path should be relative; path will then be relative to that directory.
8574dir_fd may not be implemented on your platform.
8575 If it is unavailable, using it will raise a NotImplementedError.
8576[clinic start generated code]*/
8577
Larry Hastings2f936352014-08-05 14:04:04 +10008578static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008579os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
8580/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008581{
8582 int fd;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008583 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008584
Victor Stinnerdaf45552013-08-28 00:53:59 +02008585#ifdef O_CLOEXEC
8586 int *atomic_flag_works = &_Py_open_cloexec_works;
8587#elif !defined(MS_WINDOWS)
8588 int *atomic_flag_works = NULL;
8589#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +00008590
Victor Stinnerdaf45552013-08-28 00:53:59 +02008591#ifdef MS_WINDOWS
8592 flags |= O_NOINHERIT;
8593#elif defined(O_CLOEXEC)
8594 flags |= O_CLOEXEC;
8595#endif
8596
Steve Dowerb82e17e2019-05-23 08:45:22 -07008597 if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
8598 return -1;
8599 }
8600
Steve Dower8fc89802015-04-12 00:26:27 -04008601 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008602 do {
8603 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008604#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07008605 fd = _wopen(path->wide, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008606#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07008607#ifdef HAVE_OPENAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008608 if (dir_fd != DEFAULT_DIR_FD)
8609 fd = openat(dir_fd, path->narrow, flags, mode);
8610 else
Steve Dower6230aaf2016-09-09 09:03:15 -07008611#endif /* HAVE_OPENAT */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008612 fd = open(path->narrow, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008613#endif /* !MS_WINDOWS */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008614 Py_END_ALLOW_THREADS
8615 } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04008616 _Py_END_SUPPRESS_IPH
Guido van Rossum687dd131993-05-17 08:34:16 +00008617
Victor Stinnerd3ffd322015-09-15 10:11:03 +02008618 if (fd < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008619 if (!async_err)
8620 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Larry Hastings2f936352014-08-05 14:04:04 +10008621 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008622 }
8623
Victor Stinnerdaf45552013-08-28 00:53:59 +02008624#ifndef MS_WINDOWS
8625 if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
8626 close(fd);
Larry Hastings2f936352014-08-05 14:04:04 +10008627 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008628 }
8629#endif
8630
Larry Hastings2f936352014-08-05 14:04:04 +10008631 return fd;
8632}
8633
8634
8635/*[clinic input]
8636os.close
8637
8638 fd: int
8639
8640Close a file descriptor.
8641[clinic start generated code]*/
8642
Barry Warsaw53699e91996-12-10 23:23:01 +00008643static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008644os_close_impl(PyObject *module, int fd)
8645/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00008646{
Larry Hastings2f936352014-08-05 14:04:04 +10008647 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008648 /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
8649 * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
8650 * for more details.
8651 */
Victor Stinner8c62be82010-05-06 00:08:46 +00008652 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008653 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008654 res = close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04008655 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008656 Py_END_ALLOW_THREADS
8657 if (res < 0)
8658 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008659 Py_RETURN_NONE;
Guido van Rossum687dd131993-05-17 08:34:16 +00008660}
8661
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008662
Jakub Kulíke20134f2019-09-11 17:11:57 +02008663#ifdef HAVE_FDWALK
8664static int
8665_fdwalk_close_func(void *lohi, int fd)
8666{
8667 int lo = ((int *)lohi)[0];
8668 int hi = ((int *)lohi)[1];
8669
8670 if (fd >= hi)
8671 return 1;
8672 else if (fd >= lo)
8673 close(fd);
8674 return 0;
8675}
8676#endif /* HAVE_FDWALK */
8677
Larry Hastings2f936352014-08-05 14:04:04 +10008678/*[clinic input]
8679os.closerange
8680
8681 fd_low: int
8682 fd_high: int
8683 /
8684
8685Closes all file descriptors in [fd_low, fd_high), ignoring errors.
8686[clinic start generated code]*/
8687
Larry Hastings2f936352014-08-05 14:04:04 +10008688static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008689os_closerange_impl(PyObject *module, int fd_low, int fd_high)
8690/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008691{
Jakub Kulíke20134f2019-09-11 17:11:57 +02008692#ifdef HAVE_FDWALK
8693 int lohi[2];
8694#else
Larry Hastings2f936352014-08-05 14:04:04 +10008695 int i;
Jakub Kulíke20134f2019-09-11 17:11:57 +02008696#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00008697 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008698 _Py_BEGIN_SUPPRESS_IPH
Jakub Kulíke20134f2019-09-11 17:11:57 +02008699#ifdef HAVE_FDWALK
8700 lohi[0] = Py_MAX(fd_low, 0);
8701 lohi[1] = fd_high;
8702 fdwalk(_fdwalk_close_func, lohi);
8703#else
Benjamin Peterson207116b2016-09-08 11:28:06 -07008704 for (i = Py_MAX(fd_low, 0); i < fd_high; i++)
Steve Dower940f33a2016-09-08 11:21:54 -07008705 close(i);
Jakub Kulíke20134f2019-09-11 17:11:57 +02008706#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008707 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008708 Py_END_ALLOW_THREADS
8709 Py_RETURN_NONE;
Christian Heimesfdab48e2008-01-20 09:06:41 +00008710}
8711
8712
Larry Hastings2f936352014-08-05 14:04:04 +10008713/*[clinic input]
8714os.dup -> int
8715
8716 fd: int
8717 /
8718
8719Return a duplicate of a file descriptor.
8720[clinic start generated code]*/
8721
Larry Hastings2f936352014-08-05 14:04:04 +10008722static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008723os_dup_impl(PyObject *module, int fd)
8724/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008725{
8726 return _Py_dup(fd);
Guido van Rossum687dd131993-05-17 08:34:16 +00008727}
8728
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008729
Larry Hastings2f936352014-08-05 14:04:04 +10008730/*[clinic input]
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008731os.dup2 -> int
Larry Hastings2f936352014-08-05 14:04:04 +10008732 fd: int
8733 fd2: int
8734 inheritable: bool=True
8735
8736Duplicate file descriptor.
8737[clinic start generated code]*/
8738
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008739static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008740os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008741/*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008742{
Stéphane Wirtel3d86e482018-01-30 07:04:36 +01008743 int res = 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008744#if defined(HAVE_DUP3) && \
8745 !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
8746 /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
Alexey Izbyshevb3caf382018-02-20 10:25:46 +03008747 static int dup3_works = -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008748#endif
8749
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008750 if (fd < 0 || fd2 < 0) {
8751 posix_error();
8752 return -1;
8753 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008754
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008755 /* dup2() can fail with EINTR if the target FD is already open, because it
8756 * then has to be closed. See os_close_impl() for why we don't handle EINTR
8757 * upon close(), and therefore below.
8758 */
Victor Stinnerdaf45552013-08-28 00:53:59 +02008759#ifdef MS_WINDOWS
8760 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008761 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008762 res = dup2(fd, fd2);
Steve Dower8fc89802015-04-12 00:26:27 -04008763 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02008764 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008765 if (res < 0) {
8766 posix_error();
8767 return -1;
8768 }
8769 res = fd2; // msvcrt dup2 returns 0 on success.
Victor Stinnerdaf45552013-08-28 00:53:59 +02008770
8771 /* Character files like console cannot be make non-inheritable */
8772 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8773 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008774 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008775 }
8776
8777#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
8778 Py_BEGIN_ALLOW_THREADS
8779 if (!inheritable)
8780 res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
8781 else
8782 res = dup2(fd, fd2);
8783 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008784 if (res < 0) {
8785 posix_error();
8786 return -1;
8787 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008788
8789#else
8790
8791#ifdef HAVE_DUP3
8792 if (!inheritable && dup3_works != 0) {
8793 Py_BEGIN_ALLOW_THREADS
8794 res = dup3(fd, fd2, O_CLOEXEC);
8795 Py_END_ALLOW_THREADS
8796 if (res < 0) {
8797 if (dup3_works == -1)
8798 dup3_works = (errno != ENOSYS);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008799 if (dup3_works) {
8800 posix_error();
8801 return -1;
8802 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008803 }
8804 }
8805
8806 if (inheritable || dup3_works == 0)
8807 {
8808#endif
8809 Py_BEGIN_ALLOW_THREADS
8810 res = dup2(fd, fd2);
8811 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008812 if (res < 0) {
8813 posix_error();
8814 return -1;
8815 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008816
8817 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8818 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008819 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008820 }
8821#ifdef HAVE_DUP3
8822 }
8823#endif
8824
8825#endif
8826
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008827 return res;
Guido van Rossum687dd131993-05-17 08:34:16 +00008828}
8829
Larry Hastings2f936352014-08-05 14:04:04 +10008830
Ross Lagerwall7807c352011-03-17 20:20:30 +02008831#ifdef HAVE_LOCKF
Larry Hastings2f936352014-08-05 14:04:04 +10008832/*[clinic input]
8833os.lockf
8834
8835 fd: int
8836 An open file descriptor.
8837 command: int
8838 One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
8839 length: Py_off_t
8840 The number of bytes to lock, starting at the current position.
8841 /
8842
8843Apply, test or remove a POSIX lock on an open file descriptor.
8844
8845[clinic start generated code]*/
8846
Larry Hastings2f936352014-08-05 14:04:04 +10008847static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008848os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
8849/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008850{
8851 int res;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008852
Saiyang Gou7514f4f2020-02-12 23:47:42 -08008853 if (PySys_Audit("os.lockf", "iiL", fd, command, length) < 0) {
8854 return NULL;
8855 }
8856
Ross Lagerwall7807c352011-03-17 20:20:30 +02008857 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008858 res = lockf(fd, command, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008859 Py_END_ALLOW_THREADS
8860
8861 if (res < 0)
8862 return posix_error();
8863
8864 Py_RETURN_NONE;
8865}
Larry Hastings2f936352014-08-05 14:04:04 +10008866#endif /* HAVE_LOCKF */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008867
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008868
Larry Hastings2f936352014-08-05 14:04:04 +10008869/*[clinic input]
8870os.lseek -> Py_off_t
8871
8872 fd: int
8873 position: Py_off_t
8874 how: int
8875 /
8876
8877Set the position of a file descriptor. Return the new position.
8878
8879Return the new cursor position in number of bytes
8880relative to the beginning of the file.
8881[clinic start generated code]*/
8882
Larry Hastings2f936352014-08-05 14:04:04 +10008883static Py_off_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008884os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
8885/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008886{
8887 Py_off_t result;
8888
Guido van Rossum687dd131993-05-17 08:34:16 +00008889#ifdef SEEK_SET
Victor Stinner8c62be82010-05-06 00:08:46 +00008890 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
8891 switch (how) {
Larry Hastings2f936352014-08-05 14:04:04 +10008892 case 0: how = SEEK_SET; break;
8893 case 1: how = SEEK_CUR; break;
8894 case 2: how = SEEK_END; break;
Victor Stinner8c62be82010-05-06 00:08:46 +00008895 }
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00008896#endif /* SEEK_END */
Guido van Rossum94f6f721999-01-06 18:42:14 +00008897
Victor Stinner8c62be82010-05-06 00:08:46 +00008898 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008899 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner14b9b112013-06-25 00:37:25 +02008900#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10008901 result = _lseeki64(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008902#else
Larry Hastings2f936352014-08-05 14:04:04 +10008903 result = lseek(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008904#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008905 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008906 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008907 if (result < 0)
8908 posix_error();
Guido van Rossum94f6f721999-01-06 18:42:14 +00008909
Larry Hastings2f936352014-08-05 14:04:04 +10008910 return result;
Guido van Rossum687dd131993-05-17 08:34:16 +00008911}
8912
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008913
Larry Hastings2f936352014-08-05 14:04:04 +10008914/*[clinic input]
8915os.read
8916 fd: int
8917 length: Py_ssize_t
8918 /
8919
8920Read from a file descriptor. Returns a bytes object.
8921[clinic start generated code]*/
8922
Larry Hastings2f936352014-08-05 14:04:04 +10008923static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008924os_read_impl(PyObject *module, int fd, Py_ssize_t length)
8925/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008926{
Victor Stinner8c62be82010-05-06 00:08:46 +00008927 Py_ssize_t n;
8928 PyObject *buffer;
Larry Hastings2f936352014-08-05 14:04:04 +10008929
8930 if (length < 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008931 errno = EINVAL;
8932 return posix_error();
8933 }
Larry Hastings2f936352014-08-05 14:04:04 +10008934
Victor Stinner9a0d7a72018-11-22 15:03:40 +01008935 length = Py_MIN(length, _PY_READ_MAX);
Larry Hastings2f936352014-08-05 14:04:04 +10008936
8937 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Victor Stinner8c62be82010-05-06 00:08:46 +00008938 if (buffer == NULL)
8939 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008940
Victor Stinner66aab0c2015-03-19 22:53:20 +01008941 n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
8942 if (n == -1) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008943 Py_DECREF(buffer);
Victor Stinner66aab0c2015-03-19 22:53:20 +01008944 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00008945 }
Larry Hastings2f936352014-08-05 14:04:04 +10008946
8947 if (n != length)
Victor Stinner8c62be82010-05-06 00:08:46 +00008948 _PyBytes_Resize(&buffer, n);
Larry Hastings2f936352014-08-05 14:04:04 +10008949
Victor Stinner8c62be82010-05-06 00:08:46 +00008950 return buffer;
Guido van Rossum687dd131993-05-17 08:34:16 +00008951}
8952
Ross Lagerwall7807c352011-03-17 20:20:30 +02008953#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008954 || defined(__APPLE__))) \
8955 || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
8956 || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
8957static int
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008958iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008959{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008960 Py_ssize_t i, j;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008961
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008962 *iov = PyMem_New(struct iovec, cnt);
8963 if (*iov == NULL) {
8964 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008965 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008966 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008967
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008968 *buf = PyMem_New(Py_buffer, cnt);
8969 if (*buf == NULL) {
8970 PyMem_Del(*iov);
8971 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008972 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008973 }
8974
8975 for (i = 0; i < cnt; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008976 PyObject *item = PySequence_GetItem(seq, i);
8977 if (item == NULL)
8978 goto fail;
8979 if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
8980 Py_DECREF(item);
8981 goto fail;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008982 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008983 Py_DECREF(item);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008984 (*iov)[i].iov_base = (*buf)[i].buf;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008985 (*iov)[i].iov_len = (*buf)[i].len;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008986 }
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008987 return 0;
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008988
8989fail:
8990 PyMem_Del(*iov);
8991 for (j = 0; j < i; j++) {
8992 PyBuffer_Release(&(*buf)[j]);
8993 }
8994 PyMem_Del(*buf);
Victor Stinner57ddf782014-01-08 15:21:28 +01008995 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008996}
8997
8998static void
8999iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
9000{
9001 int i;
9002 PyMem_Del(iov);
9003 for (i = 0; i < cnt; i++) {
9004 PyBuffer_Release(&buf[i]);
9005 }
9006 PyMem_Del(buf);
9007}
9008#endif
9009
Larry Hastings2f936352014-08-05 14:04:04 +10009010
Ross Lagerwall7807c352011-03-17 20:20:30 +02009011#ifdef HAVE_READV
Larry Hastings2f936352014-08-05 14:04:04 +10009012/*[clinic input]
9013os.readv -> Py_ssize_t
9014
9015 fd: int
9016 buffers: object
9017 /
9018
9019Read from a file descriptor fd into an iterable of buffers.
9020
9021The buffers should be mutable buffers accepting bytes.
9022readv will transfer data into each buffer until it is full
9023and then move on to the next buffer in the sequence to hold
9024the rest of the data.
9025
9026readv returns the total number of bytes read,
9027which may be less than the total capacity of all the buffers.
9028[clinic start generated code]*/
9029
Larry Hastings2f936352014-08-05 14:04:04 +10009030static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009031os_readv_impl(PyObject *module, int fd, PyObject *buffers)
9032/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009033{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009034 Py_ssize_t cnt, n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009035 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009036 struct iovec *iov;
9037 Py_buffer *buf;
9038
Larry Hastings2f936352014-08-05 14:04:04 +10009039 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009040 PyErr_SetString(PyExc_TypeError,
9041 "readv() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009042 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009043 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02009044
Larry Hastings2f936352014-08-05 14:04:04 +10009045 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009046 if (cnt < 0)
9047 return -1;
Larry Hastings2f936352014-08-05 14:04:04 +10009048
9049 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
9050 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009051
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009052 do {
9053 Py_BEGIN_ALLOW_THREADS
9054 n = readv(fd, iov, cnt);
9055 Py_END_ALLOW_THREADS
9056 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009057
9058 iov_cleanup(iov, buf, cnt);
Larry Hastings2f936352014-08-05 14:04:04 +10009059 if (n < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009060 if (!async_err)
9061 posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10009062 return -1;
9063 }
Victor Stinner57ddf782014-01-08 15:21:28 +01009064
Larry Hastings2f936352014-08-05 14:04:04 +10009065 return n;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009066}
Larry Hastings2f936352014-08-05 14:04:04 +10009067#endif /* HAVE_READV */
9068
Ross Lagerwall7807c352011-03-17 20:20:30 +02009069
9070#ifdef HAVE_PREAD
Larry Hastings2f936352014-08-05 14:04:04 +10009071/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10009072os.pread
9073
9074 fd: int
Dong-hee Naad7736f2019-09-25 14:47:04 +09009075 length: Py_ssize_t
Larry Hastings2f936352014-08-05 14:04:04 +10009076 offset: Py_off_t
9077 /
9078
9079Read a number of bytes from a file descriptor starting at a particular offset.
9080
9081Read length bytes from file descriptor fd, starting at offset bytes from
9082the beginning of the file. The file offset remains unchanged.
9083[clinic start generated code]*/
9084
Larry Hastings2f936352014-08-05 14:04:04 +10009085static PyObject *
Dong-hee Naad7736f2019-09-25 14:47:04 +09009086os_pread_impl(PyObject *module, int fd, Py_ssize_t length, Py_off_t offset)
9087/*[clinic end generated code: output=3f875c1eef82e32f input=85cb4a5589627144]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009088{
Ross Lagerwall7807c352011-03-17 20:20:30 +02009089 Py_ssize_t n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009090 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009091 PyObject *buffer;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009092
Larry Hastings2f936352014-08-05 14:04:04 +10009093 if (length < 0) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009094 errno = EINVAL;
9095 return posix_error();
9096 }
Larry Hastings2f936352014-08-05 14:04:04 +10009097 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02009098 if (buffer == NULL)
9099 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009100
9101 do {
9102 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009103 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009104 n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009105 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009106 Py_END_ALLOW_THREADS
9107 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9108
Ross Lagerwall7807c352011-03-17 20:20:30 +02009109 if (n < 0) {
9110 Py_DECREF(buffer);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009111 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009112 }
Larry Hastings2f936352014-08-05 14:04:04 +10009113 if (n != length)
Ross Lagerwall7807c352011-03-17 20:20:30 +02009114 _PyBytes_Resize(&buffer, n);
9115 return buffer;
9116}
Larry Hastings2f936352014-08-05 14:04:04 +10009117#endif /* HAVE_PREAD */
Ross Lagerwall7807c352011-03-17 20:20:30 +02009118
Pablo Galindo4defba32018-01-27 16:16:37 +00009119#if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
9120/*[clinic input]
9121os.preadv -> Py_ssize_t
9122
9123 fd: int
9124 buffers: object
9125 offset: Py_off_t
9126 flags: int = 0
9127 /
9128
9129Reads from a file descriptor into a number of mutable bytes-like objects.
9130
9131Combines the functionality of readv() and pread(). As readv(), it will
9132transfer data into each buffer until it is full and then move on to the next
9133buffer in the sequence to hold the rest of the data. Its fourth argument,
9134specifies the file offset at which the input operation is to be performed. It
9135will return the total number of bytes read (which can be less than the total
9136capacity of all the objects).
9137
9138The flags argument contains a bitwise OR of zero or more of the following flags:
9139
9140- RWF_HIPRI
9141- RWF_NOWAIT
9142
9143Using non-zero flags requires Linux 4.6 or newer.
9144[clinic start generated code]*/
9145
9146static Py_ssize_t
9147os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9148 int flags)
9149/*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
9150{
9151 Py_ssize_t cnt, n;
9152 int async_err = 0;
9153 struct iovec *iov;
9154 Py_buffer *buf;
9155
9156 if (!PySequence_Check(buffers)) {
9157 PyErr_SetString(PyExc_TypeError,
9158 "preadv2() arg 2 must be a sequence");
9159 return -1;
9160 }
9161
9162 cnt = PySequence_Size(buffers);
9163 if (cnt < 0) {
9164 return -1;
9165 }
9166
9167#ifndef HAVE_PREADV2
9168 if(flags != 0) {
9169 argument_unavailable_error("preadv2", "flags");
9170 return -1;
9171 }
9172#endif
9173
9174 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
9175 return -1;
9176 }
9177#ifdef HAVE_PREADV2
9178 do {
9179 Py_BEGIN_ALLOW_THREADS
9180 _Py_BEGIN_SUPPRESS_IPH
9181 n = preadv2(fd, iov, cnt, offset, flags);
9182 _Py_END_SUPPRESS_IPH
9183 Py_END_ALLOW_THREADS
9184 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9185#else
9186 do {
9187 Py_BEGIN_ALLOW_THREADS
9188 _Py_BEGIN_SUPPRESS_IPH
9189 n = preadv(fd, iov, cnt, offset);
9190 _Py_END_SUPPRESS_IPH
9191 Py_END_ALLOW_THREADS
9192 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9193#endif
9194
9195 iov_cleanup(iov, buf, cnt);
9196 if (n < 0) {
9197 if (!async_err) {
9198 posix_error();
9199 }
9200 return -1;
9201 }
9202
9203 return n;
9204}
9205#endif /* HAVE_PREADV */
9206
Larry Hastings2f936352014-08-05 14:04:04 +10009207
9208/*[clinic input]
9209os.write -> Py_ssize_t
9210
9211 fd: int
9212 data: Py_buffer
9213 /
9214
9215Write a bytes object to a file descriptor.
9216[clinic start generated code]*/
9217
Larry Hastings2f936352014-08-05 14:04:04 +10009218static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009219os_write_impl(PyObject *module, int fd, Py_buffer *data)
9220/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009221{
Victor Stinner66aab0c2015-03-19 22:53:20 +01009222 return _Py_write(fd, data->buf, data->len);
Ross Lagerwall7807c352011-03-17 20:20:30 +02009223}
9224
9225#ifdef HAVE_SENDFILE
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009226PyDoc_STRVAR(posix_sendfile__doc__,
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009227"sendfile(out_fd, in_fd, offset, count) -> byteswritten\n\
9228sendfile(out_fd, in_fd, offset, count[, headers][, trailers], flags=0)\n\
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009229 -> byteswritten\n\
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009230Copy count bytes from file descriptor in_fd to file descriptor out_fd.");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009231
Larry Hastings2f936352014-08-05 14:04:04 +10009232/* AC 3.5: don't bother converting, has optional group*/
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009233static PyObject *
9234posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict)
9235{
9236 int in, out;
9237 Py_ssize_t ret;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009238 int async_err = 0;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009239 off_t offset;
9240
9241#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
9242#ifndef __APPLE__
9243 Py_ssize_t len;
9244#endif
9245 PyObject *headers = NULL, *trailers = NULL;
9246 Py_buffer *hbuf, *tbuf;
9247 off_t sbytes;
9248 struct sf_hdtr sf;
9249 int flags = 0;
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009250 static char *keywords[] = {"out_fd", "in_fd",
Benjamin Petersond8a43b42011-02-26 21:35:16 +00009251 "offset", "count",
9252 "headers", "trailers", "flags", NULL};
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009253
Victor Stinner6ce0dbf2013-07-07 16:32:36 +02009254 sf.headers = NULL;
9255 sf.trailers = NULL;
9256
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009257#ifdef __APPLE__
9258 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&O&|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10009259 keywords, &out, &in, Py_off_t_converter, &offset, Py_off_t_converter, &sbytes,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009260#else
9261 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&n|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10009262 keywords, &out, &in, Py_off_t_converter, &offset, &len,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009263#endif
9264 &headers, &trailers, &flags))
9265 return NULL;
9266 if (headers != NULL) {
9267 if (!PySequence_Check(headers)) {
9268 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009269 "sendfile() headers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009270 return NULL;
9271 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009272 Py_ssize_t i = PySequence_Size(headers);
9273 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009274 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009275 if (i > INT_MAX) {
9276 PyErr_SetString(PyExc_OverflowError,
9277 "sendfile() header is too large");
9278 return NULL;
9279 }
9280 if (i > 0) {
9281 sf.hdr_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009282 if (iov_setup(&(sf.headers), &hbuf,
9283 headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009284 return NULL;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009285#ifdef __APPLE__
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009286 for (i = 0; i < sf.hdr_cnt; i++) {
9287 Py_ssize_t blen = sf.headers[i].iov_len;
9288# define OFF_T_MAX 0x7fffffffffffffff
9289 if (sbytes >= OFF_T_MAX - blen) {
9290 PyErr_SetString(PyExc_OverflowError,
9291 "sendfile() header is too large");
9292 return NULL;
9293 }
9294 sbytes += blen;
9295 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009296#endif
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009297 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009298 }
9299 }
9300 if (trailers != NULL) {
9301 if (!PySequence_Check(trailers)) {
9302 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009303 "sendfile() trailers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009304 return NULL;
9305 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009306 Py_ssize_t i = PySequence_Size(trailers);
9307 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009308 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009309 if (i > INT_MAX) {
9310 PyErr_SetString(PyExc_OverflowError,
9311 "sendfile() trailer is too large");
9312 return NULL;
9313 }
9314 if (i > 0) {
9315 sf.trl_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009316 if (iov_setup(&(sf.trailers), &tbuf,
9317 trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009318 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009319 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009320 }
9321 }
9322
Steve Dower8fc89802015-04-12 00:26:27 -04009323 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009324 do {
9325 Py_BEGIN_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009326#ifdef __APPLE__
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009327 ret = sendfile(in, out, offset, &sbytes, &sf, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009328#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009329 ret = sendfile(in, out, offset, len, &sf, &sbytes, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009330#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009331 Py_END_ALLOW_THREADS
9332 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04009333 _Py_END_SUPPRESS_IPH
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009334
9335 if (sf.headers != NULL)
9336 iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
9337 if (sf.trailers != NULL)
9338 iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
9339
9340 if (ret < 0) {
9341 if ((errno == EAGAIN) || (errno == EBUSY)) {
9342 if (sbytes != 0) {
9343 // some data has been sent
9344 goto done;
9345 }
9346 else {
9347 // no data has been sent; upper application is supposed
9348 // to retry on EAGAIN or EBUSY
9349 return posix_error();
9350 }
9351 }
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009352 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009353 }
9354 goto done;
9355
9356done:
9357 #if !defined(HAVE_LARGEFILE_SUPPORT)
9358 return Py_BuildValue("l", sbytes);
9359 #else
9360 return Py_BuildValue("L", sbytes);
9361 #endif
9362
9363#else
9364 Py_ssize_t count;
9365 PyObject *offobj;
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009366 static char *keywords[] = {"out_fd", "in_fd",
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009367 "offset", "count", NULL};
9368 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiOn:sendfile",
9369 keywords, &out, &in, &offobj, &count))
9370 return NULL;
Benjamin Peterson840ef8f2016-09-07 14:45:10 -07009371#ifdef __linux__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009372 if (offobj == Py_None) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009373 do {
9374 Py_BEGIN_ALLOW_THREADS
9375 ret = sendfile(out, in, NULL, count);
9376 Py_END_ALLOW_THREADS
9377 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009378 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009379 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodola'ff1a7352011-04-19 09:47:16 +02009380 return Py_BuildValue("n", ret);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009381 }
9382#endif
Larry Hastings2f936352014-08-05 14:04:04 +10009383 if (!Py_off_t_converter(offobj, &offset))
Antoine Pitroudcc20b82011-02-26 13:38:35 +00009384 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009385
9386 do {
9387 Py_BEGIN_ALLOW_THREADS
9388 ret = sendfile(out, in, &offset, count);
9389 Py_END_ALLOW_THREADS
9390 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009391 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009392 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009393 return Py_BuildValue("n", ret);
9394#endif
9395}
Larry Hastings2f936352014-08-05 14:04:04 +10009396#endif /* HAVE_SENDFILE */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009397
Larry Hastings2f936352014-08-05 14:04:04 +10009398
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009399#if defined(__APPLE__)
9400/*[clinic input]
9401os._fcopyfile
9402
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009403 in_fd: int
9404 out_fd: int
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009405 flags: int
9406 /
9407
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009408Efficiently copy content or metadata of 2 regular file descriptors (macOS).
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009409[clinic start generated code]*/
9410
9411static PyObject *
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009412os__fcopyfile_impl(PyObject *module, int in_fd, int out_fd, int flags)
9413/*[clinic end generated code: output=c9d1a35a992e401b input=1e34638a86948795]*/
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009414{
9415 int ret;
9416
9417 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009418 ret = fcopyfile(in_fd, out_fd, NULL, flags);
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009419 Py_END_ALLOW_THREADS
9420 if (ret < 0)
9421 return posix_error();
9422 Py_RETURN_NONE;
9423}
9424#endif
9425
9426
Larry Hastings2f936352014-08-05 14:04:04 +10009427/*[clinic input]
9428os.fstat
9429
9430 fd : int
9431
9432Perform a stat system call on the given file descriptor.
9433
9434Like stat(), but for an open file descriptor.
9435Equivalent to os.stat(fd).
9436[clinic start generated code]*/
9437
Larry Hastings2f936352014-08-05 14:04:04 +10009438static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009439os_fstat_impl(PyObject *module, int fd)
9440/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009441{
Victor Stinner8c62be82010-05-06 00:08:46 +00009442 STRUCT_STAT st;
9443 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009444 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009445
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009446 do {
9447 Py_BEGIN_ALLOW_THREADS
9448 res = FSTAT(fd, &st);
9449 Py_END_ALLOW_THREADS
9450 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner8c62be82010-05-06 00:08:46 +00009451 if (res != 0) {
Martin v. Löwis14694662006-02-03 12:54:16 +00009452#ifdef MS_WINDOWS
Victor Stinnerb024e842012-10-31 22:24:06 +01009453 return PyErr_SetFromWindowsErr(0);
Martin v. Löwis14694662006-02-03 12:54:16 +00009454#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009455 return (!async_err) ? posix_error() : NULL;
Martin v. Löwis14694662006-02-03 12:54:16 +00009456#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00009457 }
Tim Peters5aa91602002-01-30 05:46:57 +00009458
Victor Stinner4195b5c2012-02-08 23:03:19 +01009459 return _pystat_fromstructstat(&st);
Guido van Rossum687dd131993-05-17 08:34:16 +00009460}
9461
Larry Hastings2f936352014-08-05 14:04:04 +10009462
9463/*[clinic input]
9464os.isatty -> bool
9465 fd: int
9466 /
9467
9468Return True if the fd is connected to a terminal.
9469
9470Return True if the file descriptor is an open file descriptor
9471connected to the slave end of a terminal.
9472[clinic start generated code]*/
9473
Larry Hastings2f936352014-08-05 14:04:04 +10009474static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009475os_isatty_impl(PyObject *module, int fd)
9476/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009477{
Steve Dower8fc89802015-04-12 00:26:27 -04009478 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -04009479 _Py_BEGIN_SUPPRESS_IPH
9480 return_value = isatty(fd);
9481 _Py_END_SUPPRESS_IPH
9482 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +10009483}
9484
9485
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009486#ifdef HAVE_PIPE
Larry Hastings2f936352014-08-05 14:04:04 +10009487/*[clinic input]
9488os.pipe
9489
9490Create a pipe.
9491
9492Returns a tuple of two file descriptors:
9493 (read_fd, write_fd)
9494[clinic start generated code]*/
9495
Larry Hastings2f936352014-08-05 14:04:04 +10009496static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009497os_pipe_impl(PyObject *module)
9498/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00009499{
Victor Stinner8c62be82010-05-06 00:08:46 +00009500 int fds[2];
Victor Stinnerdaf45552013-08-28 00:53:59 +02009501#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00009502 HANDLE read, write;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009503 SECURITY_ATTRIBUTES attr;
Victor Stinner8c62be82010-05-06 00:08:46 +00009504 BOOL ok;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009505#else
9506 int res;
9507#endif
9508
9509#ifdef MS_WINDOWS
9510 attr.nLength = sizeof(attr);
9511 attr.lpSecurityDescriptor = NULL;
9512 attr.bInheritHandle = FALSE;
9513
9514 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08009515 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009516 ok = CreatePipe(&read, &write, &attr, 0);
9517 if (ok) {
Benjamin Petersonca470632016-09-06 13:47:26 -07009518 fds[0] = _open_osfhandle((intptr_t)read, _O_RDONLY);
9519 fds[1] = _open_osfhandle((intptr_t)write, _O_WRONLY);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009520 if (fds[0] == -1 || fds[1] == -1) {
9521 CloseHandle(read);
9522 CloseHandle(write);
9523 ok = 0;
9524 }
9525 }
Steve Dowerc3630612016-11-19 18:41:16 -08009526 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009527 Py_END_ALLOW_THREADS
9528
Victor Stinner8c62be82010-05-06 00:08:46 +00009529 if (!ok)
Victor Stinnerb024e842012-10-31 22:24:06 +01009530 return PyErr_SetFromWindowsErr(0);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009531#else
9532
9533#ifdef HAVE_PIPE2
9534 Py_BEGIN_ALLOW_THREADS
9535 res = pipe2(fds, O_CLOEXEC);
9536 Py_END_ALLOW_THREADS
9537
9538 if (res != 0 && errno == ENOSYS)
9539 {
9540#endif
9541 Py_BEGIN_ALLOW_THREADS
9542 res = pipe(fds);
9543 Py_END_ALLOW_THREADS
9544
9545 if (res == 0) {
9546 if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
9547 close(fds[0]);
9548 close(fds[1]);
9549 return NULL;
9550 }
9551 if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
9552 close(fds[0]);
9553 close(fds[1]);
9554 return NULL;
9555 }
9556 }
9557#ifdef HAVE_PIPE2
9558 }
9559#endif
9560
9561 if (res != 0)
9562 return PyErr_SetFromErrno(PyExc_OSError);
9563#endif /* !MS_WINDOWS */
9564 return Py_BuildValue("(ii)", fds[0], fds[1]);
Guido van Rossum687dd131993-05-17 08:34:16 +00009565}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009566#endif /* HAVE_PIPE */
9567
Larry Hastings2f936352014-08-05 14:04:04 +10009568
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009569#ifdef HAVE_PIPE2
Larry Hastings2f936352014-08-05 14:04:04 +10009570/*[clinic input]
9571os.pipe2
9572
9573 flags: int
9574 /
9575
9576Create a pipe with flags set atomically.
9577
9578Returns a tuple of two file descriptors:
9579 (read_fd, write_fd)
9580
9581flags can be constructed by ORing together one or more of these values:
9582O_NONBLOCK, O_CLOEXEC.
9583[clinic start generated code]*/
9584
Larry Hastings2f936352014-08-05 14:04:04 +10009585static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009586os_pipe2_impl(PyObject *module, int flags)
9587/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009588{
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009589 int fds[2];
9590 int res;
9591
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009592 res = pipe2(fds, flags);
9593 if (res != 0)
9594 return posix_error();
9595 return Py_BuildValue("(ii)", fds[0], fds[1]);
9596}
9597#endif /* HAVE_PIPE2 */
9598
Larry Hastings2f936352014-08-05 14:04:04 +10009599
Ross Lagerwall7807c352011-03-17 20:20:30 +02009600#ifdef HAVE_WRITEV
Larry Hastings2f936352014-08-05 14:04:04 +10009601/*[clinic input]
9602os.writev -> Py_ssize_t
9603 fd: int
9604 buffers: object
9605 /
9606
9607Iterate over buffers, and write the contents of each to a file descriptor.
9608
9609Returns the total number of bytes written.
9610buffers must be a sequence of bytes-like objects.
9611[clinic start generated code]*/
9612
Larry Hastings2f936352014-08-05 14:04:04 +10009613static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009614os_writev_impl(PyObject *module, int fd, PyObject *buffers)
9615/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009616{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009617 Py_ssize_t cnt;
Larry Hastings2f936352014-08-05 14:04:04 +10009618 Py_ssize_t result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009619 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009620 struct iovec *iov;
9621 Py_buffer *buf;
Larry Hastings2f936352014-08-05 14:04:04 +10009622
9623 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009624 PyErr_SetString(PyExc_TypeError,
9625 "writev() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009626 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009627 }
Larry Hastings2f936352014-08-05 14:04:04 +10009628 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009629 if (cnt < 0)
9630 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009631
Larry Hastings2f936352014-08-05 14:04:04 +10009632 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9633 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009634 }
9635
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009636 do {
9637 Py_BEGIN_ALLOW_THREADS
9638 result = writev(fd, iov, cnt);
9639 Py_END_ALLOW_THREADS
9640 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009641
9642 iov_cleanup(iov, buf, cnt);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009643 if (result < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009644 posix_error();
Victor Stinner57ddf782014-01-08 15:21:28 +01009645
Georg Brandl306336b2012-06-24 12:55:33 +02009646 return result;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009647}
Larry Hastings2f936352014-08-05 14:04:04 +10009648#endif /* HAVE_WRITEV */
9649
9650
9651#ifdef HAVE_PWRITE
9652/*[clinic input]
9653os.pwrite -> Py_ssize_t
9654
9655 fd: int
9656 buffer: Py_buffer
9657 offset: Py_off_t
9658 /
9659
9660Write bytes to a file descriptor starting at a particular offset.
9661
9662Write buffer to fd, starting at offset bytes from the beginning of
9663the file. Returns the number of bytes writte. Does not change the
9664current file offset.
9665[clinic start generated code]*/
9666
Larry Hastings2f936352014-08-05 14:04:04 +10009667static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009668os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
9669/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009670{
9671 Py_ssize_t size;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009672 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009673
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009674 do {
9675 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009676 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009677 size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009678 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009679 Py_END_ALLOW_THREADS
9680 } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +10009681
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009682 if (size < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009683 posix_error();
9684 return size;
9685}
9686#endif /* HAVE_PWRITE */
9687
Pablo Galindo4defba32018-01-27 16:16:37 +00009688#if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
9689/*[clinic input]
9690os.pwritev -> Py_ssize_t
9691
9692 fd: int
9693 buffers: object
9694 offset: Py_off_t
9695 flags: int = 0
9696 /
9697
9698Writes the contents of bytes-like objects to a file descriptor at a given offset.
9699
9700Combines the functionality of writev() and pwrite(). All buffers must be a sequence
9701of bytes-like objects. Buffers are processed in array order. Entire contents of first
9702buffer is written before proceeding to second, and so on. The operating system may
9703set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
9704This function writes the contents of each object to the file descriptor and returns
9705the total number of bytes written.
9706
9707The flags argument contains a bitwise OR of zero or more of the following flags:
9708
9709- RWF_DSYNC
9710- RWF_SYNC
9711
9712Using non-zero flags requires Linux 4.7 or newer.
9713[clinic start generated code]*/
9714
9715static Py_ssize_t
9716os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9717 int flags)
9718/*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=803dc5ddbf0cfd3b]*/
9719{
9720 Py_ssize_t cnt;
9721 Py_ssize_t result;
9722 int async_err = 0;
9723 struct iovec *iov;
9724 Py_buffer *buf;
9725
9726 if (!PySequence_Check(buffers)) {
9727 PyErr_SetString(PyExc_TypeError,
9728 "pwritev() arg 2 must be a sequence");
9729 return -1;
9730 }
9731
9732 cnt = PySequence_Size(buffers);
9733 if (cnt < 0) {
9734 return -1;
9735 }
9736
9737#ifndef HAVE_PWRITEV2
9738 if(flags != 0) {
9739 argument_unavailable_error("pwritev2", "flags");
9740 return -1;
9741 }
9742#endif
9743
9744 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9745 return -1;
9746 }
9747#ifdef HAVE_PWRITEV2
9748 do {
9749 Py_BEGIN_ALLOW_THREADS
9750 _Py_BEGIN_SUPPRESS_IPH
9751 result = pwritev2(fd, iov, cnt, offset, flags);
9752 _Py_END_SUPPRESS_IPH
9753 Py_END_ALLOW_THREADS
9754 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9755#else
9756 do {
9757 Py_BEGIN_ALLOW_THREADS
9758 _Py_BEGIN_SUPPRESS_IPH
9759 result = pwritev(fd, iov, cnt, offset);
9760 _Py_END_SUPPRESS_IPH
9761 Py_END_ALLOW_THREADS
9762 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9763#endif
9764
9765 iov_cleanup(iov, buf, cnt);
9766 if (result < 0) {
9767 if (!async_err) {
9768 posix_error();
9769 }
9770 return -1;
9771 }
9772
9773 return result;
9774}
9775#endif /* HAVE_PWRITEV */
9776
Pablo Galindoaac4d032019-05-31 19:39:47 +01009777#ifdef HAVE_COPY_FILE_RANGE
9778/*[clinic input]
9779
9780os.copy_file_range
9781 src: int
9782 Source file descriptor.
9783 dst: int
9784 Destination file descriptor.
9785 count: Py_ssize_t
9786 Number of bytes to copy.
9787 offset_src: object = None
9788 Starting offset in src.
9789 offset_dst: object = None
9790 Starting offset in dst.
9791
9792Copy count bytes from one file descriptor to another.
9793
9794If offset_src is None, then src is read from the current position;
9795respectively for offset_dst.
9796[clinic start generated code]*/
9797
9798static PyObject *
9799os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
9800 PyObject *offset_src, PyObject *offset_dst)
9801/*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
9802{
9803 off_t offset_src_val, offset_dst_val;
9804 off_t *p_offset_src = NULL;
9805 off_t *p_offset_dst = NULL;
9806 Py_ssize_t ret;
9807 int async_err = 0;
9808 /* The flags argument is provided to allow
9809 * for future extensions and currently must be to 0. */
9810 int flags = 0;
Pablo Galindo4defba32018-01-27 16:16:37 +00009811
9812
Pablo Galindoaac4d032019-05-31 19:39:47 +01009813 if (count < 0) {
9814 PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
9815 return NULL;
9816 }
9817
9818 if (offset_src != Py_None) {
9819 if (!Py_off_t_converter(offset_src, &offset_src_val)) {
9820 return NULL;
9821 }
9822 p_offset_src = &offset_src_val;
9823 }
9824
9825 if (offset_dst != Py_None) {
9826 if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
9827 return NULL;
9828 }
9829 p_offset_dst = &offset_dst_val;
9830 }
9831
9832 do {
9833 Py_BEGIN_ALLOW_THREADS
9834 ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
9835 Py_END_ALLOW_THREADS
9836 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9837
9838 if (ret < 0) {
9839 return (!async_err) ? posix_error() : NULL;
9840 }
9841
9842 return PyLong_FromSsize_t(ret);
9843}
9844#endif /* HAVE_COPY_FILE_RANGE*/
Larry Hastings2f936352014-08-05 14:04:04 +10009845
9846#ifdef HAVE_MKFIFO
9847/*[clinic input]
9848os.mkfifo
9849
9850 path: path_t
9851 mode: int=0o666
9852 *
9853 dir_fd: dir_fd(requires='mkfifoat')=None
9854
9855Create a "fifo" (a POSIX named pipe).
9856
9857If dir_fd is not None, it should be a file descriptor open to a directory,
9858 and path should be relative; path will then be relative to that directory.
9859dir_fd may not be implemented on your platform.
9860 If it is unavailable, using it will raise a NotImplementedError.
9861[clinic start generated code]*/
9862
Larry Hastings2f936352014-08-05 14:04:04 +10009863static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009864os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
9865/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009866{
9867 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009868 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009869
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009870 do {
9871 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009872#ifdef HAVE_MKFIFOAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009873 if (dir_fd != DEFAULT_DIR_FD)
9874 result = mkfifoat(dir_fd, path->narrow, mode);
9875 else
Ross Lagerwall7807c352011-03-17 20:20:30 +02009876#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009877 result = mkfifo(path->narrow, mode);
9878 Py_END_ALLOW_THREADS
9879 } while (result != 0 && errno == EINTR &&
9880 !(async_err = PyErr_CheckSignals()));
9881 if (result != 0)
9882 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009883
9884 Py_RETURN_NONE;
9885}
9886#endif /* HAVE_MKFIFO */
9887
9888
9889#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
9890/*[clinic input]
9891os.mknod
9892
9893 path: path_t
9894 mode: int=0o600
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009895 device: dev_t=0
Larry Hastings2f936352014-08-05 14:04:04 +10009896 *
9897 dir_fd: dir_fd(requires='mknodat')=None
9898
9899Create a node in the file system.
9900
9901Create a node in the file system (file, device special file or named pipe)
9902at path. mode specifies both the permissions to use and the
9903type of node to be created, being combined (bitwise OR) with one of
9904S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
9905device defines the newly created device special file (probably using
9906os.makedev()). Otherwise device is ignored.
9907
9908If dir_fd is not None, it should be a file descriptor open to a directory,
9909 and path should be relative; path will then be relative to that directory.
9910dir_fd may not be implemented on your platform.
9911 If it is unavailable, using it will raise a NotImplementedError.
9912[clinic start generated code]*/
9913
Larry Hastings2f936352014-08-05 14:04:04 +10009914static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009915os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
Larry Hastings89964c42015-04-14 18:07:59 -04009916 int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009917/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009918{
9919 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009920 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009921
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009922 do {
9923 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009924#ifdef HAVE_MKNODAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009925 if (dir_fd != DEFAULT_DIR_FD)
9926 result = mknodat(dir_fd, path->narrow, mode, device);
9927 else
Larry Hastings2f936352014-08-05 14:04:04 +10009928#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009929 result = mknod(path->narrow, mode, device);
9930 Py_END_ALLOW_THREADS
9931 } while (result != 0 && errno == EINTR &&
9932 !(async_err = PyErr_CheckSignals()));
9933 if (result != 0)
9934 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009935
9936 Py_RETURN_NONE;
9937}
9938#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
9939
9940
9941#ifdef HAVE_DEVICE_MACROS
9942/*[clinic input]
9943os.major -> unsigned_int
9944
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009945 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009946 /
9947
9948Extracts a device major number from a raw device number.
9949[clinic start generated code]*/
9950
Larry Hastings2f936352014-08-05 14:04:04 +10009951static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009952os_major_impl(PyObject *module, dev_t device)
9953/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009954{
9955 return major(device);
9956}
9957
9958
9959/*[clinic input]
9960os.minor -> unsigned_int
9961
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009962 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009963 /
9964
9965Extracts a device minor number from a raw device number.
9966[clinic start generated code]*/
9967
Larry Hastings2f936352014-08-05 14:04:04 +10009968static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009969os_minor_impl(PyObject *module, dev_t device)
9970/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009971{
9972 return minor(device);
9973}
9974
9975
9976/*[clinic input]
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009977os.makedev -> dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009978
9979 major: int
9980 minor: int
9981 /
9982
9983Composes a raw device number from the major and minor device numbers.
9984[clinic start generated code]*/
9985
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009986static dev_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009987os_makedev_impl(PyObject *module, int major, int minor)
9988/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009989{
9990 return makedev(major, minor);
9991}
9992#endif /* HAVE_DEVICE_MACROS */
9993
9994
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009995#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009996/*[clinic input]
9997os.ftruncate
9998
9999 fd: int
10000 length: Py_off_t
10001 /
10002
10003Truncate a file, specified by file descriptor, to a specific length.
10004[clinic start generated code]*/
10005
Larry Hastings2f936352014-08-05 14:04:04 +100010006static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010007os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
10008/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010009{
10010 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010011 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +100010012
Steve Dowerb82e17e2019-05-23 08:45:22 -070010013 if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
10014 return NULL;
10015 }
10016
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010017 do {
10018 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -040010019 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010020#ifdef MS_WINDOWS
10021 result = _chsize_s(fd, length);
10022#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010023 result = ftruncate(fd, length);
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010024#endif
Steve Dowera1c7e722015-04-12 00:26:43 -040010025 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010026 Py_END_ALLOW_THREADS
10027 } while (result != 0 && errno == EINTR &&
10028 !(async_err = PyErr_CheckSignals()));
10029 if (result != 0)
10030 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100010031 Py_RETURN_NONE;
10032}
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010033#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +100010034
10035
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010036#if defined HAVE_TRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010037/*[clinic input]
10038os.truncate
10039 path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
10040 length: Py_off_t
10041
10042Truncate a file, specified by path, to a specific length.
10043
10044On some platforms, path may also be specified as an open file descriptor.
10045 If this functionality is unavailable, using it raises an exception.
10046[clinic start generated code]*/
10047
Larry Hastings2f936352014-08-05 14:04:04 +100010048static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010049os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
10050/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010051{
10052 int result;
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010053#ifdef MS_WINDOWS
10054 int fd;
10055#endif
10056
10057 if (path->fd != -1)
10058 return os_ftruncate_impl(module, path->fd, length);
Larry Hastings2f936352014-08-05 14:04:04 +100010059
Steve Dowerb82e17e2019-05-23 08:45:22 -070010060 if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
10061 return NULL;
10062 }
10063
Larry Hastings2f936352014-08-05 14:04:04 +100010064 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -040010065 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010066#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -070010067 fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
Victor Stinnercc0bbbc2015-04-25 00:21:52 +020010068 if (fd < 0)
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010069 result = -1;
10070 else {
10071 result = _chsize_s(fd, length);
10072 close(fd);
10073 if (result < 0)
10074 errno = result;
10075 }
10076#else
10077 result = truncate(path->narrow, length);
Larry Hastings2f936352014-08-05 14:04:04 +100010078#endif
Steve Dowera1c7e722015-04-12 00:26:43 -040010079 _Py_END_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +100010080 Py_END_ALLOW_THREADS
10081 if (result < 0)
Alexey Izbyshev83460312018-10-20 03:28:22 +030010082 return posix_path_error(path);
Larry Hastings2f936352014-08-05 14:04:04 +100010083
10084 Py_RETURN_NONE;
10085}
Steve Dowerfe0a41a2015-03-20 19:50:46 -070010086#endif /* HAVE_TRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +100010087
Ross Lagerwall7807c352011-03-17 20:20:30 +020010088
Victor Stinnerd6b17692014-09-30 12:20:05 +020010089/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
10090 and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
10091 defined, which is the case in Python on AIX. AIX bug report:
10092 http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
10093#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
10094# define POSIX_FADVISE_AIX_BUG
10095#endif
10096
Victor Stinnerec39e262014-09-30 12:35:58 +020010097
Victor Stinnerd6b17692014-09-30 12:20:05 +020010098#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +100010099/*[clinic input]
10100os.posix_fallocate
10101
10102 fd: int
10103 offset: Py_off_t
10104 length: Py_off_t
10105 /
10106
10107Ensure a file has allocated at least a particular number of bytes on disk.
10108
10109Ensure that the file specified by fd encompasses a range of bytes
10110starting at offset bytes from the beginning and continuing for length bytes.
10111[clinic start generated code]*/
10112
Larry Hastings2f936352014-08-05 14:04:04 +100010113static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010114os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -040010115 Py_off_t length)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010116/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010117{
10118 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010119 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010120
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010121 do {
10122 Py_BEGIN_ALLOW_THREADS
10123 result = posix_fallocate(fd, offset, length);
10124 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010125 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10126
10127 if (result == 0)
10128 Py_RETURN_NONE;
10129
10130 if (async_err)
10131 return NULL;
10132
10133 errno = result;
10134 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010135}
Victor Stinnerec39e262014-09-30 12:35:58 +020010136#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
Larry Hastings2f936352014-08-05 14:04:04 +100010137
Ross Lagerwall7807c352011-03-17 20:20:30 +020010138
Victor Stinnerd6b17692014-09-30 12:20:05 +020010139#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +100010140/*[clinic input]
10141os.posix_fadvise
10142
10143 fd: int
10144 offset: Py_off_t
10145 length: Py_off_t
10146 advice: int
10147 /
10148
10149Announce an intention to access data in a specific pattern.
10150
10151Announce an intention to access data in a specific pattern, thus allowing
10152the kernel to make optimizations.
10153The advice applies to the region of the file specified by fd starting at
10154offset and continuing for length bytes.
10155advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
10156POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
10157POSIX_FADV_DONTNEED.
10158[clinic start generated code]*/
10159
Larry Hastings2f936352014-08-05 14:04:04 +100010160static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010161os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -040010162 Py_off_t length, int advice)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010163/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010164{
10165 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010166 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010167
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010168 do {
10169 Py_BEGIN_ALLOW_THREADS
10170 result = posix_fadvise(fd, offset, length, advice);
10171 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010172 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10173
10174 if (result == 0)
10175 Py_RETURN_NONE;
10176
10177 if (async_err)
10178 return NULL;
10179
10180 errno = result;
10181 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010182}
Victor Stinnerec39e262014-09-30 12:35:58 +020010183#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
Ross Lagerwall7807c352011-03-17 20:20:30 +020010184
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000010185
Thomas Hellerf78f12a2007-11-08 19:33:05 +000010186#ifdef MS_WINDOWS
Victor Stinner161e7b32020-01-24 11:53:44 +010010187static PyObject*
10188win32_putenv(PyObject *name, PyObject *value)
10189{
10190 /* Search from index 1 because on Windows starting '=' is allowed for
10191 defining hidden environment variables. */
10192 if (PyUnicode_GET_LENGTH(name) == 0 ||
10193 PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
10194 {
10195 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10196 return NULL;
10197 }
10198 PyObject *unicode;
10199 if (value != NULL) {
10200 unicode = PyUnicode_FromFormat("%U=%U", name, value);
10201 }
10202 else {
10203 unicode = PyUnicode_FromFormat("%U=", name);
10204 }
10205 if (unicode == NULL) {
10206 return NULL;
10207 }
10208
10209 Py_ssize_t size;
10210 /* PyUnicode_AsWideCharString() rejects embedded null characters */
10211 wchar_t *env = PyUnicode_AsWideCharString(unicode, &size);
10212 Py_DECREF(unicode);
10213
10214 if (env == NULL) {
10215 return NULL;
10216 }
10217 if (size > _MAX_ENV) {
10218 PyErr_Format(PyExc_ValueError,
10219 "the environment variable is longer than %u characters",
10220 _MAX_ENV);
10221 PyMem_Free(env);
10222 return NULL;
10223 }
10224
10225 /* _wputenv() and SetEnvironmentVariableW() update the environment in the
10226 Process Environment Block (PEB). _wputenv() also updates CRT 'environ'
10227 and '_wenviron' variables, whereas SetEnvironmentVariableW() does not.
10228
10229 Prefer _wputenv() to be compatible with C libraries using CRT
10230 variables and CRT functions using these variables (ex: getenv()). */
10231 int err = _wputenv(env);
10232 PyMem_Free(env);
10233
10234 if (err) {
10235 posix_error();
10236 return NULL;
10237 }
10238
10239 Py_RETURN_NONE;
10240}
10241#endif
10242
10243
10244#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010245/*[clinic input]
10246os.putenv
10247
10248 name: unicode
10249 value: unicode
10250 /
10251
10252Change or add an environment variable.
10253[clinic start generated code]*/
10254
Larry Hastings2f936352014-08-05 14:04:04 +100010255static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010256os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10257/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010258{
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010259 if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
10260 return NULL;
10261 }
Victor Stinner161e7b32020-01-24 11:53:44 +010010262 return win32_putenv(name, value);
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010263}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010264#else
Larry Hastings2f936352014-08-05 14:04:04 +100010265/*[clinic input]
10266os.putenv
Guido van Rossumb6a47161997-09-15 22:54:34 +000010267
Larry Hastings2f936352014-08-05 14:04:04 +100010268 name: FSConverter
10269 value: FSConverter
10270 /
10271
10272Change or add an environment variable.
10273[clinic start generated code]*/
10274
Larry Hastings2f936352014-08-05 14:04:04 +100010275static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010276os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10277/*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010278{
Serhiy Storchaka77703942017-06-25 07:33:01 +030010279 const char *name_string = PyBytes_AS_STRING(name);
10280 const char *value_string = PyBytes_AS_STRING(value);
Larry Hastings2f936352014-08-05 14:04:04 +100010281
Serhiy Storchaka77703942017-06-25 07:33:01 +030010282 if (strchr(name_string, '=') != NULL) {
10283 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10284 return NULL;
10285 }
Victor Stinnerb477d192020-01-22 22:48:16 +010010286
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010287 if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
10288 return NULL;
10289 }
10290
Victor Stinnerb477d192020-01-22 22:48:16 +010010291 if (setenv(name_string, value_string, 1)) {
10292 return posix_error();
10293 }
Larry Hastings2f936352014-08-05 14:04:04 +100010294 Py_RETURN_NONE;
10295}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010296#endif /* !defined(MS_WINDOWS) */
Larry Hastings2f936352014-08-05 14:04:04 +100010297
10298
Victor Stinner161e7b32020-01-24 11:53:44 +010010299#ifdef MS_WINDOWS
10300/*[clinic input]
10301os.unsetenv
10302 name: unicode
10303 /
10304
10305Delete an environment variable.
10306[clinic start generated code]*/
10307
10308static PyObject *
10309os_unsetenv_impl(PyObject *module, PyObject *name)
10310/*[clinic end generated code: output=54c4137ab1834f02 input=4d6a1747cc526d2f]*/
10311{
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010312 if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
10313 return NULL;
10314 }
Victor Stinner161e7b32020-01-24 11:53:44 +010010315 return win32_putenv(name, NULL);
10316}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010317#else
Larry Hastings2f936352014-08-05 14:04:04 +100010318/*[clinic input]
10319os.unsetenv
10320 name: FSConverter
10321 /
10322
10323Delete an environment variable.
10324[clinic start generated code]*/
10325
Larry Hastings2f936352014-08-05 14:04:04 +100010326static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010327os_unsetenv_impl(PyObject *module, PyObject *name)
10328/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010329{
Saiyang Gou7514f4f2020-02-12 23:47:42 -080010330 if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
10331 return NULL;
10332 }
Victor Stinner984890f2011-11-24 13:53:38 +010010333#ifdef HAVE_BROKEN_UNSETENV
10334 unsetenv(PyBytes_AS_STRING(name));
10335#else
Victor Stinner161e7b32020-01-24 11:53:44 +010010336 int err = unsetenv(PyBytes_AS_STRING(name));
10337 if (err) {
Victor Stinner60b385e2011-11-22 22:01:28 +010010338 return posix_error();
Victor Stinner161e7b32020-01-24 11:53:44 +010010339 }
Victor Stinner984890f2011-11-24 13:53:38 +010010340#endif
Guido van Rossumc524d952001-10-19 01:31:59 +000010341
Victor Stinner84ae1182010-05-06 22:05:07 +000010342 Py_RETURN_NONE;
Guido van Rossumc524d952001-10-19 01:31:59 +000010343}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010344#endif /* !MS_WINDOWS */
Guido van Rossumc524d952001-10-19 01:31:59 +000010345
Larry Hastings2f936352014-08-05 14:04:04 +100010346
10347/*[clinic input]
10348os.strerror
10349
10350 code: int
10351 /
10352
10353Translate an error code to a message string.
10354[clinic start generated code]*/
10355
Larry Hastings2f936352014-08-05 14:04:04 +100010356static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010357os_strerror_impl(PyObject *module, int code)
10358/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010359{
10360 char *message = strerror(code);
Victor Stinner8c62be82010-05-06 00:08:46 +000010361 if (message == NULL) {
10362 PyErr_SetString(PyExc_ValueError,
10363 "strerror() argument out of range");
10364 return NULL;
10365 }
Victor Stinner1b579672011-12-17 05:47:23 +010010366 return PyUnicode_DecodeLocale(message, "surrogateescape");
Guido van Rossumb6a47161997-09-15 22:54:34 +000010367}
Guido van Rossumb6a47161997-09-15 22:54:34 +000010368
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010369
Guido van Rossumc9641791998-08-04 15:26:23 +000010370#ifdef HAVE_SYS_WAIT_H
Fred Drake106c1a02002-04-23 15:58:02 +000010371#ifdef WCOREDUMP
Larry Hastings2f936352014-08-05 14:04:04 +100010372/*[clinic input]
10373os.WCOREDUMP -> bool
10374
10375 status: int
10376 /
10377
10378Return True if the process returning status was dumped to a core file.
10379[clinic start generated code]*/
10380
Larry Hastings2f936352014-08-05 14:04:04 +100010381static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010382os_WCOREDUMP_impl(PyObject *module, int status)
10383/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010384{
10385 WAIT_TYPE wait_status;
10386 WAIT_STATUS_INT(wait_status) = status;
10387 return WCOREDUMP(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010388}
10389#endif /* WCOREDUMP */
10390
Larry Hastings2f936352014-08-05 14:04:04 +100010391
Fred Drake106c1a02002-04-23 15:58:02 +000010392#ifdef WIFCONTINUED
Larry Hastings2f936352014-08-05 14:04:04 +100010393/*[clinic input]
10394os.WIFCONTINUED -> bool
10395
10396 status: int
10397
10398Return True if a particular process was continued from a job control stop.
10399
10400Return True if the process returning status was continued from a
10401job control stop.
10402[clinic start generated code]*/
10403
Larry Hastings2f936352014-08-05 14:04:04 +100010404static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010405os_WIFCONTINUED_impl(PyObject *module, int status)
10406/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010407{
10408 WAIT_TYPE wait_status;
10409 WAIT_STATUS_INT(wait_status) = status;
10410 return WIFCONTINUED(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010411}
10412#endif /* WIFCONTINUED */
10413
Larry Hastings2f936352014-08-05 14:04:04 +100010414
Guido van Rossumc9641791998-08-04 15:26:23 +000010415#ifdef WIFSTOPPED
Larry Hastings2f936352014-08-05 14:04:04 +100010416/*[clinic input]
10417os.WIFSTOPPED -> bool
10418
10419 status: int
10420
10421Return True if the process returning status was stopped.
10422[clinic start generated code]*/
10423
Larry Hastings2f936352014-08-05 14:04:04 +100010424static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010425os_WIFSTOPPED_impl(PyObject *module, int status)
10426/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010427{
10428 WAIT_TYPE wait_status;
10429 WAIT_STATUS_INT(wait_status) = status;
10430 return WIFSTOPPED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010431}
10432#endif /* WIFSTOPPED */
10433
Larry Hastings2f936352014-08-05 14:04:04 +100010434
Guido van Rossumc9641791998-08-04 15:26:23 +000010435#ifdef WIFSIGNALED
Larry Hastings2f936352014-08-05 14:04:04 +100010436/*[clinic input]
10437os.WIFSIGNALED -> bool
10438
10439 status: int
10440
10441Return True if the process returning status was terminated by a signal.
10442[clinic start generated code]*/
10443
Larry Hastings2f936352014-08-05 14:04:04 +100010444static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010445os_WIFSIGNALED_impl(PyObject *module, int status)
10446/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010447{
10448 WAIT_TYPE wait_status;
10449 WAIT_STATUS_INT(wait_status) = status;
10450 return WIFSIGNALED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010451}
10452#endif /* WIFSIGNALED */
10453
Larry Hastings2f936352014-08-05 14:04:04 +100010454
Guido van Rossumc9641791998-08-04 15:26:23 +000010455#ifdef WIFEXITED
Larry Hastings2f936352014-08-05 14:04:04 +100010456/*[clinic input]
10457os.WIFEXITED -> bool
10458
10459 status: int
10460
10461Return True if the process returning status exited via the exit() system call.
10462[clinic start generated code]*/
10463
Larry Hastings2f936352014-08-05 14:04:04 +100010464static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010465os_WIFEXITED_impl(PyObject *module, int status)
10466/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010467{
10468 WAIT_TYPE wait_status;
10469 WAIT_STATUS_INT(wait_status) = status;
10470 return WIFEXITED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010471}
10472#endif /* WIFEXITED */
10473
Larry Hastings2f936352014-08-05 14:04:04 +100010474
Guido van Rossum54ecc3d1999-01-27 17:53:11 +000010475#ifdef WEXITSTATUS
Larry Hastings2f936352014-08-05 14:04:04 +100010476/*[clinic input]
10477os.WEXITSTATUS -> int
10478
10479 status: int
10480
10481Return the process return code from status.
10482[clinic start generated code]*/
10483
Larry Hastings2f936352014-08-05 14:04:04 +100010484static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010485os_WEXITSTATUS_impl(PyObject *module, int status)
10486/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010487{
10488 WAIT_TYPE wait_status;
10489 WAIT_STATUS_INT(wait_status) = status;
10490 return WEXITSTATUS(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010491}
10492#endif /* WEXITSTATUS */
10493
Larry Hastings2f936352014-08-05 14:04:04 +100010494
Guido van Rossumc9641791998-08-04 15:26:23 +000010495#ifdef WTERMSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010496/*[clinic input]
10497os.WTERMSIG -> int
10498
10499 status: int
10500
10501Return the signal that terminated the process that provided the status value.
10502[clinic start generated code]*/
10503
Larry Hastings2f936352014-08-05 14:04:04 +100010504static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010505os_WTERMSIG_impl(PyObject *module, int status)
10506/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010507{
10508 WAIT_TYPE wait_status;
10509 WAIT_STATUS_INT(wait_status) = status;
10510 return WTERMSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010511}
10512#endif /* WTERMSIG */
10513
Larry Hastings2f936352014-08-05 14:04:04 +100010514
Guido van Rossumc9641791998-08-04 15:26:23 +000010515#ifdef WSTOPSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010516/*[clinic input]
10517os.WSTOPSIG -> int
10518
10519 status: int
10520
10521Return the signal that stopped the process that provided the status value.
10522[clinic start generated code]*/
10523
Larry Hastings2f936352014-08-05 14:04:04 +100010524static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010525os_WSTOPSIG_impl(PyObject *module, int status)
10526/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010527{
10528 WAIT_TYPE wait_status;
10529 WAIT_STATUS_INT(wait_status) = status;
10530 return WSTOPSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010531}
10532#endif /* WSTOPSIG */
Guido van Rossumc9641791998-08-04 15:26:23 +000010533#endif /* HAVE_SYS_WAIT_H */
10534
10535
Thomas Wouters477c8d52006-05-27 19:21:47 +000010536#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossumd5753e11999-10-19 13:29:23 +000010537#ifdef _SCO_DS
10538/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
10539 needed definitions in sys/statvfs.h */
10540#define _SVID3
10541#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000010542#include <sys/statvfs.h>
10543
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010544static PyObject*
10545_pystatvfs_fromstructstatvfs(struct statvfs st) {
Eddie Elizondob3966632019-11-05 07:16:14 -080010546 PyObject *StatVFSResultType = _posixstate_global->StatVFSResultType;
10547 PyObject *v = PyStructSequence_New((PyTypeObject *)StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000010548 if (v == NULL)
10549 return NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010550
10551#if !defined(HAVE_LARGEFILE_SUPPORT)
Victor Stinner8c62be82010-05-06 00:08:46 +000010552 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10553 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10554 PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
10555 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
10556 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
10557 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
10558 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
10559 PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
10560 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10561 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010562#else
Victor Stinner8c62be82010-05-06 00:08:46 +000010563 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10564 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10565 PyStructSequence_SET_ITEM(v, 2,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010566 PyLong_FromLongLong((long long) st.f_blocks));
Victor Stinner8c62be82010-05-06 00:08:46 +000010567 PyStructSequence_SET_ITEM(v, 3,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010568 PyLong_FromLongLong((long long) st.f_bfree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010569 PyStructSequence_SET_ITEM(v, 4,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010570 PyLong_FromLongLong((long long) st.f_bavail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010571 PyStructSequence_SET_ITEM(v, 5,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010572 PyLong_FromLongLong((long long) st.f_files));
Victor Stinner8c62be82010-05-06 00:08:46 +000010573 PyStructSequence_SET_ITEM(v, 6,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010574 PyLong_FromLongLong((long long) st.f_ffree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010575 PyStructSequence_SET_ITEM(v, 7,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010576 PyLong_FromLongLong((long long) st.f_favail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010577 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10578 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010579#endif
Michael Felt502d5512018-01-05 13:01:58 +010010580/* The _ALL_SOURCE feature test macro defines f_fsid as a structure
10581 * (issue #32390). */
10582#if defined(_AIX) && defined(_ALL_SOURCE)
10583 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
10584#else
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +010010585 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid));
Michael Felt502d5512018-01-05 13:01:58 +010010586#endif
Victor Stinnerf0a7bac2013-10-30 18:55:24 +010010587 if (PyErr_Occurred()) {
10588 Py_DECREF(v);
10589 return NULL;
10590 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010591
Victor Stinner8c62be82010-05-06 00:08:46 +000010592 return v;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010593}
10594
Larry Hastings2f936352014-08-05 14:04:04 +100010595
10596/*[clinic input]
10597os.fstatvfs
10598 fd: int
10599 /
10600
10601Perform an fstatvfs system call on the given fd.
10602
10603Equivalent to statvfs(fd).
10604[clinic start generated code]*/
10605
Larry Hastings2f936352014-08-05 14:04:04 +100010606static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010607os_fstatvfs_impl(PyObject *module, int fd)
10608/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010609{
10610 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010611 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010612 struct statvfs st;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010613
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010614 do {
10615 Py_BEGIN_ALLOW_THREADS
10616 result = fstatvfs(fd, &st);
10617 Py_END_ALLOW_THREADS
10618 } while (result != 0 && errno == EINTR &&
10619 !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +100010620 if (result != 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010621 return (!async_err) ? posix_error() : NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010622
Victor Stinner8c62be82010-05-06 00:08:46 +000010623 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010624}
Larry Hastings2f936352014-08-05 14:04:04 +100010625#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
Guido van Rossum94f6f721999-01-06 18:42:14 +000010626
10627
Thomas Wouters477c8d52006-05-27 19:21:47 +000010628#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossum94f6f721999-01-06 18:42:14 +000010629#include <sys/statvfs.h>
Larry Hastings2f936352014-08-05 14:04:04 +100010630/*[clinic input]
10631os.statvfs
Guido van Rossum94f6f721999-01-06 18:42:14 +000010632
Larry Hastings2f936352014-08-05 14:04:04 +100010633 path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
10634
10635Perform a statvfs system call on the given path.
10636
10637path may always be specified as a string.
10638On some platforms, path may also be specified as an open file descriptor.
10639 If this functionality is unavailable, using it raises an exception.
10640[clinic start generated code]*/
10641
Larry Hastings2f936352014-08-05 14:04:04 +100010642static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010643os_statvfs_impl(PyObject *module, path_t *path)
10644/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010645{
10646 int result;
10647 struct statvfs st;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010648
10649 Py_BEGIN_ALLOW_THREADS
10650#ifdef HAVE_FSTATVFS
Larry Hastings2f936352014-08-05 14:04:04 +100010651 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -070010652#ifdef __APPLE__
10653 /* handle weak-linking on Mac OS X 10.3 */
10654 if (fstatvfs == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010655 fd_specified("statvfs", path->fd);
10656 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010657 }
10658#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010659 result = fstatvfs(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010660 }
10661 else
10662#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010663 result = statvfs(path->narrow, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010664 Py_END_ALLOW_THREADS
10665
10666 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100010667 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010668 }
10669
Larry Hastings2f936352014-08-05 14:04:04 +100010670 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010671}
Larry Hastings2f936352014-08-05 14:04:04 +100010672#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
10673
Guido van Rossum94f6f721999-01-06 18:42:14 +000010674
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010675#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010676/*[clinic input]
10677os._getdiskusage
10678
Steve Dower23ad6d02018-02-22 10:39:10 -080010679 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +100010680
10681Return disk usage statistics about the given path as a (total, free) tuple.
10682[clinic start generated code]*/
10683
Larry Hastings2f936352014-08-05 14:04:04 +100010684static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -080010685os__getdiskusage_impl(PyObject *module, path_t *path)
10686/*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010687{
10688 BOOL retval;
10689 ULARGE_INTEGER _, total, free;
Joe Pamerc8c02492018-09-25 10:57:36 -040010690 DWORD err = 0;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010691
10692 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -080010693 retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010694 Py_END_ALLOW_THREADS
Joe Pamerc8c02492018-09-25 10:57:36 -040010695 if (retval == 0) {
10696 if (GetLastError() == ERROR_DIRECTORY) {
10697 wchar_t *dir_path = NULL;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010698
Joe Pamerc8c02492018-09-25 10:57:36 -040010699 dir_path = PyMem_New(wchar_t, path->length + 1);
10700 if (dir_path == NULL) {
10701 return PyErr_NoMemory();
10702 }
10703
10704 wcscpy_s(dir_path, path->length + 1, path->wide);
10705
10706 if (_dirnameW(dir_path) != -1) {
10707 Py_BEGIN_ALLOW_THREADS
10708 retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
10709 Py_END_ALLOW_THREADS
10710 }
10711 /* Record the last error in case it's modified by PyMem_Free. */
10712 err = GetLastError();
10713 PyMem_Free(dir_path);
10714 if (retval) {
10715 goto success;
10716 }
10717 }
10718 return PyErr_SetFromWindowsErr(err);
10719 }
10720
10721success:
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010722 return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
10723}
Larry Hastings2f936352014-08-05 14:04:04 +100010724#endif /* MS_WINDOWS */
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010725
10726
Fred Drakec9680921999-12-13 16:37:25 +000010727/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
10728 * It maps strings representing configuration variable names to
10729 * integer values, allowing those functions to be called with the
Thomas Wouters7e474022000-07-16 12:04:32 +000010730 * magic names instead of polluting the module's namespace with tons of
Fred Drake12c6e2d1999-12-14 21:25:03 +000010731 * rarely-used constants. There are three separate tables that use
10732 * these definitions.
Fred Drakebec628d1999-12-15 18:31:10 +000010733 *
10734 * This code is always included, even if none of the interfaces that
10735 * need it are included. The #if hackery needed to avoid it would be
10736 * sufficiently pervasive that it's not worth the loss of readability.
Fred Drakec9680921999-12-13 16:37:25 +000010737 */
10738struct constdef {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020010739 const char *name;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010740 int value;
Fred Drakec9680921999-12-13 16:37:25 +000010741};
10742
Fred Drake12c6e2d1999-12-14 21:25:03 +000010743static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010744conv_confname(PyObject *arg, int *valuep, struct constdef *table,
Guido van Rossum7d5baac2007-08-27 23:24:46 +000010745 size_t tablesize)
Fred Drake12c6e2d1999-12-14 21:25:03 +000010746{
Christian Heimes217cfd12007-12-02 14:31:20 +000010747 if (PyLong_Check(arg)) {
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010748 int value = _PyLong_AsInt(arg);
10749 if (value == -1 && PyErr_Occurred())
10750 return 0;
10751 *valuep = value;
Stefan Krah0e803b32010-11-26 16:16:47 +000010752 return 1;
Fred Drake12c6e2d1999-12-14 21:25:03 +000010753 }
Guido van Rossumbce56a62007-05-10 18:04:33 +000010754 else {
Stefan Krah0e803b32010-11-26 16:16:47 +000010755 /* look up the value in the table using a binary search */
10756 size_t lo = 0;
10757 size_t mid;
10758 size_t hi = tablesize;
10759 int cmp;
10760 const char *confname;
10761 if (!PyUnicode_Check(arg)) {
10762 PyErr_SetString(PyExc_TypeError,
10763 "configuration names must be strings or integers");
10764 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010765 }
Serhiy Storchaka06515832016-11-20 09:13:07 +020010766 confname = PyUnicode_AsUTF8(arg);
Stefan Krah0e803b32010-11-26 16:16:47 +000010767 if (confname == NULL)
10768 return 0;
10769 while (lo < hi) {
10770 mid = (lo + hi) / 2;
10771 cmp = strcmp(confname, table[mid].name);
10772 if (cmp < 0)
10773 hi = mid;
10774 else if (cmp > 0)
10775 lo = mid + 1;
10776 else {
10777 *valuep = table[mid].value;
10778 return 1;
10779 }
10780 }
10781 PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
10782 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010783 }
Fred Drake12c6e2d1999-12-14 21:25:03 +000010784}
10785
10786
10787#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
10788static struct constdef posix_constants_pathconf[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010789#ifdef _PC_ABI_AIO_XFER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010790 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000010791#endif
10792#ifdef _PC_ABI_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010793 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010794#endif
Fred Drakec9680921999-12-13 16:37:25 +000010795#ifdef _PC_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010796 {"PC_ASYNC_IO", _PC_ASYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010797#endif
10798#ifdef _PC_CHOWN_RESTRICTED
Victor Stinner8c62be82010-05-06 00:08:46 +000010799 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
Fred Drakec9680921999-12-13 16:37:25 +000010800#endif
10801#ifdef _PC_FILESIZEBITS
Victor Stinner8c62be82010-05-06 00:08:46 +000010802 {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
Fred Drakec9680921999-12-13 16:37:25 +000010803#endif
10804#ifdef _PC_LAST
Victor Stinner8c62be82010-05-06 00:08:46 +000010805 {"PC_LAST", _PC_LAST},
Fred Drakec9680921999-12-13 16:37:25 +000010806#endif
10807#ifdef _PC_LINK_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010808 {"PC_LINK_MAX", _PC_LINK_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010809#endif
10810#ifdef _PC_MAX_CANON
Victor Stinner8c62be82010-05-06 00:08:46 +000010811 {"PC_MAX_CANON", _PC_MAX_CANON},
Fred Drakec9680921999-12-13 16:37:25 +000010812#endif
10813#ifdef _PC_MAX_INPUT
Victor Stinner8c62be82010-05-06 00:08:46 +000010814 {"PC_MAX_INPUT", _PC_MAX_INPUT},
Fred Drakec9680921999-12-13 16:37:25 +000010815#endif
10816#ifdef _PC_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010817 {"PC_NAME_MAX", _PC_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010818#endif
10819#ifdef _PC_NO_TRUNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010820 {"PC_NO_TRUNC", _PC_NO_TRUNC},
Fred Drakec9680921999-12-13 16:37:25 +000010821#endif
10822#ifdef _PC_PATH_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010823 {"PC_PATH_MAX", _PC_PATH_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010824#endif
10825#ifdef _PC_PIPE_BUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010826 {"PC_PIPE_BUF", _PC_PIPE_BUF},
Fred Drakec9680921999-12-13 16:37:25 +000010827#endif
10828#ifdef _PC_PRIO_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010829 {"PC_PRIO_IO", _PC_PRIO_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010830#endif
10831#ifdef _PC_SOCK_MAXBUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010832 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
Fred Drakec9680921999-12-13 16:37:25 +000010833#endif
10834#ifdef _PC_SYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010835 {"PC_SYNC_IO", _PC_SYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010836#endif
10837#ifdef _PC_VDISABLE
Victor Stinner8c62be82010-05-06 00:08:46 +000010838 {"PC_VDISABLE", _PC_VDISABLE},
Fred Drakec9680921999-12-13 16:37:25 +000010839#endif
Jesus Cea7e9065c2010-10-25 13:02:04 +000010840#ifdef _PC_ACL_ENABLED
10841 {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
10842#endif
10843#ifdef _PC_MIN_HOLE_SIZE
10844 {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
10845#endif
10846#ifdef _PC_ALLOC_SIZE_MIN
10847 {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
10848#endif
10849#ifdef _PC_REC_INCR_XFER_SIZE
10850 {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
10851#endif
10852#ifdef _PC_REC_MAX_XFER_SIZE
10853 {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
10854#endif
10855#ifdef _PC_REC_MIN_XFER_SIZE
10856 {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
10857#endif
10858#ifdef _PC_REC_XFER_ALIGN
10859 {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
10860#endif
10861#ifdef _PC_SYMLINK_MAX
10862 {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
10863#endif
10864#ifdef _PC_XATTR_ENABLED
10865 {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
10866#endif
10867#ifdef _PC_XATTR_EXISTS
10868 {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
10869#endif
10870#ifdef _PC_TIMESTAMP_RESOLUTION
10871 {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
10872#endif
Fred Drakec9680921999-12-13 16:37:25 +000010873};
10874
Fred Drakec9680921999-12-13 16:37:25 +000010875static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010876conv_path_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010877{
10878 return conv_confname(arg, valuep, posix_constants_pathconf,
10879 sizeof(posix_constants_pathconf)
10880 / sizeof(struct constdef));
10881}
10882#endif
10883
Larry Hastings2f936352014-08-05 14:04:04 +100010884
Fred Drakec9680921999-12-13 16:37:25 +000010885#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010886/*[clinic input]
10887os.fpathconf -> long
10888
10889 fd: int
10890 name: path_confname
10891 /
10892
10893Return the configuration limit name for the file descriptor fd.
10894
10895If there is no limit, return -1.
10896[clinic start generated code]*/
10897
Larry Hastings2f936352014-08-05 14:04:04 +100010898static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010899os_fpathconf_impl(PyObject *module, int fd, int name)
10900/*[clinic end generated code: output=d5b7042425fc3e21 input=5942a024d3777810]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010901{
10902 long limit;
10903
10904 errno = 0;
10905 limit = fpathconf(fd, name);
10906 if (limit == -1 && errno != 0)
10907 posix_error();
10908
10909 return limit;
10910}
10911#endif /* HAVE_FPATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010912
10913
10914#ifdef HAVE_PATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010915/*[clinic input]
10916os.pathconf -> long
10917 path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
10918 name: path_confname
10919
10920Return the configuration limit name for the file or directory path.
10921
10922If there is no limit, return -1.
10923On some platforms, path may also be specified as an open file descriptor.
10924 If this functionality is unavailable, using it raises an exception.
10925[clinic start generated code]*/
10926
Larry Hastings2f936352014-08-05 14:04:04 +100010927static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010928os_pathconf_impl(PyObject *module, path_t *path, int name)
10929/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010930{
Victor Stinner8c62be82010-05-06 00:08:46 +000010931 long limit;
Fred Drakec9680921999-12-13 16:37:25 +000010932
Victor Stinner8c62be82010-05-06 00:08:46 +000010933 errno = 0;
Georg Brandl306336b2012-06-24 12:55:33 +020010934#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010935 if (path->fd != -1)
10936 limit = fpathconf(path->fd, name);
Georg Brandl306336b2012-06-24 12:55:33 +020010937 else
10938#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010939 limit = pathconf(path->narrow, name);
Victor Stinner8c62be82010-05-06 00:08:46 +000010940 if (limit == -1 && errno != 0) {
10941 if (errno == EINVAL)
Stefan Krah99439262010-11-26 12:58:05 +000010942 /* could be a path or name problem */
10943 posix_error();
Fred Drakec9680921999-12-13 16:37:25 +000010944 else
Larry Hastings2f936352014-08-05 14:04:04 +100010945 path_error(path);
Victor Stinner8c62be82010-05-06 00:08:46 +000010946 }
Larry Hastings2f936352014-08-05 14:04:04 +100010947
10948 return limit;
Fred Drakec9680921999-12-13 16:37:25 +000010949}
Larry Hastings2f936352014-08-05 14:04:04 +100010950#endif /* HAVE_PATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010951
10952#ifdef HAVE_CONFSTR
10953static struct constdef posix_constants_confstr[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010954#ifdef _CS_ARCHITECTURE
Victor Stinner8c62be82010-05-06 00:08:46 +000010955 {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
Fred Draked86ed291999-12-15 15:34:33 +000010956#endif
Mark Dickinson876d7c82010-04-16 12:47:52 +000010957#ifdef _CS_GNU_LIBC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010958 {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010959#endif
10960#ifdef _CS_GNU_LIBPTHREAD_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010961 {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010962#endif
Fred Draked86ed291999-12-15 15:34:33 +000010963#ifdef _CS_HOSTNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010964 {"CS_HOSTNAME", _CS_HOSTNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010965#endif
10966#ifdef _CS_HW_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010967 {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010968#endif
10969#ifdef _CS_HW_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010970 {"CS_HW_SERIAL", _CS_HW_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010971#endif
10972#ifdef _CS_INITTAB_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010973 {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010974#endif
Fred Drakec9680921999-12-13 16:37:25 +000010975#ifdef _CS_LFS64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010976 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010977#endif
10978#ifdef _CS_LFS64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010979 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010980#endif
10981#ifdef _CS_LFS64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010982 {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010983#endif
10984#ifdef _CS_LFS64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010985 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010986#endif
10987#ifdef _CS_LFS_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010988 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010989#endif
10990#ifdef _CS_LFS_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010991 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010992#endif
10993#ifdef _CS_LFS_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010994 {"CS_LFS_LIBS", _CS_LFS_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010995#endif
10996#ifdef _CS_LFS_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010997 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010998#endif
Fred Draked86ed291999-12-15 15:34:33 +000010999#ifdef _CS_MACHINE
Victor Stinner8c62be82010-05-06 00:08:46 +000011000 {"CS_MACHINE", _CS_MACHINE},
Fred Draked86ed291999-12-15 15:34:33 +000011001#endif
Fred Drakec9680921999-12-13 16:37:25 +000011002#ifdef _CS_PATH
Victor Stinner8c62be82010-05-06 00:08:46 +000011003 {"CS_PATH", _CS_PATH},
Fred Drakec9680921999-12-13 16:37:25 +000011004#endif
Fred Draked86ed291999-12-15 15:34:33 +000011005#ifdef _CS_RELEASE
Victor Stinner8c62be82010-05-06 00:08:46 +000011006 {"CS_RELEASE", _CS_RELEASE},
Fred Draked86ed291999-12-15 15:34:33 +000011007#endif
11008#ifdef _CS_SRPC_DOMAIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011009 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
Fred Draked86ed291999-12-15 15:34:33 +000011010#endif
11011#ifdef _CS_SYSNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011012 {"CS_SYSNAME", _CS_SYSNAME},
Fred Draked86ed291999-12-15 15:34:33 +000011013#endif
11014#ifdef _CS_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011015 {"CS_VERSION", _CS_VERSION},
Fred Draked86ed291999-12-15 15:34:33 +000011016#endif
Fred Drakec9680921999-12-13 16:37:25 +000011017#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011018 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011019#endif
11020#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011021 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011022#endif
11023#ifdef _CS_XBS5_ILP32_OFF32_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011024 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011025#endif
11026#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011027 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011028#endif
11029#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011030 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011031#endif
11032#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011033 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011034#endif
11035#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011036 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011037#endif
11038#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011039 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011040#endif
11041#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011042 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011043#endif
11044#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011045 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011046#endif
11047#ifdef _CS_XBS5_LP64_OFF64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011048 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011049#endif
11050#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011051 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011052#endif
11053#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011054 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011055#endif
11056#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011057 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011058#endif
11059#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000011060 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000011061#endif
11062#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000011063 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000011064#endif
Fred Draked86ed291999-12-15 15:34:33 +000011065#ifdef _MIPS_CS_AVAIL_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000011066 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000011067#endif
11068#ifdef _MIPS_CS_BASE
Victor Stinner8c62be82010-05-06 00:08:46 +000011069 {"MIPS_CS_BASE", _MIPS_CS_BASE},
Fred Draked86ed291999-12-15 15:34:33 +000011070#endif
11071#ifdef _MIPS_CS_HOSTID
Victor Stinner8c62be82010-05-06 00:08:46 +000011072 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
Fred Draked86ed291999-12-15 15:34:33 +000011073#endif
11074#ifdef _MIPS_CS_HW_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011075 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000011076#endif
11077#ifdef _MIPS_CS_NUM_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000011078 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000011079#endif
11080#ifdef _MIPS_CS_OSREL_MAJ
Victor Stinner8c62be82010-05-06 00:08:46 +000011081 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
Fred Draked86ed291999-12-15 15:34:33 +000011082#endif
11083#ifdef _MIPS_CS_OSREL_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011084 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
Fred Draked86ed291999-12-15 15:34:33 +000011085#endif
11086#ifdef _MIPS_CS_OSREL_PATCH
Victor Stinner8c62be82010-05-06 00:08:46 +000011087 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
Fred Draked86ed291999-12-15 15:34:33 +000011088#endif
11089#ifdef _MIPS_CS_OS_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000011090 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000011091#endif
11092#ifdef _MIPS_CS_OS_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000011093 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000011094#endif
11095#ifdef _MIPS_CS_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000011096 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000011097#endif
11098#ifdef _MIPS_CS_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000011099 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000011100#endif
11101#ifdef _MIPS_CS_VENDOR
Victor Stinner8c62be82010-05-06 00:08:46 +000011102 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
Fred Draked86ed291999-12-15 15:34:33 +000011103#endif
Fred Drakec9680921999-12-13 16:37:25 +000011104};
11105
11106static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011107conv_confstr_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011108{
11109 return conv_confname(arg, valuep, posix_constants_confstr,
11110 sizeof(posix_constants_confstr)
11111 / sizeof(struct constdef));
11112}
11113
Larry Hastings2f936352014-08-05 14:04:04 +100011114
11115/*[clinic input]
11116os.confstr
11117
11118 name: confstr_confname
11119 /
11120
11121Return a string-valued system configuration variable.
11122[clinic start generated code]*/
11123
Larry Hastings2f936352014-08-05 14:04:04 +100011124static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011125os_confstr_impl(PyObject *module, int name)
11126/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
Fred Drakec9680921999-12-13 16:37:25 +000011127{
11128 PyObject *result = NULL;
Victor Stinnercb043522010-09-10 23:49:04 +000011129 char buffer[255];
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011130 size_t len;
Fred Drakec9680921999-12-13 16:37:25 +000011131
Victor Stinnercb043522010-09-10 23:49:04 +000011132 errno = 0;
11133 len = confstr(name, buffer, sizeof(buffer));
11134 if (len == 0) {
11135 if (errno) {
11136 posix_error();
11137 return NULL;
Fred Drakec9680921999-12-13 16:37:25 +000011138 }
11139 else {
Victor Stinnercb043522010-09-10 23:49:04 +000011140 Py_RETURN_NONE;
Fred Drakec9680921999-12-13 16:37:25 +000011141 }
11142 }
Victor Stinnercb043522010-09-10 23:49:04 +000011143
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011144 if (len >= sizeof(buffer)) {
Victor Stinnercbc18f32014-12-05 22:51:51 +010011145 size_t len2;
Victor Stinnercb043522010-09-10 23:49:04 +000011146 char *buf = PyMem_Malloc(len);
11147 if (buf == NULL)
11148 return PyErr_NoMemory();
Victor Stinnercbc18f32014-12-05 22:51:51 +010011149 len2 = confstr(name, buf, len);
11150 assert(len == len2);
Christian Heimes8714cfd2015-04-21 10:57:41 +020011151 result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
Victor Stinnercb043522010-09-10 23:49:04 +000011152 PyMem_Free(buf);
11153 }
11154 else
11155 result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
Fred Drakec9680921999-12-13 16:37:25 +000011156 return result;
11157}
Larry Hastings2f936352014-08-05 14:04:04 +100011158#endif /* HAVE_CONFSTR */
Fred Drakec9680921999-12-13 16:37:25 +000011159
11160
11161#ifdef HAVE_SYSCONF
11162static struct constdef posix_constants_sysconf[] = {
11163#ifdef _SC_2_CHAR_TERM
Victor Stinner8c62be82010-05-06 00:08:46 +000011164 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
Fred Drakec9680921999-12-13 16:37:25 +000011165#endif
11166#ifdef _SC_2_C_BIND
Victor Stinner8c62be82010-05-06 00:08:46 +000011167 {"SC_2_C_BIND", _SC_2_C_BIND},
Fred Drakec9680921999-12-13 16:37:25 +000011168#endif
11169#ifdef _SC_2_C_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011170 {"SC_2_C_DEV", _SC_2_C_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011171#endif
11172#ifdef _SC_2_C_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011173 {"SC_2_C_VERSION", _SC_2_C_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011174#endif
11175#ifdef _SC_2_FORT_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011176 {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011177#endif
11178#ifdef _SC_2_FORT_RUN
Victor Stinner8c62be82010-05-06 00:08:46 +000011179 {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
Fred Drakec9680921999-12-13 16:37:25 +000011180#endif
11181#ifdef _SC_2_LOCALEDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000011182 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
Fred Drakec9680921999-12-13 16:37:25 +000011183#endif
11184#ifdef _SC_2_SW_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011185 {"SC_2_SW_DEV", _SC_2_SW_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011186#endif
11187#ifdef _SC_2_UPE
Victor Stinner8c62be82010-05-06 00:08:46 +000011188 {"SC_2_UPE", _SC_2_UPE},
Fred Drakec9680921999-12-13 16:37:25 +000011189#endif
11190#ifdef _SC_2_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011191 {"SC_2_VERSION", _SC_2_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011192#endif
Fred Draked86ed291999-12-15 15:34:33 +000011193#ifdef _SC_ABI_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011194 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
Fred Draked86ed291999-12-15 15:34:33 +000011195#endif
11196#ifdef _SC_ACL
Victor Stinner8c62be82010-05-06 00:08:46 +000011197 {"SC_ACL", _SC_ACL},
Fred Draked86ed291999-12-15 15:34:33 +000011198#endif
Fred Drakec9680921999-12-13 16:37:25 +000011199#ifdef _SC_AIO_LISTIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011200 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011201#endif
Fred Drakec9680921999-12-13 16:37:25 +000011202#ifdef _SC_AIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011203 {"SC_AIO_MAX", _SC_AIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011204#endif
11205#ifdef _SC_AIO_PRIO_DELTA_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011206 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011207#endif
11208#ifdef _SC_ARG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011209 {"SC_ARG_MAX", _SC_ARG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011210#endif
11211#ifdef _SC_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011212 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011213#endif
11214#ifdef _SC_ATEXIT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011215 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011216#endif
Fred Draked86ed291999-12-15 15:34:33 +000011217#ifdef _SC_AUDIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011218 {"SC_AUDIT", _SC_AUDIT},
Fred Draked86ed291999-12-15 15:34:33 +000011219#endif
Fred Drakec9680921999-12-13 16:37:25 +000011220#ifdef _SC_AVPHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011221 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011222#endif
11223#ifdef _SC_BC_BASE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011224 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011225#endif
11226#ifdef _SC_BC_DIM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011227 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011228#endif
11229#ifdef _SC_BC_SCALE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011230 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011231#endif
11232#ifdef _SC_BC_STRING_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011233 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011234#endif
Fred Draked86ed291999-12-15 15:34:33 +000011235#ifdef _SC_CAP
Victor Stinner8c62be82010-05-06 00:08:46 +000011236 {"SC_CAP", _SC_CAP},
Fred Draked86ed291999-12-15 15:34:33 +000011237#endif
Fred Drakec9680921999-12-13 16:37:25 +000011238#ifdef _SC_CHARCLASS_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011239 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011240#endif
11241#ifdef _SC_CHAR_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011242 {"SC_CHAR_BIT", _SC_CHAR_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011243#endif
11244#ifdef _SC_CHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011245 {"SC_CHAR_MAX", _SC_CHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011246#endif
11247#ifdef _SC_CHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011248 {"SC_CHAR_MIN", _SC_CHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011249#endif
11250#ifdef _SC_CHILD_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011251 {"SC_CHILD_MAX", _SC_CHILD_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011252#endif
11253#ifdef _SC_CLK_TCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011254 {"SC_CLK_TCK", _SC_CLK_TCK},
Fred Drakec9680921999-12-13 16:37:25 +000011255#endif
11256#ifdef _SC_COHER_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011257 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011258#endif
11259#ifdef _SC_COLL_WEIGHTS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011260 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011261#endif
11262#ifdef _SC_DCACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011263 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011264#endif
11265#ifdef _SC_DCACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011266 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011267#endif
11268#ifdef _SC_DCACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011269 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011270#endif
11271#ifdef _SC_DCACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011272 {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011273#endif
11274#ifdef _SC_DCACHE_TBLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011275 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011276#endif
11277#ifdef _SC_DELAYTIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011278 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011279#endif
11280#ifdef _SC_EQUIV_CLASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011281 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011282#endif
11283#ifdef _SC_EXPR_NEST_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011284 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011285#endif
11286#ifdef _SC_FSYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000011287 {"SC_FSYNC", _SC_FSYNC},
Fred Drakec9680921999-12-13 16:37:25 +000011288#endif
11289#ifdef _SC_GETGR_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011290 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011291#endif
11292#ifdef _SC_GETPW_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011293 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011294#endif
11295#ifdef _SC_ICACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011296 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011297#endif
11298#ifdef _SC_ICACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011299 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011300#endif
11301#ifdef _SC_ICACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011302 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011303#endif
11304#ifdef _SC_ICACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011305 {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011306#endif
Fred Draked86ed291999-12-15 15:34:33 +000011307#ifdef _SC_INF
Victor Stinner8c62be82010-05-06 00:08:46 +000011308 {"SC_INF", _SC_INF},
Fred Draked86ed291999-12-15 15:34:33 +000011309#endif
Fred Drakec9680921999-12-13 16:37:25 +000011310#ifdef _SC_INT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011311 {"SC_INT_MAX", _SC_INT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011312#endif
11313#ifdef _SC_INT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011314 {"SC_INT_MIN", _SC_INT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011315#endif
11316#ifdef _SC_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011317 {"SC_IOV_MAX", _SC_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011318#endif
Fred Draked86ed291999-12-15 15:34:33 +000011319#ifdef _SC_IP_SECOPTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011320 {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
Fred Draked86ed291999-12-15 15:34:33 +000011321#endif
Fred Drakec9680921999-12-13 16:37:25 +000011322#ifdef _SC_JOB_CONTROL
Victor Stinner8c62be82010-05-06 00:08:46 +000011323 {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
Fred Drakec9680921999-12-13 16:37:25 +000011324#endif
Fred Draked86ed291999-12-15 15:34:33 +000011325#ifdef _SC_KERN_POINTERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011326 {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
Fred Draked86ed291999-12-15 15:34:33 +000011327#endif
11328#ifdef _SC_KERN_SIM
Victor Stinner8c62be82010-05-06 00:08:46 +000011329 {"SC_KERN_SIM", _SC_KERN_SIM},
Fred Draked86ed291999-12-15 15:34:33 +000011330#endif
Fred Drakec9680921999-12-13 16:37:25 +000011331#ifdef _SC_LINE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011332 {"SC_LINE_MAX", _SC_LINE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011333#endif
11334#ifdef _SC_LOGIN_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011335 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011336#endif
11337#ifdef _SC_LOGNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011338 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011339#endif
11340#ifdef _SC_LONG_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011341 {"SC_LONG_BIT", _SC_LONG_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011342#endif
Fred Draked86ed291999-12-15 15:34:33 +000011343#ifdef _SC_MAC
Victor Stinner8c62be82010-05-06 00:08:46 +000011344 {"SC_MAC", _SC_MAC},
Fred Draked86ed291999-12-15 15:34:33 +000011345#endif
Fred Drakec9680921999-12-13 16:37:25 +000011346#ifdef _SC_MAPPED_FILES
Victor Stinner8c62be82010-05-06 00:08:46 +000011347 {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
Fred Drakec9680921999-12-13 16:37:25 +000011348#endif
11349#ifdef _SC_MAXPID
Victor Stinner8c62be82010-05-06 00:08:46 +000011350 {"SC_MAXPID", _SC_MAXPID},
Fred Drakec9680921999-12-13 16:37:25 +000011351#endif
11352#ifdef _SC_MB_LEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011353 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011354#endif
11355#ifdef _SC_MEMLOCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011356 {"SC_MEMLOCK", _SC_MEMLOCK},
Fred Drakec9680921999-12-13 16:37:25 +000011357#endif
11358#ifdef _SC_MEMLOCK_RANGE
Victor Stinner8c62be82010-05-06 00:08:46 +000011359 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
Fred Drakec9680921999-12-13 16:37:25 +000011360#endif
11361#ifdef _SC_MEMORY_PROTECTION
Victor Stinner8c62be82010-05-06 00:08:46 +000011362 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
Fred Drakec9680921999-12-13 16:37:25 +000011363#endif
11364#ifdef _SC_MESSAGE_PASSING
Victor Stinner8c62be82010-05-06 00:08:46 +000011365 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
Fred Drakec9680921999-12-13 16:37:25 +000011366#endif
Fred Draked86ed291999-12-15 15:34:33 +000011367#ifdef _SC_MMAP_FIXED_ALIGNMENT
Victor Stinner8c62be82010-05-06 00:08:46 +000011368 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
Fred Draked86ed291999-12-15 15:34:33 +000011369#endif
Fred Drakec9680921999-12-13 16:37:25 +000011370#ifdef _SC_MQ_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011371 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011372#endif
11373#ifdef _SC_MQ_PRIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011374 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011375#endif
Fred Draked86ed291999-12-15 15:34:33 +000011376#ifdef _SC_NACLS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011377 {"SC_NACLS_MAX", _SC_NACLS_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000011378#endif
Fred Drakec9680921999-12-13 16:37:25 +000011379#ifdef _SC_NGROUPS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011380 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011381#endif
11382#ifdef _SC_NL_ARGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011383 {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011384#endif
11385#ifdef _SC_NL_LANGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011386 {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011387#endif
11388#ifdef _SC_NL_MSGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011389 {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011390#endif
11391#ifdef _SC_NL_NMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011392 {"SC_NL_NMAX", _SC_NL_NMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011393#endif
11394#ifdef _SC_NL_SETMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011395 {"SC_NL_SETMAX", _SC_NL_SETMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011396#endif
11397#ifdef _SC_NL_TEXTMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011398 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011399#endif
11400#ifdef _SC_NPROCESSORS_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011401 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
Fred Drakec9680921999-12-13 16:37:25 +000011402#endif
11403#ifdef _SC_NPROCESSORS_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011404 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
Fred Drakec9680921999-12-13 16:37:25 +000011405#endif
Fred Draked86ed291999-12-15 15:34:33 +000011406#ifdef _SC_NPROC_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011407 {"SC_NPROC_CONF", _SC_NPROC_CONF},
Fred Draked86ed291999-12-15 15:34:33 +000011408#endif
11409#ifdef _SC_NPROC_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011410 {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
Fred Draked86ed291999-12-15 15:34:33 +000011411#endif
Fred Drakec9680921999-12-13 16:37:25 +000011412#ifdef _SC_NZERO
Victor Stinner8c62be82010-05-06 00:08:46 +000011413 {"SC_NZERO", _SC_NZERO},
Fred Drakec9680921999-12-13 16:37:25 +000011414#endif
11415#ifdef _SC_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011416 {"SC_OPEN_MAX", _SC_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011417#endif
11418#ifdef _SC_PAGESIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011419 {"SC_PAGESIZE", _SC_PAGESIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011420#endif
11421#ifdef _SC_PAGE_SIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011422 {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011423#endif
11424#ifdef _SC_PASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011425 {"SC_PASS_MAX", _SC_PASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011426#endif
11427#ifdef _SC_PHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011428 {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011429#endif
11430#ifdef _SC_PII
Victor Stinner8c62be82010-05-06 00:08:46 +000011431 {"SC_PII", _SC_PII},
Fred Drakec9680921999-12-13 16:37:25 +000011432#endif
11433#ifdef _SC_PII_INTERNET
Victor Stinner8c62be82010-05-06 00:08:46 +000011434 {"SC_PII_INTERNET", _SC_PII_INTERNET},
Fred Drakec9680921999-12-13 16:37:25 +000011435#endif
11436#ifdef _SC_PII_INTERNET_DGRAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011437 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
Fred Drakec9680921999-12-13 16:37:25 +000011438#endif
11439#ifdef _SC_PII_INTERNET_STREAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011440 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
Fred Drakec9680921999-12-13 16:37:25 +000011441#endif
11442#ifdef _SC_PII_OSI
Victor Stinner8c62be82010-05-06 00:08:46 +000011443 {"SC_PII_OSI", _SC_PII_OSI},
Fred Drakec9680921999-12-13 16:37:25 +000011444#endif
11445#ifdef _SC_PII_OSI_CLTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011446 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
Fred Drakec9680921999-12-13 16:37:25 +000011447#endif
11448#ifdef _SC_PII_OSI_COTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011449 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
Fred Drakec9680921999-12-13 16:37:25 +000011450#endif
11451#ifdef _SC_PII_OSI_M
Victor Stinner8c62be82010-05-06 00:08:46 +000011452 {"SC_PII_OSI_M", _SC_PII_OSI_M},
Fred Drakec9680921999-12-13 16:37:25 +000011453#endif
11454#ifdef _SC_PII_SOCKET
Victor Stinner8c62be82010-05-06 00:08:46 +000011455 {"SC_PII_SOCKET", _SC_PII_SOCKET},
Fred Drakec9680921999-12-13 16:37:25 +000011456#endif
11457#ifdef _SC_PII_XTI
Victor Stinner8c62be82010-05-06 00:08:46 +000011458 {"SC_PII_XTI", _SC_PII_XTI},
Fred Drakec9680921999-12-13 16:37:25 +000011459#endif
11460#ifdef _SC_POLL
Victor Stinner8c62be82010-05-06 00:08:46 +000011461 {"SC_POLL", _SC_POLL},
Fred Drakec9680921999-12-13 16:37:25 +000011462#endif
11463#ifdef _SC_PRIORITIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011464 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011465#endif
11466#ifdef _SC_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011467 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011468#endif
11469#ifdef _SC_REALTIME_SIGNALS
Victor Stinner8c62be82010-05-06 00:08:46 +000011470 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
Fred Drakec9680921999-12-13 16:37:25 +000011471#endif
11472#ifdef _SC_RE_DUP_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011473 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011474#endif
11475#ifdef _SC_RTSIG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011476 {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011477#endif
11478#ifdef _SC_SAVED_IDS
Victor Stinner8c62be82010-05-06 00:08:46 +000011479 {"SC_SAVED_IDS", _SC_SAVED_IDS},
Fred Drakec9680921999-12-13 16:37:25 +000011480#endif
11481#ifdef _SC_SCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011482 {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011483#endif
11484#ifdef _SC_SCHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011485 {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011486#endif
11487#ifdef _SC_SELECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011488 {"SC_SELECT", _SC_SELECT},
Fred Drakec9680921999-12-13 16:37:25 +000011489#endif
11490#ifdef _SC_SEMAPHORES
Victor Stinner8c62be82010-05-06 00:08:46 +000011491 {"SC_SEMAPHORES", _SC_SEMAPHORES},
Fred Drakec9680921999-12-13 16:37:25 +000011492#endif
11493#ifdef _SC_SEM_NSEMS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011494 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011495#endif
11496#ifdef _SC_SEM_VALUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011497 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011498#endif
11499#ifdef _SC_SHARED_MEMORY_OBJECTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011500 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
Fred Drakec9680921999-12-13 16:37:25 +000011501#endif
11502#ifdef _SC_SHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011503 {"SC_SHRT_MAX", _SC_SHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011504#endif
11505#ifdef _SC_SHRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011506 {"SC_SHRT_MIN", _SC_SHRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011507#endif
11508#ifdef _SC_SIGQUEUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011509 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011510#endif
11511#ifdef _SC_SIGRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011512 {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011513#endif
11514#ifdef _SC_SIGRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011515 {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011516#endif
Fred Draked86ed291999-12-15 15:34:33 +000011517#ifdef _SC_SOFTPOWER
Victor Stinner8c62be82010-05-06 00:08:46 +000011518 {"SC_SOFTPOWER", _SC_SOFTPOWER},
Fred Draked86ed291999-12-15 15:34:33 +000011519#endif
Fred Drakec9680921999-12-13 16:37:25 +000011520#ifdef _SC_SPLIT_CACHE
Victor Stinner8c62be82010-05-06 00:08:46 +000011521 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
Fred Drakec9680921999-12-13 16:37:25 +000011522#endif
11523#ifdef _SC_SSIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011524 {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011525#endif
11526#ifdef _SC_STACK_PROT
Victor Stinner8c62be82010-05-06 00:08:46 +000011527 {"SC_STACK_PROT", _SC_STACK_PROT},
Fred Drakec9680921999-12-13 16:37:25 +000011528#endif
11529#ifdef _SC_STREAM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011530 {"SC_STREAM_MAX", _SC_STREAM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011531#endif
11532#ifdef _SC_SYNCHRONIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011533 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011534#endif
11535#ifdef _SC_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011536 {"SC_THREADS", _SC_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011537#endif
11538#ifdef _SC_THREAD_ATTR_STACKADDR
Victor Stinner8c62be82010-05-06 00:08:46 +000011539 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
Fred Drakec9680921999-12-13 16:37:25 +000011540#endif
11541#ifdef _SC_THREAD_ATTR_STACKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011542 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011543#endif
11544#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011545 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011546#endif
11547#ifdef _SC_THREAD_KEYS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011548 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011549#endif
11550#ifdef _SC_THREAD_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011551 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011552#endif
11553#ifdef _SC_THREAD_PRIO_INHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011554 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
Fred Drakec9680921999-12-13 16:37:25 +000011555#endif
11556#ifdef _SC_THREAD_PRIO_PROTECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011557 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
Fred Drakec9680921999-12-13 16:37:25 +000011558#endif
11559#ifdef _SC_THREAD_PROCESS_SHARED
Victor Stinner8c62be82010-05-06 00:08:46 +000011560 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
Fred Drakec9680921999-12-13 16:37:25 +000011561#endif
11562#ifdef _SC_THREAD_SAFE_FUNCTIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011563 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011564#endif
11565#ifdef _SC_THREAD_STACK_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011566 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011567#endif
11568#ifdef _SC_THREAD_THREADS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011569 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011570#endif
11571#ifdef _SC_TIMERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011572 {"SC_TIMERS", _SC_TIMERS},
Fred Drakec9680921999-12-13 16:37:25 +000011573#endif
11574#ifdef _SC_TIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011575 {"SC_TIMER_MAX", _SC_TIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011576#endif
11577#ifdef _SC_TTY_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011578 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011579#endif
11580#ifdef _SC_TZNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011581 {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011582#endif
11583#ifdef _SC_T_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011584 {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011585#endif
11586#ifdef _SC_UCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011587 {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011588#endif
11589#ifdef _SC_UINT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011590 {"SC_UINT_MAX", _SC_UINT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011591#endif
11592#ifdef _SC_UIO_MAXIOV
Victor Stinner8c62be82010-05-06 00:08:46 +000011593 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
Fred Drakec9680921999-12-13 16:37:25 +000011594#endif
11595#ifdef _SC_ULONG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011596 {"SC_ULONG_MAX", _SC_ULONG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011597#endif
11598#ifdef _SC_USHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011599 {"SC_USHRT_MAX", _SC_USHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011600#endif
11601#ifdef _SC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011602 {"SC_VERSION", _SC_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011603#endif
11604#ifdef _SC_WORD_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011605 {"SC_WORD_BIT", _SC_WORD_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011606#endif
11607#ifdef _SC_XBS5_ILP32_OFF32
Victor Stinner8c62be82010-05-06 00:08:46 +000011608 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
Fred Drakec9680921999-12-13 16:37:25 +000011609#endif
11610#ifdef _SC_XBS5_ILP32_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011611 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011612#endif
11613#ifdef _SC_XBS5_LP64_OFF64
Victor Stinner8c62be82010-05-06 00:08:46 +000011614 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
Fred Drakec9680921999-12-13 16:37:25 +000011615#endif
11616#ifdef _SC_XBS5_LPBIG_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011617 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011618#endif
11619#ifdef _SC_XOPEN_CRYPT
Victor Stinner8c62be82010-05-06 00:08:46 +000011620 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
Fred Drakec9680921999-12-13 16:37:25 +000011621#endif
11622#ifdef _SC_XOPEN_ENH_I18N
Victor Stinner8c62be82010-05-06 00:08:46 +000011623 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
Fred Drakec9680921999-12-13 16:37:25 +000011624#endif
11625#ifdef _SC_XOPEN_LEGACY
Victor Stinner8c62be82010-05-06 00:08:46 +000011626 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
Fred Drakec9680921999-12-13 16:37:25 +000011627#endif
11628#ifdef _SC_XOPEN_REALTIME
Victor Stinner8c62be82010-05-06 00:08:46 +000011629 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
Fred Drakec9680921999-12-13 16:37:25 +000011630#endif
11631#ifdef _SC_XOPEN_REALTIME_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011632 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011633#endif
11634#ifdef _SC_XOPEN_SHM
Victor Stinner8c62be82010-05-06 00:08:46 +000011635 {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
Fred Drakec9680921999-12-13 16:37:25 +000011636#endif
11637#ifdef _SC_XOPEN_UNIX
Victor Stinner8c62be82010-05-06 00:08:46 +000011638 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
Fred Drakec9680921999-12-13 16:37:25 +000011639#endif
11640#ifdef _SC_XOPEN_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011641 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011642#endif
11643#ifdef _SC_XOPEN_XCU_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011644 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011645#endif
11646#ifdef _SC_XOPEN_XPG2
Victor Stinner8c62be82010-05-06 00:08:46 +000011647 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
Fred Drakec9680921999-12-13 16:37:25 +000011648#endif
11649#ifdef _SC_XOPEN_XPG3
Victor Stinner8c62be82010-05-06 00:08:46 +000011650 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
Fred Drakec9680921999-12-13 16:37:25 +000011651#endif
11652#ifdef _SC_XOPEN_XPG4
Victor Stinner8c62be82010-05-06 00:08:46 +000011653 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
Fred Drakec9680921999-12-13 16:37:25 +000011654#endif
11655};
11656
11657static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011658conv_sysconf_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011659{
11660 return conv_confname(arg, valuep, posix_constants_sysconf,
11661 sizeof(posix_constants_sysconf)
11662 / sizeof(struct constdef));
11663}
11664
Larry Hastings2f936352014-08-05 14:04:04 +100011665
11666/*[clinic input]
11667os.sysconf -> long
11668 name: sysconf_confname
11669 /
11670
11671Return an integer-valued system configuration variable.
11672[clinic start generated code]*/
11673
Larry Hastings2f936352014-08-05 14:04:04 +100011674static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011675os_sysconf_impl(PyObject *module, int name)
11676/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011677{
11678 long value;
11679
11680 errno = 0;
11681 value = sysconf(name);
11682 if (value == -1 && errno != 0)
11683 posix_error();
11684 return value;
11685}
11686#endif /* HAVE_SYSCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011687
11688
Fred Drakebec628d1999-12-15 18:31:10 +000011689/* This code is used to ensure that the tables of configuration value names
Serhiy Storchaka56a6d852014-12-01 18:28:43 +020011690 * are in sorted order as required by conv_confname(), and also to build
Fred Drakebec628d1999-12-15 18:31:10 +000011691 * the exported dictionaries that are used to publish information about the
11692 * names available on the host platform.
11693 *
11694 * Sorting the table at runtime ensures that the table is properly ordered
11695 * when used, even for platforms we're not able to test on. It also makes
11696 * it easier to add additional entries to the tables.
Fred Draked86ed291999-12-15 15:34:33 +000011697 */
Fred Drakebec628d1999-12-15 18:31:10 +000011698
11699static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011700cmp_constdefs(const void *v1, const void *v2)
Fred Drakebec628d1999-12-15 18:31:10 +000011701{
11702 const struct constdef *c1 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011703 (const struct constdef *) v1;
Fred Drakebec628d1999-12-15 18:31:10 +000011704 const struct constdef *c2 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011705 (const struct constdef *) v2;
Fred Drakebec628d1999-12-15 18:31:10 +000011706
11707 return strcmp(c1->name, c2->name);
11708}
11709
11710static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011711setup_confname_table(struct constdef *table, size_t tablesize,
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011712 const char *tablename, PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011713{
Fred Drakebec628d1999-12-15 18:31:10 +000011714 PyObject *d = NULL;
Barry Warsaw3155db32000-04-13 15:20:40 +000011715 size_t i;
Fred Drakebec628d1999-12-15 18:31:10 +000011716
11717 qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
11718 d = PyDict_New();
Barry Warsaw3155db32000-04-13 15:20:40 +000011719 if (d == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +000011720 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011721
Barry Warsaw3155db32000-04-13 15:20:40 +000011722 for (i=0; i < tablesize; ++i) {
Victor Stinner8c62be82010-05-06 00:08:46 +000011723 PyObject *o = PyLong_FromLong(table[i].value);
11724 if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
11725 Py_XDECREF(o);
11726 Py_DECREF(d);
11727 return -1;
11728 }
11729 Py_DECREF(o);
Fred Draked86ed291999-12-15 15:34:33 +000011730 }
Fred Drake4d1e64b2002-04-15 19:40:07 +000011731 return PyModule_AddObject(module, tablename, d);
Fred Draked86ed291999-12-15 15:34:33 +000011732}
11733
Fred Drakebec628d1999-12-15 18:31:10 +000011734/* Return -1 on failure, 0 on success. */
11735static int
Fred Drake4d1e64b2002-04-15 19:40:07 +000011736setup_confname_tables(PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011737{
11738#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
Fred Drakebec628d1999-12-15 18:31:10 +000011739 if (setup_confname_table(posix_constants_pathconf,
Fred Draked86ed291999-12-15 15:34:33 +000011740 sizeof(posix_constants_pathconf)
11741 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011742 "pathconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011743 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011744#endif
11745#ifdef HAVE_CONFSTR
Fred Drakebec628d1999-12-15 18:31:10 +000011746 if (setup_confname_table(posix_constants_confstr,
Fred Draked86ed291999-12-15 15:34:33 +000011747 sizeof(posix_constants_confstr)
11748 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011749 "confstr_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011750 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011751#endif
11752#ifdef HAVE_SYSCONF
Fred Drakebec628d1999-12-15 18:31:10 +000011753 if (setup_confname_table(posix_constants_sysconf,
Fred Draked86ed291999-12-15 15:34:33 +000011754 sizeof(posix_constants_sysconf)
11755 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011756 "sysconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011757 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011758#endif
Fred Drakebec628d1999-12-15 18:31:10 +000011759 return 0;
Fred Draked86ed291999-12-15 15:34:33 +000011760}
Fred Draked86ed291999-12-15 15:34:33 +000011761
11762
Larry Hastings2f936352014-08-05 14:04:04 +100011763/*[clinic input]
11764os.abort
11765
11766Abort the interpreter immediately.
11767
11768This function 'dumps core' or otherwise fails in the hardest way possible
11769on the hosting operating system. This function never returns.
11770[clinic start generated code]*/
11771
Larry Hastings2f936352014-08-05 14:04:04 +100011772static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011773os_abort_impl(PyObject *module)
11774/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011775{
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011776 abort();
11777 /*NOTREACHED*/
Victor Stinner9a2329f2016-12-05 17:56:36 +010011778#ifndef __clang__
11779 /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
11780 GCC emits a warning without "return NULL;" (compiler bug?), but Clang
11781 is smarter and emits a warning on the return. */
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011782 Py_FatalError("abort() called from Python code didn't abort!");
11783 return NULL;
Victor Stinner9a2329f2016-12-05 17:56:36 +010011784#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011785}
Fred Drakebec628d1999-12-15 18:31:10 +000011786
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011787#ifdef MS_WINDOWS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011788/* Grab ShellExecute dynamically from shell32 */
11789static int has_ShellExecute = -1;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011790static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
11791 LPCWSTR, INT);
11792static int
11793check_ShellExecute()
11794{
11795 HINSTANCE hShell32;
11796
11797 /* only recheck */
11798 if (-1 == has_ShellExecute) {
11799 Py_BEGIN_ALLOW_THREADS
Victor Stinnera9912152017-10-13 13:46:57 -070011800 /* Security note: this call is not vulnerable to "DLL hijacking".
11801 SHELL32 is part of "KnownDLLs" and so Windows always load
11802 the system SHELL32.DLL, even if there is another SHELL32.DLL
11803 in the DLL search path. */
Steve Dower7d0e0c92015-01-24 08:18:24 -080011804 hShell32 = LoadLibraryW(L"SHELL32");
Steve Dower7d0e0c92015-01-24 08:18:24 -080011805 if (hShell32) {
Steve Dower7d0e0c92015-01-24 08:18:24 -080011806 *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
11807 "ShellExecuteW");
Steve Dowercc16be82016-09-08 10:35:16 -070011808 has_ShellExecute = Py_ShellExecuteW != NULL;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011809 } else {
11810 has_ShellExecute = 0;
11811 }
Tony Roberts4860f012019-02-02 18:16:42 +010011812 Py_END_ALLOW_THREADS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011813 }
11814 return has_ShellExecute;
11815}
11816
11817
Steve Dowercc16be82016-09-08 10:35:16 -070011818/*[clinic input]
11819os.startfile
11820 filepath: path_t
11821 operation: Py_UNICODE = NULL
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +000011822
Steve Dowercc16be82016-09-08 10:35:16 -070011823Start a file with its associated application.
11824
11825When "operation" is not specified or "open", this acts like
11826double-clicking the file in Explorer, or giving the file name as an
11827argument to the DOS "start" command: the file is opened with whatever
11828application (if any) its extension is associated.
11829When another "operation" is given, it specifies what should be done with
11830the file. A typical operation is "print".
11831
11832startfile returns as soon as the associated application is launched.
11833There is no option to wait for the application to close, and no way
11834to retrieve the application's exit status.
11835
11836The filepath is relative to the current directory. If you want to use
11837an absolute path, make sure the first character is not a slash ("/");
11838the underlying Win32 ShellExecute function doesn't work if it is.
11839[clinic start generated code]*/
11840
11841static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +020011842os_startfile_impl(PyObject *module, path_t *filepath,
11843 const Py_UNICODE *operation)
Serhiy Storchaka279f4462019-09-14 12:24:05 +030011844/*[clinic end generated code: output=66dc311c94d50797 input=c940888a5390f039]*/
Steve Dowercc16be82016-09-08 10:35:16 -070011845{
11846 HINSTANCE rc;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011847
11848 if(!check_ShellExecute()) {
11849 /* If the OS doesn't have ShellExecute, return a
11850 NotImplementedError. */
11851 return PyErr_Format(PyExc_NotImplementedError,
11852 "startfile not available on this platform");
11853 }
11854
Saiyang Gou7514f4f2020-02-12 23:47:42 -080011855 if (PySys_Audit("os.startfile", "Ou", filepath->object, operation) < 0) {
Saiyang Gou95f60012020-02-04 16:15:00 -080011856 return NULL;
11857 }
11858
Victor Stinner8c62be82010-05-06 00:08:46 +000011859 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -070011860 rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
Steve Dower7d0e0c92015-01-24 08:18:24 -080011861 NULL, NULL, SW_SHOWNORMAL);
Victor Stinner8c62be82010-05-06 00:08:46 +000011862 Py_END_ALLOW_THREADS
11863
Victor Stinner8c62be82010-05-06 00:08:46 +000011864 if (rc <= (HINSTANCE)32) {
Steve Dowercc16be82016-09-08 10:35:16 -070011865 win32_error_object("startfile", filepath->object);
Victor Stinnereb5657a2011-09-30 01:44:27 +020011866 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000011867 }
Steve Dowercc16be82016-09-08 10:35:16 -070011868 Py_RETURN_NONE;
Tim Petersf58a7aa2000-09-22 10:05:54 +000011869}
Larry Hastings2f936352014-08-05 14:04:04 +100011870#endif /* MS_WINDOWS */
11871
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011872
Martin v. Löwis438b5342002-12-27 10:16:42 +000011873#ifdef HAVE_GETLOADAVG
Larry Hastings2f936352014-08-05 14:04:04 +100011874/*[clinic input]
11875os.getloadavg
11876
11877Return average recent system load information.
11878
11879Return the number of processes in the system run queue averaged over
11880the last 1, 5, and 15 minutes as a tuple of three floats.
11881Raises OSError if the load average was unobtainable.
11882[clinic start generated code]*/
11883
Larry Hastings2f936352014-08-05 14:04:04 +100011884static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011885os_getloadavg_impl(PyObject *module)
11886/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
Martin v. Löwis438b5342002-12-27 10:16:42 +000011887{
11888 double loadavg[3];
Martin v. Löwis438b5342002-12-27 10:16:42 +000011889 if (getloadavg(loadavg, 3)!=3) {
Stefan Krah0e803b32010-11-26 16:16:47 +000011890 PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
11891 return NULL;
Martin v. Löwis438b5342002-12-27 10:16:42 +000011892 } else
Stefan Krah0e803b32010-11-26 16:16:47 +000011893 return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
Martin v. Löwis438b5342002-12-27 10:16:42 +000011894}
Larry Hastings2f936352014-08-05 14:04:04 +100011895#endif /* HAVE_GETLOADAVG */
Martin v. Löwis438b5342002-12-27 10:16:42 +000011896
Larry Hastings2f936352014-08-05 14:04:04 +100011897
11898/*[clinic input]
11899os.device_encoding
11900 fd: int
11901
11902Return a string describing the encoding of a terminal's file descriptor.
11903
11904The file descriptor must be attached to a terminal.
11905If the device is not a terminal, return None.
11906[clinic start generated code]*/
11907
Larry Hastings2f936352014-08-05 14:04:04 +100011908static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011909os_device_encoding_impl(PyObject *module, int fd)
11910/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011911{
Brett Cannonefb00c02012-02-29 18:31:31 -050011912 return _Py_device_encoding(fd);
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +000011913}
11914
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011915
Larry Hastings2f936352014-08-05 14:04:04 +100011916#ifdef HAVE_SETRESUID
11917/*[clinic input]
11918os.setresuid
11919
11920 ruid: uid_t
11921 euid: uid_t
11922 suid: uid_t
11923 /
11924
11925Set the current process's real, effective, and saved user ids.
11926[clinic start generated code]*/
11927
Larry Hastings2f936352014-08-05 14:04:04 +100011928static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011929os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
11930/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011931{
Victor Stinner8c62be82010-05-06 00:08:46 +000011932 if (setresuid(ruid, euid, suid) < 0)
11933 return posix_error();
11934 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011935}
Larry Hastings2f936352014-08-05 14:04:04 +100011936#endif /* HAVE_SETRESUID */
11937
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011938
11939#ifdef HAVE_SETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011940/*[clinic input]
11941os.setresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011942
Larry Hastings2f936352014-08-05 14:04:04 +100011943 rgid: gid_t
11944 egid: gid_t
11945 sgid: gid_t
11946 /
11947
11948Set the current process's real, effective, and saved group ids.
11949[clinic start generated code]*/
11950
Larry Hastings2f936352014-08-05 14:04:04 +100011951static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011952os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
11953/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011954{
Victor Stinner8c62be82010-05-06 00:08:46 +000011955 if (setresgid(rgid, egid, sgid) < 0)
11956 return posix_error();
11957 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011958}
Larry Hastings2f936352014-08-05 14:04:04 +100011959#endif /* HAVE_SETRESGID */
11960
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011961
11962#ifdef HAVE_GETRESUID
Larry Hastings2f936352014-08-05 14:04:04 +100011963/*[clinic input]
11964os.getresuid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011965
Larry Hastings2f936352014-08-05 14:04:04 +100011966Return a tuple of the current process's real, effective, and saved user ids.
11967[clinic start generated code]*/
11968
Larry Hastings2f936352014-08-05 14:04:04 +100011969static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011970os_getresuid_impl(PyObject *module)
11971/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011972{
Victor Stinner8c62be82010-05-06 00:08:46 +000011973 uid_t ruid, euid, suid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011974 if (getresuid(&ruid, &euid, &suid) < 0)
11975 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011976 return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
11977 _PyLong_FromUid(euid),
11978 _PyLong_FromUid(suid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011979}
Larry Hastings2f936352014-08-05 14:04:04 +100011980#endif /* HAVE_GETRESUID */
11981
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011982
11983#ifdef HAVE_GETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011984/*[clinic input]
11985os.getresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011986
Larry Hastings2f936352014-08-05 14:04:04 +100011987Return a tuple of the current process's real, effective, and saved group ids.
11988[clinic start generated code]*/
11989
Larry Hastings2f936352014-08-05 14:04:04 +100011990static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011991os_getresgid_impl(PyObject *module)
11992/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011993{
11994 gid_t rgid, egid, sgid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011995 if (getresgid(&rgid, &egid, &sgid) < 0)
11996 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011997 return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
11998 _PyLong_FromGid(egid),
11999 _PyLong_FromGid(sgid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012000}
Larry Hastings2f936352014-08-05 14:04:04 +100012001#endif /* HAVE_GETRESGID */
12002
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000012003
Benjamin Peterson9428d532011-09-14 11:45:52 -040012004#ifdef USE_XATTRS
Larry Hastings2f936352014-08-05 14:04:04 +100012005/*[clinic input]
12006os.getxattr
Benjamin Peterson799bd802011-08-31 22:15:17 -040012007
Larry Hastings2f936352014-08-05 14:04:04 +100012008 path: path_t(allow_fd=True)
12009 attribute: path_t
12010 *
12011 follow_symlinks: bool = True
12012
12013Return the value of extended attribute attribute on path.
12014
BNMetricsb9427072018-11-02 15:20:19 +000012015path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012016If follow_symlinks is False, and the last element of the path is a symbolic
12017 link, getxattr will examine the symbolic link itself instead of the file
12018 the link points to.
12019
12020[clinic start generated code]*/
12021
Larry Hastings2f936352014-08-05 14:04:04 +100012022static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012023os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012024 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012025/*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012026{
12027 Py_ssize_t i;
12028 PyObject *buffer = NULL;
12029
12030 if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
12031 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012032
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012033 if (PySys_Audit("os.getxattr", "OO", path->object, attribute->object) < 0) {
12034 return NULL;
12035 }
12036
Larry Hastings9cf065c2012-06-22 16:30:09 -070012037 for (i = 0; ; i++) {
12038 void *ptr;
12039 ssize_t result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012040 static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
Larry Hastings9cf065c2012-06-22 16:30:09 -070012041 Py_ssize_t buffer_size = buffer_sizes[i];
12042 if (!buffer_size) {
Larry Hastings2f936352014-08-05 14:04:04 +100012043 path_error(path);
12044 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012045 }
12046 buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
12047 if (!buffer)
Larry Hastings2f936352014-08-05 14:04:04 +100012048 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012049 ptr = PyBytes_AS_STRING(buffer);
Benjamin Peterson799bd802011-08-31 22:15:17 -040012050
Larry Hastings9cf065c2012-06-22 16:30:09 -070012051 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012052 if (path->fd >= 0)
12053 result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012054 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100012055 result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012056 else
Larry Hastings2f936352014-08-05 14:04:04 +100012057 result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012058 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012059
Larry Hastings9cf065c2012-06-22 16:30:09 -070012060 if (result < 0) {
12061 Py_DECREF(buffer);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012062 if (errno == ERANGE)
12063 continue;
Larry Hastings2f936352014-08-05 14:04:04 +100012064 path_error(path);
12065 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012066 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012067
Larry Hastings9cf065c2012-06-22 16:30:09 -070012068 if (result != buffer_size) {
12069 /* Can only shrink. */
12070 _PyBytes_Resize(&buffer, result);
12071 }
12072 break;
12073 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012074
Larry Hastings9cf065c2012-06-22 16:30:09 -070012075 return buffer;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012076}
12077
Larry Hastings2f936352014-08-05 14:04:04 +100012078
12079/*[clinic input]
12080os.setxattr
12081
12082 path: path_t(allow_fd=True)
12083 attribute: path_t
12084 value: Py_buffer
12085 flags: int = 0
12086 *
12087 follow_symlinks: bool = True
12088
12089Set extended attribute attribute on path to value.
12090
BNMetricsb9427072018-11-02 15:20:19 +000012091path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012092If follow_symlinks is False, and the last element of the path is a symbolic
12093 link, setxattr will modify the symbolic link itself instead of the file
12094 the link points to.
12095
12096[clinic start generated code]*/
12097
Benjamin Peterson799bd802011-08-31 22:15:17 -040012098static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012099os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012100 Py_buffer *value, int flags, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012101/*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
Benjamin Peterson799bd802011-08-31 22:15:17 -040012102{
Larry Hastings2f936352014-08-05 14:04:04 +100012103 ssize_t result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012104
Larry Hastings2f936352014-08-05 14:04:04 +100012105 if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
Benjamin Peterson799bd802011-08-31 22:15:17 -040012106 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012107
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012108 if (PySys_Audit("os.setxattr", "OOy#i", path->object, attribute->object,
12109 value->buf, value->len, flags) < 0) {
12110 return NULL;
12111 }
12112
Benjamin Peterson799bd802011-08-31 22:15:17 -040012113 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012114 if (path->fd > -1)
12115 result = fsetxattr(path->fd, attribute->narrow,
12116 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012117 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100012118 result = setxattr(path->narrow, attribute->narrow,
12119 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012120 else
Larry Hastings2f936352014-08-05 14:04:04 +100012121 result = lsetxattr(path->narrow, attribute->narrow,
12122 value->buf, value->len, flags);
Benjamin Peterson799bd802011-08-31 22:15:17 -040012123 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012124
Larry Hastings9cf065c2012-06-22 16:30:09 -070012125 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100012126 path_error(path);
12127 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012128 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012129
Larry Hastings2f936352014-08-05 14:04:04 +100012130 Py_RETURN_NONE;
12131}
12132
12133
12134/*[clinic input]
12135os.removexattr
12136
12137 path: path_t(allow_fd=True)
12138 attribute: path_t
12139 *
12140 follow_symlinks: bool = True
12141
12142Remove extended attribute attribute on path.
12143
BNMetricsb9427072018-11-02 15:20:19 +000012144path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012145If follow_symlinks is False, and the last element of the path is a symbolic
12146 link, removexattr will modify the symbolic link itself instead of the file
12147 the link points to.
12148
12149[clinic start generated code]*/
12150
Larry Hastings2f936352014-08-05 14:04:04 +100012151static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012152os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012153 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012154/*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012155{
12156 ssize_t result;
12157
12158 if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
12159 return NULL;
12160
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012161 if (PySys_Audit("os.removexattr", "OO", path->object, attribute->object) < 0) {
12162 return NULL;
12163 }
12164
Larry Hastings2f936352014-08-05 14:04:04 +100012165 Py_BEGIN_ALLOW_THREADS;
12166 if (path->fd > -1)
12167 result = fremovexattr(path->fd, attribute->narrow);
12168 else if (follow_symlinks)
12169 result = removexattr(path->narrow, attribute->narrow);
12170 else
12171 result = lremovexattr(path->narrow, attribute->narrow);
12172 Py_END_ALLOW_THREADS;
12173
12174 if (result) {
12175 return path_error(path);
12176 }
12177
12178 Py_RETURN_NONE;
12179}
12180
12181
12182/*[clinic input]
12183os.listxattr
12184
12185 path: path_t(allow_fd=True, nullable=True) = None
12186 *
12187 follow_symlinks: bool = True
12188
12189Return a list of extended attributes on path.
12190
BNMetricsb9427072018-11-02 15:20:19 +000012191path may be either None, a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012192if path is None, listxattr will examine the current directory.
12193If follow_symlinks is False, and the last element of the path is a symbolic
12194 link, listxattr will examine the symbolic link itself instead of the file
12195 the link points to.
12196[clinic start generated code]*/
12197
Larry Hastings2f936352014-08-05 14:04:04 +100012198static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012199os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012200/*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012201{
Larry Hastings9cf065c2012-06-22 16:30:09 -070012202 Py_ssize_t i;
12203 PyObject *result = NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100012204 const char *name;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012205 char *buffer = NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012206
Larry Hastings2f936352014-08-05 14:04:04 +100012207 if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
Larry Hastings9cf065c2012-06-22 16:30:09 -070012208 goto exit;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012209
Saiyang Gou7514f4f2020-02-12 23:47:42 -080012210 if (PySys_Audit("os.listxattr", "(O)",
12211 path->object ? path->object : Py_None) < 0) {
12212 return NULL;
12213 }
12214
Larry Hastings2f936352014-08-05 14:04:04 +100012215 name = path->narrow ? path->narrow : ".";
12216
Larry Hastings9cf065c2012-06-22 16:30:09 -070012217 for (i = 0; ; i++) {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012218 const char *start, *trace, *end;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012219 ssize_t length;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012220 static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
Larry Hastings9cf065c2012-06-22 16:30:09 -070012221 Py_ssize_t buffer_size = buffer_sizes[i];
12222 if (!buffer_size) {
Christian Heimes3b9493b2012-09-23 16:11:15 +020012223 /* ERANGE */
Larry Hastings2f936352014-08-05 14:04:04 +100012224 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012225 break;
12226 }
12227 buffer = PyMem_MALLOC(buffer_size);
12228 if (!buffer) {
12229 PyErr_NoMemory();
12230 break;
12231 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012232
Larry Hastings9cf065c2012-06-22 16:30:09 -070012233 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012234 if (path->fd > -1)
12235 length = flistxattr(path->fd, buffer, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012236 else if (follow_symlinks)
12237 length = listxattr(name, buffer, buffer_size);
12238 else
12239 length = llistxattr(name, buffer, buffer_size);
12240 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012241
Larry Hastings9cf065c2012-06-22 16:30:09 -070012242 if (length < 0) {
Antoine Pitrou7f987392013-05-13 19:46:29 +020012243 if (errno == ERANGE) {
12244 PyMem_FREE(buffer);
Benjamin Petersondedac522013-05-13 19:55:40 -050012245 buffer = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012246 continue;
Antoine Pitrou7f987392013-05-13 19:46:29 +020012247 }
Larry Hastings2f936352014-08-05 14:04:04 +100012248 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012249 break;
12250 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012251
Larry Hastings9cf065c2012-06-22 16:30:09 -070012252 result = PyList_New(0);
12253 if (!result) {
12254 goto exit;
12255 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012256
Larry Hastings9cf065c2012-06-22 16:30:09 -070012257 end = buffer + length;
12258 for (trace = start = buffer; trace != end; trace++) {
12259 if (!*trace) {
12260 int error;
12261 PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
12262 trace - start);
12263 if (!attribute) {
12264 Py_DECREF(result);
12265 result = NULL;
12266 goto exit;
12267 }
12268 error = PyList_Append(result, attribute);
12269 Py_DECREF(attribute);
12270 if (error) {
12271 Py_DECREF(result);
12272 result = NULL;
12273 goto exit;
12274 }
12275 start = trace + 1;
12276 }
12277 }
12278 break;
12279 }
12280exit:
Larry Hastings9cf065c2012-06-22 16:30:09 -070012281 if (buffer)
12282 PyMem_FREE(buffer);
12283 return result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012284}
Benjamin Peterson9428d532011-09-14 11:45:52 -040012285#endif /* USE_XATTRS */
Benjamin Peterson799bd802011-08-31 22:15:17 -040012286
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012287
Larry Hastings2f936352014-08-05 14:04:04 +100012288/*[clinic input]
12289os.urandom
12290
12291 size: Py_ssize_t
12292 /
12293
12294Return a bytes object containing random bytes suitable for cryptographic use.
12295[clinic start generated code]*/
12296
Larry Hastings2f936352014-08-05 14:04:04 +100012297static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012298os_urandom_impl(PyObject *module, Py_ssize_t size)
12299/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012300{
12301 PyObject *bytes;
12302 int result;
12303
Georg Brandl2fb477c2012-02-21 00:33:36 +010012304 if (size < 0)
12305 return PyErr_Format(PyExc_ValueError,
12306 "negative argument not allowed");
Larry Hastings2f936352014-08-05 14:04:04 +100012307 bytes = PyBytes_FromStringAndSize(NULL, size);
12308 if (bytes == NULL)
Georg Brandl2fb477c2012-02-21 00:33:36 +010012309 return NULL;
12310
Victor Stinnere66987e2016-09-06 16:33:52 -070012311 result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
Larry Hastings2f936352014-08-05 14:04:04 +100012312 if (result == -1) {
12313 Py_DECREF(bytes);
Georg Brandl2fb477c2012-02-21 00:33:36 +010012314 return NULL;
12315 }
Larry Hastings2f936352014-08-05 14:04:04 +100012316 return bytes;
Georg Brandl2fb477c2012-02-21 00:33:36 +010012317}
12318
Zackery Spytz43fdbd22019-05-29 13:57:07 -060012319#ifdef HAVE_MEMFD_CREATE
12320/*[clinic input]
12321os.memfd_create
12322
12323 name: FSConverter
12324 flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
12325
12326[clinic start generated code]*/
12327
12328static PyObject *
12329os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
12330/*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
12331{
12332 int fd;
12333 const char *bytes = PyBytes_AS_STRING(name);
12334 Py_BEGIN_ALLOW_THREADS
12335 fd = memfd_create(bytes, flags);
12336 Py_END_ALLOW_THREADS
12337 if (fd == -1) {
12338 return PyErr_SetFromErrno(PyExc_OSError);
12339 }
12340 return PyLong_FromLong(fd);
12341}
12342#endif
12343
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012344/* Terminal size querying */
12345
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012346PyDoc_STRVAR(TerminalSize_docstring,
12347 "A tuple of (columns, lines) for holding terminal window size");
12348
12349static PyStructSequence_Field TerminalSize_fields[] = {
12350 {"columns", "width of the terminal window in characters"},
12351 {"lines", "height of the terminal window in characters"},
12352 {NULL, NULL}
12353};
12354
12355static PyStructSequence_Desc TerminalSize_desc = {
12356 "os.terminal_size",
12357 TerminalSize_docstring,
12358 TerminalSize_fields,
12359 2,
12360};
12361
12362#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
Larry Hastings2f936352014-08-05 14:04:04 +100012363/* AC 3.5: fd should accept None */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012364PyDoc_STRVAR(termsize__doc__,
12365 "Return the size of the terminal window as (columns, lines).\n" \
12366 "\n" \
12367 "The optional argument fd (default standard output) specifies\n" \
12368 "which file descriptor should be queried.\n" \
12369 "\n" \
12370 "If the file descriptor is not connected to a terminal, an OSError\n" \
12371 "is thrown.\n" \
12372 "\n" \
12373 "This function will only be defined if an implementation is\n" \
12374 "available for this system.\n" \
12375 "\n" \
oldkaa0735f2018-02-02 16:52:55 +080012376 "shutil.get_terminal_size is the high-level function which should\n" \
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012377 "normally be used, os.get_terminal_size is the low-level implementation.");
12378
12379static PyObject*
12380get_terminal_size(PyObject *self, PyObject *args)
12381{
12382 int columns, lines;
12383 PyObject *termsize;
12384
12385 int fd = fileno(stdout);
12386 /* Under some conditions stdout may not be connected and
12387 * fileno(stdout) may point to an invalid file descriptor. For example
12388 * GUI apps don't have valid standard streams by default.
12389 *
12390 * If this happens, and the optional fd argument is not present,
12391 * the ioctl below will fail returning EBADF. This is what we want.
12392 */
12393
12394 if (!PyArg_ParseTuple(args, "|i", &fd))
12395 return NULL;
12396
12397#ifdef TERMSIZE_USE_IOCTL
12398 {
12399 struct winsize w;
12400 if (ioctl(fd, TIOCGWINSZ, &w))
12401 return PyErr_SetFromErrno(PyExc_OSError);
12402 columns = w.ws_col;
12403 lines = w.ws_row;
12404 }
12405#endif /* TERMSIZE_USE_IOCTL */
12406
12407#ifdef TERMSIZE_USE_CONIO
12408 {
12409 DWORD nhandle;
12410 HANDLE handle;
12411 CONSOLE_SCREEN_BUFFER_INFO csbi;
12412 switch (fd) {
12413 case 0: nhandle = STD_INPUT_HANDLE;
12414 break;
12415 case 1: nhandle = STD_OUTPUT_HANDLE;
12416 break;
12417 case 2: nhandle = STD_ERROR_HANDLE;
12418 break;
12419 default:
12420 return PyErr_Format(PyExc_ValueError, "bad file descriptor");
12421 }
12422 handle = GetStdHandle(nhandle);
12423 if (handle == NULL)
12424 return PyErr_Format(PyExc_OSError, "handle cannot be retrieved");
12425 if (handle == INVALID_HANDLE_VALUE)
12426 return PyErr_SetFromWindowsErr(0);
12427
12428 if (!GetConsoleScreenBufferInfo(handle, &csbi))
12429 return PyErr_SetFromWindowsErr(0);
12430
12431 columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
12432 lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
12433 }
12434#endif /* TERMSIZE_USE_CONIO */
12435
Hai Shif707d942020-03-16 21:15:01 +080012436 PyObject *TerminalSizeType = get_posix_state(self)->TerminalSizeType;
Eddie Elizondob3966632019-11-05 07:16:14 -080012437 termsize = PyStructSequence_New((PyTypeObject *)TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012438 if (termsize == NULL)
12439 return NULL;
12440 PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
12441 PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
12442 if (PyErr_Occurred()) {
12443 Py_DECREF(termsize);
12444 return NULL;
12445 }
12446 return termsize;
12447}
12448#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
12449
Larry Hastings2f936352014-08-05 14:04:04 +100012450
12451/*[clinic input]
12452os.cpu_count
12453
Charles-François Natali80d62e62015-08-13 20:37:08 +010012454Return the number of CPUs in the system; return None if indeterminable.
12455
12456This number is not equivalent to the number of CPUs the current process can
12457use. The number of usable CPUs can be obtained with
12458``len(os.sched_getaffinity(0))``
Larry Hastings2f936352014-08-05 14:04:04 +100012459[clinic start generated code]*/
12460
Larry Hastings2f936352014-08-05 14:04:04 +100012461static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012462os_cpu_count_impl(PyObject *module)
Serhiy Storchaka2954f832016-07-07 18:20:03 +030012463/*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012464{
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012465 int ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012466#ifdef MS_WINDOWS
Steve Doweraa929272019-09-11 16:15:39 +010012467 ncpu = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012468#elif defined(__hpux)
12469 ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
12470#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
12471 ncpu = sysconf(_SC_NPROCESSORS_ONLN);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012472#elif defined(__DragonFly__) || \
12473 defined(__OpenBSD__) || \
12474 defined(__FreeBSD__) || \
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012475 defined(__NetBSD__) || \
12476 defined(__APPLE__)
Charles-Francois Natali7c4f8da2013-05-20 17:40:32 +020012477 int mib[2];
12478 size_t len = sizeof(ncpu);
12479 mib[0] = CTL_HW;
12480 mib[1] = HW_NCPU;
12481 if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
12482 ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012483#endif
12484 if (ncpu >= 1)
12485 return PyLong_FromLong(ncpu);
12486 else
12487 Py_RETURN_NONE;
12488}
12489
Victor Stinnerdaf45552013-08-28 00:53:59 +020012490
Larry Hastings2f936352014-08-05 14:04:04 +100012491/*[clinic input]
12492os.get_inheritable -> bool
12493
12494 fd: int
12495 /
12496
12497Get the close-on-exe flag of the specified file descriptor.
12498[clinic start generated code]*/
12499
Larry Hastings2f936352014-08-05 14:04:04 +100012500static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012501os_get_inheritable_impl(PyObject *module, int fd)
12502/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012503{
Steve Dower8fc89802015-04-12 00:26:27 -040012504 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -040012505 _Py_BEGIN_SUPPRESS_IPH
12506 return_value = _Py_get_inheritable(fd);
12507 _Py_END_SUPPRESS_IPH
12508 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +100012509}
12510
12511
12512/*[clinic input]
12513os.set_inheritable
12514 fd: int
12515 inheritable: int
12516 /
12517
12518Set the inheritable flag of the specified file descriptor.
12519[clinic start generated code]*/
12520
Larry Hastings2f936352014-08-05 14:04:04 +100012521static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012522os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
12523/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
Victor Stinnerdaf45552013-08-28 00:53:59 +020012524{
Steve Dower8fc89802015-04-12 00:26:27 -040012525 int result;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012526
Steve Dower8fc89802015-04-12 00:26:27 -040012527 _Py_BEGIN_SUPPRESS_IPH
12528 result = _Py_set_inheritable(fd, inheritable, NULL);
12529 _Py_END_SUPPRESS_IPH
12530 if (result < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +020012531 return NULL;
12532 Py_RETURN_NONE;
12533}
12534
12535
12536#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100012537/*[clinic input]
12538os.get_handle_inheritable -> bool
Benjamin Petersonca470632016-09-06 13:47:26 -070012539 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012540 /
Victor Stinnerdaf45552013-08-28 00:53:59 +020012541
Larry Hastings2f936352014-08-05 14:04:04 +100012542Get the close-on-exe flag of the specified file descriptor.
12543[clinic start generated code]*/
12544
Larry Hastings2f936352014-08-05 14:04:04 +100012545static int
Benjamin Petersonca470632016-09-06 13:47:26 -070012546os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
Victor Stinner581139c2016-09-06 15:54:20 -070012547/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012548{
12549 DWORD flags;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012550
12551 if (!GetHandleInformation((HANDLE)handle, &flags)) {
12552 PyErr_SetFromWindowsErr(0);
Larry Hastings2f936352014-08-05 14:04:04 +100012553 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012554 }
12555
Larry Hastings2f936352014-08-05 14:04:04 +100012556 return flags & HANDLE_FLAG_INHERIT;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012557}
12558
Victor Stinnerdaf45552013-08-28 00:53:59 +020012559
Larry Hastings2f936352014-08-05 14:04:04 +100012560/*[clinic input]
12561os.set_handle_inheritable
Benjamin Petersonca470632016-09-06 13:47:26 -070012562 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012563 inheritable: bool
12564 /
12565
12566Set the inheritable flag of the specified handle.
12567[clinic start generated code]*/
12568
Larry Hastings2f936352014-08-05 14:04:04 +100012569static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -070012570os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
Larry Hastings89964c42015-04-14 18:07:59 -040012571 int inheritable)
Victor Stinner581139c2016-09-06 15:54:20 -070012572/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012573{
12574 DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012575 if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
12576 PyErr_SetFromWindowsErr(0);
12577 return NULL;
12578 }
12579 Py_RETURN_NONE;
12580}
Larry Hastings2f936352014-08-05 14:04:04 +100012581#endif /* MS_WINDOWS */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012582
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012583#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012584/*[clinic input]
12585os.get_blocking -> bool
12586 fd: int
12587 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012588
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012589Get the blocking mode of the file descriptor.
12590
12591Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
12592[clinic start generated code]*/
12593
12594static int
12595os_get_blocking_impl(PyObject *module, int fd)
12596/*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012597{
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012598 int blocking;
12599
Steve Dower8fc89802015-04-12 00:26:27 -040012600 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012601 blocking = _Py_get_blocking(fd);
Steve Dower8fc89802015-04-12 00:26:27 -040012602 _Py_END_SUPPRESS_IPH
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012603 return blocking;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012604}
12605
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012606/*[clinic input]
12607os.set_blocking
12608 fd: int
12609 blocking: bool(accept={int})
12610 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012611
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012612Set the blocking mode of the specified file descriptor.
12613
12614Set the O_NONBLOCK flag if blocking is False,
12615clear the O_NONBLOCK flag otherwise.
12616[clinic start generated code]*/
12617
12618static PyObject *
12619os_set_blocking_impl(PyObject *module, int fd, int blocking)
12620/*[clinic end generated code: output=384eb43aa0762a9d input=bf5c8efdc5860ff3]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012621{
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012622 int result;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012623
Steve Dower8fc89802015-04-12 00:26:27 -040012624 _Py_BEGIN_SUPPRESS_IPH
12625 result = _Py_set_blocking(fd, blocking);
12626 _Py_END_SUPPRESS_IPH
12627 if (result < 0)
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012628 return NULL;
12629 Py_RETURN_NONE;
12630}
12631#endif /* !MS_WINDOWS */
12632
12633
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012634/*[clinic input]
Eddie Elizondob3966632019-11-05 07:16:14 -080012635class os.DirEntry "DirEntry *" "DirEntryType"
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012636[clinic start generated code]*/
Eddie Elizondob3966632019-11-05 07:16:14 -080012637/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3c18c7a448247980]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012638
12639typedef struct {
12640 PyObject_HEAD
12641 PyObject *name;
12642 PyObject *path;
12643 PyObject *stat;
12644 PyObject *lstat;
12645#ifdef MS_WINDOWS
12646 struct _Py_stat_struct win32_lstat;
Victor Stinner0f6d7332017-03-09 17:34:28 +010012647 uint64_t win32_file_index;
Victor Stinner6036e442015-03-08 01:58:04 +010012648 int got_file_index;
12649#else /* POSIX */
Victor Stinner35a97c02015-03-08 02:59:09 +010012650#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012651 unsigned char d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012652#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012653 ino_t d_ino;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012654 int dir_fd;
Victor Stinner6036e442015-03-08 01:58:04 +010012655#endif
12656} DirEntry;
12657
Eddie Elizondob3966632019-11-05 07:16:14 -080012658static PyObject *
12659_disabled_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
12660{
12661 PyErr_Format(PyExc_TypeError,
12662 "cannot create '%.100s' instances", _PyType_Name(type));
12663 return NULL;
12664}
12665
Victor Stinner6036e442015-03-08 01:58:04 +010012666static void
12667DirEntry_dealloc(DirEntry *entry)
12668{
Eddie Elizondob3966632019-11-05 07:16:14 -080012669 PyTypeObject *tp = Py_TYPE(entry);
Victor Stinner6036e442015-03-08 01:58:04 +010012670 Py_XDECREF(entry->name);
12671 Py_XDECREF(entry->path);
12672 Py_XDECREF(entry->stat);
12673 Py_XDECREF(entry->lstat);
Eddie Elizondob3966632019-11-05 07:16:14 -080012674 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
12675 free_func(entry);
12676 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010012677}
12678
12679/* Forward reference */
12680static int
12681DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits);
12682
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012683/*[clinic input]
12684os.DirEntry.is_symlink -> bool
12685
12686Return True if the entry is a symbolic link; cached per entry.
12687[clinic start generated code]*/
12688
Victor Stinner6036e442015-03-08 01:58:04 +010012689static int
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012690os_DirEntry_is_symlink_impl(DirEntry *self)
12691/*[clinic end generated code: output=42244667d7bcfc25 input=1605a1b4b96976c3]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012692{
12693#ifdef MS_WINDOWS
12694 return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
Victor Stinner35a97c02015-03-08 02:59:09 +010012695#elif defined(HAVE_DIRENT_D_TYPE)
12696 /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010012697 if (self->d_type != DT_UNKNOWN)
12698 return self->d_type == DT_LNK;
12699 else
12700 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner35a97c02015-03-08 02:59:09 +010012701#else
12702 /* POSIX without d_type */
12703 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner6036e442015-03-08 01:58:04 +010012704#endif
12705}
12706
12707static PyObject *
Victor Stinner6036e442015-03-08 01:58:04 +010012708DirEntry_fetch_stat(DirEntry *self, int follow_symlinks)
12709{
12710 int result;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012711 STRUCT_STAT st;
12712 PyObject *ub;
Victor Stinner6036e442015-03-08 01:58:04 +010012713
12714#ifdef MS_WINDOWS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012715 if (!PyUnicode_FSDecoder(self->path, &ub))
12716 return NULL;
12717 const wchar_t *path = PyUnicode_AsUnicode(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012718#else /* POSIX */
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012719 if (!PyUnicode_FSConverter(self->path, &ub))
12720 return NULL;
12721 const char *path = PyBytes_AS_STRING(ub);
12722 if (self->dir_fd != DEFAULT_DIR_FD) {
12723#ifdef HAVE_FSTATAT
12724 result = fstatat(self->dir_fd, path, &st,
12725 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
12726#else
12727 PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
12728 return NULL;
12729#endif /* HAVE_FSTATAT */
12730 }
12731 else
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012732#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012733 {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012734 if (follow_symlinks)
12735 result = STAT(path, &st);
12736 else
12737 result = LSTAT(path, &st);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012738 }
12739 Py_DECREF(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012740
12741 if (result != 0)
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012742 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012743
12744 return _pystat_fromstructstat(&st);
12745}
12746
12747static PyObject *
12748DirEntry_get_lstat(DirEntry *self)
12749{
12750 if (!self->lstat) {
12751#ifdef MS_WINDOWS
12752 self->lstat = _pystat_fromstructstat(&self->win32_lstat);
12753#else /* POSIX */
12754 self->lstat = DirEntry_fetch_stat(self, 0);
12755#endif
12756 }
12757 Py_XINCREF(self->lstat);
12758 return self->lstat;
12759}
12760
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012761/*[clinic input]
12762os.DirEntry.stat
12763 *
12764 follow_symlinks: bool = True
12765
12766Return stat_result object for the entry; cached per entry.
12767[clinic start generated code]*/
12768
Victor Stinner6036e442015-03-08 01:58:04 +010012769static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012770os_DirEntry_stat_impl(DirEntry *self, int follow_symlinks)
12771/*[clinic end generated code: output=008593b3a6d01305 input=280d14c1d6f1d00d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012772{
12773 if (!follow_symlinks)
12774 return DirEntry_get_lstat(self);
12775
12776 if (!self->stat) {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012777 int result = os_DirEntry_is_symlink_impl(self);
Victor Stinner6036e442015-03-08 01:58:04 +010012778 if (result == -1)
12779 return NULL;
12780 else if (result)
12781 self->stat = DirEntry_fetch_stat(self, 1);
12782 else
12783 self->stat = DirEntry_get_lstat(self);
12784 }
12785
12786 Py_XINCREF(self->stat);
12787 return self->stat;
12788}
12789
Victor Stinner6036e442015-03-08 01:58:04 +010012790/* Set exception and return -1 on error, 0 for False, 1 for True */
12791static int
12792DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
12793{
12794 PyObject *stat = NULL;
12795 PyObject *st_mode = NULL;
12796 long mode;
12797 int result;
Victor Stinner35a97c02015-03-08 02:59:09 +010012798#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012799 int is_symlink;
12800 int need_stat;
Victor Stinner35a97c02015-03-08 02:59:09 +010012801#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012802#ifdef MS_WINDOWS
12803 unsigned long dir_bits;
12804#endif
12805
12806#ifdef MS_WINDOWS
12807 is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
12808 need_stat = follow_symlinks && is_symlink;
Victor Stinner35a97c02015-03-08 02:59:09 +010012809#elif defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012810 is_symlink = self->d_type == DT_LNK;
12811 need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
12812#endif
12813
Victor Stinner35a97c02015-03-08 02:59:09 +010012814#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012815 if (need_stat) {
Victor Stinner35a97c02015-03-08 02:59:09 +010012816#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012817 stat = os_DirEntry_stat_impl(self, follow_symlinks);
Victor Stinner6036e442015-03-08 01:58:04 +010012818 if (!stat) {
12819 if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
12820 /* If file doesn't exist (anymore), then return False
12821 (i.e., say it's not a file/directory) */
12822 PyErr_Clear();
12823 return 0;
12824 }
12825 goto error;
12826 }
Eddie Elizondob3966632019-11-05 07:16:14 -080012827 st_mode = PyObject_GetAttr(stat, _posixstate_global->st_mode);
Victor Stinner6036e442015-03-08 01:58:04 +010012828 if (!st_mode)
12829 goto error;
12830
12831 mode = PyLong_AsLong(st_mode);
12832 if (mode == -1 && PyErr_Occurred())
12833 goto error;
12834 Py_CLEAR(st_mode);
12835 Py_CLEAR(stat);
12836 result = (mode & S_IFMT) == mode_bits;
Victor Stinner35a97c02015-03-08 02:59:09 +010012837#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012838 }
12839 else if (is_symlink) {
12840 assert(mode_bits != S_IFLNK);
12841 result = 0;
12842 }
12843 else {
12844 assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
12845#ifdef MS_WINDOWS
12846 dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
12847 if (mode_bits == S_IFDIR)
12848 result = dir_bits != 0;
12849 else
12850 result = dir_bits == 0;
12851#else /* POSIX */
12852 if (mode_bits == S_IFDIR)
12853 result = self->d_type == DT_DIR;
12854 else
12855 result = self->d_type == DT_REG;
12856#endif
12857 }
Victor Stinner35a97c02015-03-08 02:59:09 +010012858#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012859
12860 return result;
12861
12862error:
12863 Py_XDECREF(st_mode);
12864 Py_XDECREF(stat);
12865 return -1;
12866}
12867
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012868/*[clinic input]
12869os.DirEntry.is_dir -> bool
12870 *
12871 follow_symlinks: bool = True
Victor Stinner6036e442015-03-08 01:58:04 +010012872
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012873Return True if the entry is a directory; cached per entry.
12874[clinic start generated code]*/
12875
12876static int
12877os_DirEntry_is_dir_impl(DirEntry *self, int follow_symlinks)
12878/*[clinic end generated code: output=ad2e8d54365da287 input=0135232766f53f58]*/
12879{
12880 return DirEntry_test_mode(self, follow_symlinks, S_IFDIR);
Victor Stinner6036e442015-03-08 01:58:04 +010012881}
12882
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012883/*[clinic input]
12884os.DirEntry.is_file -> bool
12885 *
12886 follow_symlinks: bool = True
12887
12888Return True if the entry is a file; cached per entry.
12889[clinic start generated code]*/
12890
12891static int
12892os_DirEntry_is_file_impl(DirEntry *self, int follow_symlinks)
12893/*[clinic end generated code: output=8462ade481d8a476 input=0dc90be168b041ee]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012894{
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012895 return DirEntry_test_mode(self, follow_symlinks, S_IFREG);
Victor Stinner6036e442015-03-08 01:58:04 +010012896}
12897
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012898/*[clinic input]
12899os.DirEntry.inode
Victor Stinner6036e442015-03-08 01:58:04 +010012900
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012901Return inode of the entry; cached per entry.
12902[clinic start generated code]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012903
12904static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012905os_DirEntry_inode_impl(DirEntry *self)
12906/*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012907{
12908#ifdef MS_WINDOWS
12909 if (!self->got_file_index) {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012910 PyObject *unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012911 const wchar_t *path;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012912 STRUCT_STAT stat;
12913 int result;
Victor Stinner6036e442015-03-08 01:58:04 +010012914
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012915 if (!PyUnicode_FSDecoder(self->path, &unicode))
Victor Stinner6036e442015-03-08 01:58:04 +010012916 return NULL;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012917 path = PyUnicode_AsUnicode(unicode);
12918 result = LSTAT(path, &stat);
12919 Py_DECREF(unicode);
Victor Stinner6036e442015-03-08 01:58:04 +010012920
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012921 if (result != 0)
12922 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012923
12924 self->win32_file_index = stat.st_ino;
12925 self->got_file_index = 1;
12926 }
Victor Stinner0f6d7332017-03-09 17:34:28 +010012927 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->win32_file_index));
12928 return PyLong_FromUnsignedLongLong(self->win32_file_index);
Victor Stinner6036e442015-03-08 01:58:04 +010012929#else /* POSIX */
xdegaye50e86032017-05-22 11:15:08 +020012930 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->d_ino));
12931 return PyLong_FromUnsignedLongLong(self->d_ino);
Victor Stinner6036e442015-03-08 01:58:04 +010012932#endif
12933}
12934
12935static PyObject *
12936DirEntry_repr(DirEntry *self)
12937{
12938 return PyUnicode_FromFormat("<DirEntry %R>", self->name);
12939}
12940
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012941/*[clinic input]
12942os.DirEntry.__fspath__
12943
12944Returns the path for the entry.
12945[clinic start generated code]*/
12946
Brett Cannon96881cd2016-06-10 14:37:21 -070012947static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012948os_DirEntry___fspath___impl(DirEntry *self)
12949/*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
Brett Cannon96881cd2016-06-10 14:37:21 -070012950{
12951 Py_INCREF(self->path);
12952 return self->path;
12953}
12954
Victor Stinner6036e442015-03-08 01:58:04 +010012955static PyMemberDef DirEntry_members[] = {
12956 {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
12957 "the entry's base filename, relative to scandir() \"path\" argument"},
12958 {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
12959 "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
12960 {NULL}
12961};
12962
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012963#include "clinic/posixmodule.c.h"
12964
Victor Stinner6036e442015-03-08 01:58:04 +010012965static PyMethodDef DirEntry_methods[] = {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012966 OS_DIRENTRY_IS_DIR_METHODDEF
12967 OS_DIRENTRY_IS_FILE_METHODDEF
12968 OS_DIRENTRY_IS_SYMLINK_METHODDEF
12969 OS_DIRENTRY_STAT_METHODDEF
12970 OS_DIRENTRY_INODE_METHODDEF
12971 OS_DIRENTRY___FSPATH___METHODDEF
Victor Stinner6036e442015-03-08 01:58:04 +010012972 {NULL}
12973};
12974
Eddie Elizondob3966632019-11-05 07:16:14 -080012975static PyType_Slot DirEntryType_slots[] = {
12976 {Py_tp_new, _disabled_new},
12977 {Py_tp_dealloc, DirEntry_dealloc},
12978 {Py_tp_repr, DirEntry_repr},
12979 {Py_tp_methods, DirEntry_methods},
12980 {Py_tp_members, DirEntry_members},
12981 {0, 0},
Victor Stinner6036e442015-03-08 01:58:04 +010012982};
12983
Eddie Elizondob3966632019-11-05 07:16:14 -080012984static PyType_Spec DirEntryType_spec = {
12985 MODNAME ".DirEntry",
12986 sizeof(DirEntry),
12987 0,
12988 Py_TPFLAGS_DEFAULT,
12989 DirEntryType_slots
12990};
12991
12992
Victor Stinner6036e442015-03-08 01:58:04 +010012993#ifdef MS_WINDOWS
12994
12995static wchar_t *
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012996join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
Victor Stinner6036e442015-03-08 01:58:04 +010012997{
12998 Py_ssize_t path_len;
12999 Py_ssize_t size;
13000 wchar_t *result;
13001 wchar_t ch;
13002
13003 if (!path_wide) { /* Default arg: "." */
13004 path_wide = L".";
13005 path_len = 1;
13006 }
13007 else {
13008 path_len = wcslen(path_wide);
13009 }
13010
13011 /* The +1's are for the path separator and the NUL */
13012 size = path_len + 1 + wcslen(filename) + 1;
13013 result = PyMem_New(wchar_t, size);
13014 if (!result) {
13015 PyErr_NoMemory();
13016 return NULL;
13017 }
13018 wcscpy(result, path_wide);
13019 if (path_len > 0) {
13020 ch = result[path_len - 1];
13021 if (ch != SEP && ch != ALTSEP && ch != L':')
13022 result[path_len++] = SEP;
13023 wcscpy(result + path_len, filename);
13024 }
13025 return result;
13026}
13027
13028static PyObject *
13029DirEntry_from_find_data(path_t *path, WIN32_FIND_DATAW *dataW)
13030{
13031 DirEntry *entry;
13032 BY_HANDLE_FILE_INFORMATION file_info;
13033 ULONG reparse_tag;
13034 wchar_t *joined_path;
13035
Eddie Elizondob3966632019-11-05 07:16:14 -080013036 PyObject *DirEntryType = _posixstate_global->DirEntryType;
13037 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010013038 if (!entry)
13039 return NULL;
13040 entry->name = NULL;
13041 entry->path = NULL;
13042 entry->stat = NULL;
13043 entry->lstat = NULL;
13044 entry->got_file_index = 0;
13045
13046 entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
13047 if (!entry->name)
13048 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070013049 if (path->narrow) {
13050 Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
13051 if (!entry->name)
13052 goto error;
13053 }
Victor Stinner6036e442015-03-08 01:58:04 +010013054
13055 joined_path = join_path_filenameW(path->wide, dataW->cFileName);
13056 if (!joined_path)
13057 goto error;
13058
13059 entry->path = PyUnicode_FromWideChar(joined_path, -1);
13060 PyMem_Free(joined_path);
13061 if (!entry->path)
13062 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070013063 if (path->narrow) {
13064 Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
13065 if (!entry->path)
13066 goto error;
13067 }
Victor Stinner6036e442015-03-08 01:58:04 +010013068
Steve Dowercc16be82016-09-08 10:35:16 -070013069 find_data_to_file_info(dataW, &file_info, &reparse_tag);
Victor Stinner6036e442015-03-08 01:58:04 +010013070 _Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
13071
13072 return (PyObject *)entry;
13073
13074error:
13075 Py_DECREF(entry);
13076 return NULL;
13077}
13078
13079#else /* POSIX */
13080
13081static char *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020013082join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
Victor Stinner6036e442015-03-08 01:58:04 +010013083{
13084 Py_ssize_t path_len;
13085 Py_ssize_t size;
13086 char *result;
13087
13088 if (!path_narrow) { /* Default arg: "." */
13089 path_narrow = ".";
13090 path_len = 1;
13091 }
13092 else {
13093 path_len = strlen(path_narrow);
13094 }
13095
13096 if (filename_len == -1)
13097 filename_len = strlen(filename);
13098
13099 /* The +1's are for the path separator and the NUL */
13100 size = path_len + 1 + filename_len + 1;
13101 result = PyMem_New(char, size);
13102 if (!result) {
13103 PyErr_NoMemory();
13104 return NULL;
13105 }
13106 strcpy(result, path_narrow);
13107 if (path_len > 0 && result[path_len - 1] != '/')
13108 result[path_len++] = '/';
13109 strcpy(result + path_len, filename);
13110 return result;
13111}
13112
13113static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020013114DirEntry_from_posix_info(path_t *path, const char *name, Py_ssize_t name_len,
Victor Stinner35a97c02015-03-08 02:59:09 +010013115 ino_t d_ino
13116#ifdef HAVE_DIRENT_D_TYPE
13117 , unsigned char d_type
13118#endif
13119 )
Victor Stinner6036e442015-03-08 01:58:04 +010013120{
13121 DirEntry *entry;
13122 char *joined_path;
13123
Eddie Elizondob3966632019-11-05 07:16:14 -080013124 PyObject *DirEntryType = _posixstate_global->DirEntryType;
13125 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010013126 if (!entry)
13127 return NULL;
13128 entry->name = NULL;
13129 entry->path = NULL;
13130 entry->stat = NULL;
13131 entry->lstat = NULL;
13132
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013133 if (path->fd != -1) {
13134 entry->dir_fd = path->fd;
13135 joined_path = NULL;
13136 }
13137 else {
13138 entry->dir_fd = DEFAULT_DIR_FD;
13139 joined_path = join_path_filename(path->narrow, name, name_len);
13140 if (!joined_path)
13141 goto error;
13142 }
Victor Stinner6036e442015-03-08 01:58:04 +010013143
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +030013144 if (!path->narrow || !PyObject_CheckBuffer(path->object)) {
Victor Stinner6036e442015-03-08 01:58:04 +010013145 entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013146 if (joined_path)
13147 entry->path = PyUnicode_DecodeFSDefault(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013148 }
13149 else {
13150 entry->name = PyBytes_FromStringAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013151 if (joined_path)
13152 entry->path = PyBytes_FromString(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013153 }
13154 PyMem_Free(joined_path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013155 if (!entry->name)
13156 goto error;
13157
13158 if (path->fd != -1) {
13159 entry->path = entry->name;
13160 Py_INCREF(entry->path);
13161 }
13162 else if (!entry->path)
Victor Stinner6036e442015-03-08 01:58:04 +010013163 goto error;
13164
Victor Stinner35a97c02015-03-08 02:59:09 +010013165#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010013166 entry->d_type = d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010013167#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013168 entry->d_ino = d_ino;
13169
13170 return (PyObject *)entry;
13171
13172error:
13173 Py_XDECREF(entry);
13174 return NULL;
13175}
13176
13177#endif
13178
13179
13180typedef struct {
13181 PyObject_HEAD
13182 path_t path;
13183#ifdef MS_WINDOWS
13184 HANDLE handle;
13185 WIN32_FIND_DATAW file_data;
13186 int first_time;
13187#else /* POSIX */
13188 DIR *dirp;
13189#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013190#ifdef HAVE_FDOPENDIR
13191 int fd;
13192#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013193} ScandirIterator;
13194
13195#ifdef MS_WINDOWS
13196
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013197static int
13198ScandirIterator_is_closed(ScandirIterator *iterator)
13199{
13200 return iterator->handle == INVALID_HANDLE_VALUE;
13201}
13202
Victor Stinner6036e442015-03-08 01:58:04 +010013203static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013204ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013205{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013206 HANDLE handle = iterator->handle;
13207
13208 if (handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013209 return;
13210
Victor Stinner6036e442015-03-08 01:58:04 +010013211 iterator->handle = INVALID_HANDLE_VALUE;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013212 Py_BEGIN_ALLOW_THREADS
13213 FindClose(handle);
13214 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013215}
13216
13217static PyObject *
13218ScandirIterator_iternext(ScandirIterator *iterator)
13219{
13220 WIN32_FIND_DATAW *file_data = &iterator->file_data;
13221 BOOL success;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013222 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013223
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013224 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013225 if (iterator->handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013226 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013227
13228 while (1) {
13229 if (!iterator->first_time) {
13230 Py_BEGIN_ALLOW_THREADS
13231 success = FindNextFileW(iterator->handle, file_data);
13232 Py_END_ALLOW_THREADS
13233 if (!success) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013234 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013235 if (GetLastError() != ERROR_NO_MORE_FILES)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013236 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013237 break;
13238 }
13239 }
13240 iterator->first_time = 0;
13241
13242 /* Skip over . and .. */
13243 if (wcscmp(file_data->cFileName, L".") != 0 &&
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013244 wcscmp(file_data->cFileName, L"..") != 0) {
13245 entry = DirEntry_from_find_data(&iterator->path, file_data);
13246 if (!entry)
13247 break;
13248 return entry;
13249 }
Victor Stinner6036e442015-03-08 01:58:04 +010013250
13251 /* Loop till we get a non-dot directory or finish iterating */
13252 }
13253
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013254 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013255 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013256 return NULL;
13257}
13258
13259#else /* POSIX */
13260
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013261static int
13262ScandirIterator_is_closed(ScandirIterator *iterator)
13263{
13264 return !iterator->dirp;
13265}
13266
Victor Stinner6036e442015-03-08 01:58:04 +010013267static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013268ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013269{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013270 DIR *dirp = iterator->dirp;
13271
13272 if (!dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013273 return;
13274
Victor Stinner6036e442015-03-08 01:58:04 +010013275 iterator->dirp = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013276 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013277#ifdef HAVE_FDOPENDIR
13278 if (iterator->path.fd != -1)
13279 rewinddir(dirp);
13280#endif
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013281 closedir(dirp);
13282 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013283 return;
13284}
13285
13286static PyObject *
13287ScandirIterator_iternext(ScandirIterator *iterator)
13288{
13289 struct dirent *direntp;
13290 Py_ssize_t name_len;
13291 int is_dot;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013292 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013293
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013294 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013295 if (!iterator->dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013296 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013297
13298 while (1) {
13299 errno = 0;
13300 Py_BEGIN_ALLOW_THREADS
13301 direntp = readdir(iterator->dirp);
13302 Py_END_ALLOW_THREADS
13303
13304 if (!direntp) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013305 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013306 if (errno != 0)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013307 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013308 break;
13309 }
13310
13311 /* Skip over . and .. */
13312 name_len = NAMLEN(direntp);
13313 is_dot = direntp->d_name[0] == '.' &&
13314 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
13315 if (!is_dot) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013316 entry = DirEntry_from_posix_info(&iterator->path, direntp->d_name,
Victor Stinner35a97c02015-03-08 02:59:09 +010013317 name_len, direntp->d_ino
13318#ifdef HAVE_DIRENT_D_TYPE
13319 , direntp->d_type
13320#endif
13321 );
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013322 if (!entry)
13323 break;
13324 return entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013325 }
13326
13327 /* Loop till we get a non-dot directory or finish iterating */
13328 }
13329
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013330 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013331 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013332 return NULL;
13333}
13334
13335#endif
13336
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013337static PyObject *
13338ScandirIterator_close(ScandirIterator *self, PyObject *args)
13339{
13340 ScandirIterator_closedir(self);
13341 Py_RETURN_NONE;
13342}
13343
13344static PyObject *
13345ScandirIterator_enter(PyObject *self, PyObject *args)
13346{
13347 Py_INCREF(self);
13348 return self;
13349}
13350
13351static PyObject *
13352ScandirIterator_exit(ScandirIterator *self, PyObject *args)
13353{
13354 ScandirIterator_closedir(self);
13355 Py_RETURN_NONE;
13356}
13357
Victor Stinner6036e442015-03-08 01:58:04 +010013358static void
Victor Stinner7bfa4092016-03-23 00:43:54 +010013359ScandirIterator_finalize(ScandirIterator *iterator)
13360{
13361 PyObject *error_type, *error_value, *error_traceback;
13362
13363 /* Save the current exception, if any. */
13364 PyErr_Fetch(&error_type, &error_value, &error_traceback);
13365
13366 if (!ScandirIterator_is_closed(iterator)) {
13367 ScandirIterator_closedir(iterator);
13368
13369 if (PyErr_ResourceWarning((PyObject *)iterator, 1,
13370 "unclosed scandir iterator %R", iterator)) {
13371 /* Spurious errors can appear at shutdown */
13372 if (PyErr_ExceptionMatches(PyExc_Warning)) {
13373 PyErr_WriteUnraisable((PyObject *) iterator);
13374 }
13375 }
13376 }
13377
Victor Stinner7bfa4092016-03-23 00:43:54 +010013378 path_cleanup(&iterator->path);
13379
13380 /* Restore the saved exception. */
13381 PyErr_Restore(error_type, error_value, error_traceback);
13382}
13383
13384static void
Victor Stinner6036e442015-03-08 01:58:04 +010013385ScandirIterator_dealloc(ScandirIterator *iterator)
13386{
Eddie Elizondob3966632019-11-05 07:16:14 -080013387 PyTypeObject *tp = Py_TYPE(iterator);
Victor Stinner7bfa4092016-03-23 00:43:54 +010013388 if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
13389 return;
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013390
Eddie Elizondob3966632019-11-05 07:16:14 -080013391 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
13392 free_func(iterator);
13393 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010013394}
13395
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013396static PyMethodDef ScandirIterator_methods[] = {
13397 {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
13398 {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
13399 {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
13400 {NULL}
13401};
13402
Eddie Elizondob3966632019-11-05 07:16:14 -080013403static PyType_Slot ScandirIteratorType_slots[] = {
13404 {Py_tp_new, _disabled_new},
13405 {Py_tp_dealloc, ScandirIterator_dealloc},
13406 {Py_tp_finalize, ScandirIterator_finalize},
13407 {Py_tp_iter, PyObject_SelfIter},
13408 {Py_tp_iternext, ScandirIterator_iternext},
13409 {Py_tp_methods, ScandirIterator_methods},
13410 {0, 0},
13411};
13412
13413static PyType_Spec ScandirIteratorType_spec = {
13414 MODNAME ".ScandirIterator",
13415 sizeof(ScandirIterator),
13416 0,
13417 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE,
13418 ScandirIteratorType_slots
Victor Stinner6036e442015-03-08 01:58:04 +010013419};
13420
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013421/*[clinic input]
13422os.scandir
13423
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013424 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013425
13426Return an iterator of DirEntry objects for given path.
13427
BNMetricsb9427072018-11-02 15:20:19 +000013428path can be specified as either str, bytes, or a path-like object. If path
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013429is bytes, the names of yielded DirEntry objects will also be bytes; in
13430all other circumstances they will be str.
13431
13432If path is None, uses the path='.'.
13433[clinic start generated code]*/
13434
Victor Stinner6036e442015-03-08 01:58:04 +010013435static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013436os_scandir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +000013437/*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013438{
13439 ScandirIterator *iterator;
Victor Stinner6036e442015-03-08 01:58:04 +010013440#ifdef MS_WINDOWS
13441 wchar_t *path_strW;
13442#else
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013443 const char *path_str;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013444#ifdef HAVE_FDOPENDIR
13445 int fd = -1;
13446#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013447#endif
13448
Steve Dower60419a72019-06-24 08:42:54 -070013449 if (PySys_Audit("os.scandir", "O",
13450 path->object ? path->object : Py_None) < 0) {
13451 return NULL;
13452 }
13453
Hai Shif707d942020-03-16 21:15:01 +080013454 PyObject *ScandirIteratorType = get_posix_state(module)->ScandirIteratorType;
Eddie Elizondob3966632019-11-05 07:16:14 -080013455 iterator = PyObject_New(ScandirIterator, (PyTypeObject *)ScandirIteratorType);
Victor Stinner6036e442015-03-08 01:58:04 +010013456 if (!iterator)
13457 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013458
13459#ifdef MS_WINDOWS
13460 iterator->handle = INVALID_HANDLE_VALUE;
13461#else
13462 iterator->dirp = NULL;
13463#endif
13464
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013465 memcpy(&iterator->path, path, sizeof(path_t));
Serhiy Storchaka095ef732017-02-09 20:05:51 +020013466 /* Move the ownership to iterator->path */
13467 path->object = NULL;
13468 path->cleanup = NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013469
13470#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +010013471 iterator->first_time = 1;
13472
13473 path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
13474 if (!path_strW)
13475 goto error;
13476
13477 Py_BEGIN_ALLOW_THREADS
13478 iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
13479 Py_END_ALLOW_THREADS
13480
13481 PyMem_Free(path_strW);
13482
13483 if (iterator->handle == INVALID_HANDLE_VALUE) {
13484 path_error(&iterator->path);
13485 goto error;
13486 }
13487#else /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010013488 errno = 0;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013489#ifdef HAVE_FDOPENDIR
13490 if (path->fd != -1) {
13491 /* closedir() closes the FD, so we duplicate it */
13492 fd = _Py_dup(path->fd);
13493 if (fd == -1)
13494 goto error;
13495
13496 Py_BEGIN_ALLOW_THREADS
13497 iterator->dirp = fdopendir(fd);
13498 Py_END_ALLOW_THREADS
13499 }
13500 else
13501#endif
13502 {
13503 if (iterator->path.narrow)
13504 path_str = iterator->path.narrow;
13505 else
13506 path_str = ".";
13507
13508 Py_BEGIN_ALLOW_THREADS
13509 iterator->dirp = opendir(path_str);
13510 Py_END_ALLOW_THREADS
13511 }
Victor Stinner6036e442015-03-08 01:58:04 +010013512
13513 if (!iterator->dirp) {
13514 path_error(&iterator->path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013515#ifdef HAVE_FDOPENDIR
13516 if (fd != -1) {
13517 Py_BEGIN_ALLOW_THREADS
13518 close(fd);
13519 Py_END_ALLOW_THREADS
13520 }
13521#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013522 goto error;
13523 }
13524#endif
13525
13526 return (PyObject *)iterator;
13527
13528error:
13529 Py_DECREF(iterator);
13530 return NULL;
13531}
13532
Ethan Furman410ef8e2016-06-04 12:06:26 -070013533/*
13534 Return the file system path representation of the object.
13535
13536 If the object is str or bytes, then allow it to pass through with
13537 an incremented refcount. If the object defines __fspath__(), then
13538 return the result of that method. All other types raise a TypeError.
13539*/
13540PyObject *
13541PyOS_FSPath(PyObject *path)
13542{
Brett Cannon3f9183b2016-08-26 14:44:48 -070013543 /* For error message reasons, this function is manually inlined in
13544 path_converter(). */
Ethan Furman410ef8e2016-06-04 12:06:26 -070013545 PyObject *func = NULL;
13546 PyObject *path_repr = NULL;
13547
13548 if (PyUnicode_Check(path) || PyBytes_Check(path)) {
13549 Py_INCREF(path);
13550 return path;
13551 }
13552
13553 func = _PyObject_LookupSpecial(path, &PyId___fspath__);
13554 if (NULL == func) {
13555 return PyErr_Format(PyExc_TypeError,
13556 "expected str, bytes or os.PathLike object, "
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013557 "not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -080013558 _PyType_Name(Py_TYPE(path)));
Ethan Furman410ef8e2016-06-04 12:06:26 -070013559 }
13560
Victor Stinnerf17c3de2016-12-06 18:46:19 +010013561 path_repr = _PyObject_CallNoArg(func);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013562 Py_DECREF(func);
Brett Cannon044283a2016-07-15 10:41:49 -070013563 if (NULL == path_repr) {
13564 return NULL;
13565 }
13566
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013567 if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
13568 PyErr_Format(PyExc_TypeError,
13569 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -080013570 "not %.200s", _PyType_Name(Py_TYPE(path)),
13571 _PyType_Name(Py_TYPE(path_repr)));
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013572 Py_DECREF(path_repr);
13573 return NULL;
13574 }
13575
Ethan Furman410ef8e2016-06-04 12:06:26 -070013576 return path_repr;
13577}
13578
13579/*[clinic input]
13580os.fspath
13581
13582 path: object
13583
13584Return the file system path representation of the object.
13585
Brett Cannonb4f43e92016-06-09 14:32:08 -070013586If the object is str or bytes, then allow it to pass through as-is. If the
13587object defines __fspath__(), then return the result of that method. All other
13588types raise a TypeError.
Ethan Furman410ef8e2016-06-04 12:06:26 -070013589[clinic start generated code]*/
13590
13591static PyObject *
Serhiy Storchaka2954f832016-07-07 18:20:03 +030013592os_fspath_impl(PyObject *module, PyObject *path)
13593/*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
Ethan Furman410ef8e2016-06-04 12:06:26 -070013594{
13595 return PyOS_FSPath(path);
13596}
Victor Stinner6036e442015-03-08 01:58:04 +010013597
Victor Stinner9b1f4742016-09-06 16:18:52 -070013598#ifdef HAVE_GETRANDOM_SYSCALL
13599/*[clinic input]
13600os.getrandom
13601
13602 size: Py_ssize_t
13603 flags: int=0
13604
13605Obtain a series of random bytes.
13606[clinic start generated code]*/
13607
13608static PyObject *
13609os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
13610/*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
13611{
Victor Stinner9b1f4742016-09-06 16:18:52 -070013612 PyObject *bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013613 Py_ssize_t n;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013614
13615 if (size < 0) {
13616 errno = EINVAL;
13617 return posix_error();
13618 }
13619
Victor Stinnerec2319c2016-09-20 23:00:59 +020013620 bytes = PyBytes_FromStringAndSize(NULL, size);
13621 if (bytes == NULL) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013622 PyErr_NoMemory();
13623 return NULL;
13624 }
13625
13626 while (1) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013627 n = syscall(SYS_getrandom,
13628 PyBytes_AS_STRING(bytes),
13629 PyBytes_GET_SIZE(bytes),
13630 flags);
Victor Stinner9b1f4742016-09-06 16:18:52 -070013631 if (n < 0 && errno == EINTR) {
13632 if (PyErr_CheckSignals() < 0) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013633 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013634 }
Victor Stinnerec2319c2016-09-20 23:00:59 +020013635
13636 /* getrandom() was interrupted by a signal: retry */
Victor Stinner9b1f4742016-09-06 16:18:52 -070013637 continue;
13638 }
13639 break;
13640 }
13641
13642 if (n < 0) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013643 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerec2319c2016-09-20 23:00:59 +020013644 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013645 }
13646
Victor Stinnerec2319c2016-09-20 23:00:59 +020013647 if (n != size) {
13648 _PyBytes_Resize(&bytes, n);
13649 }
Victor Stinner9b1f4742016-09-06 16:18:52 -070013650
13651 return bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013652
13653error:
13654 Py_DECREF(bytes);
13655 return NULL;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013656}
13657#endif /* HAVE_GETRANDOM_SYSCALL */
13658
Steve Dower2438cdf2019-03-29 16:37:16 -070013659#ifdef MS_WINDOWS
13660/* bpo-36085: Helper functions for managing DLL search directories
13661 * on win32
13662 */
13663
13664typedef DLL_DIRECTORY_COOKIE (WINAPI *PAddDllDirectory)(PCWSTR newDirectory);
13665typedef BOOL (WINAPI *PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE cookie);
13666
13667/*[clinic input]
13668os._add_dll_directory
13669
13670 path: path_t
13671
13672Add a path to the DLL search path.
13673
13674This search path is used when resolving dependencies for imported
13675extension modules (the module itself is resolved through sys.path),
13676and also by ctypes.
13677
13678Returns an opaque value that may be passed to os.remove_dll_directory
13679to remove this directory from the search path.
13680[clinic start generated code]*/
13681
13682static PyObject *
13683os__add_dll_directory_impl(PyObject *module, path_t *path)
13684/*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
13685{
13686 HMODULE hKernel32;
13687 PAddDllDirectory AddDllDirectory;
13688 DLL_DIRECTORY_COOKIE cookie = 0;
13689 DWORD err = 0;
13690
Saiyang Gou7514f4f2020-02-12 23:47:42 -080013691 if (PySys_Audit("os.add_dll_directory", "(O)", path->object) < 0) {
13692 return NULL;
13693 }
13694
Steve Dower2438cdf2019-03-29 16:37:16 -070013695 /* For Windows 7, we have to load this. As this will be a fairly
13696 infrequent operation, just do it each time. Kernel32 is always
13697 loaded. */
13698 Py_BEGIN_ALLOW_THREADS
13699 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13700 !(AddDllDirectory = (PAddDllDirectory)GetProcAddress(
13701 hKernel32, "AddDllDirectory")) ||
13702 !(cookie = (*AddDllDirectory)(path->wide))) {
13703 err = GetLastError();
13704 }
13705 Py_END_ALLOW_THREADS
13706
13707 if (err) {
13708 return win32_error_object_err("add_dll_directory",
13709 path->object, err);
13710 }
13711
13712 return PyCapsule_New(cookie, "DLL directory cookie", NULL);
13713}
13714
13715/*[clinic input]
13716os._remove_dll_directory
13717
13718 cookie: object
13719
13720Removes a path from the DLL search path.
13721
13722The parameter is an opaque value that was returned from
13723os.add_dll_directory. You can only remove directories that you added
13724yourself.
13725[clinic start generated code]*/
13726
13727static PyObject *
13728os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
13729/*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
13730{
13731 HMODULE hKernel32;
13732 PRemoveDllDirectory RemoveDllDirectory;
13733 DLL_DIRECTORY_COOKIE cookieValue;
13734 DWORD err = 0;
13735
13736 if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
13737 PyErr_SetString(PyExc_TypeError,
13738 "Provided cookie was not returned from os.add_dll_directory");
13739 return NULL;
13740 }
13741
13742 cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
13743 cookie, "DLL directory cookie");
13744
13745 /* For Windows 7, we have to load this. As this will be a fairly
13746 infrequent operation, just do it each time. Kernel32 is always
13747 loaded. */
13748 Py_BEGIN_ALLOW_THREADS
13749 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13750 !(RemoveDllDirectory = (PRemoveDllDirectory)GetProcAddress(
13751 hKernel32, "RemoveDllDirectory")) ||
13752 !(*RemoveDllDirectory)(cookieValue)) {
13753 err = GetLastError();
13754 }
13755 Py_END_ALLOW_THREADS
13756
13757 if (err) {
13758 return win32_error_object_err("remove_dll_directory",
13759 NULL, err);
13760 }
13761
13762 if (PyCapsule_SetName(cookie, NULL)) {
13763 return NULL;
13764 }
13765
13766 Py_RETURN_NONE;
13767}
13768
13769#endif
Larry Hastings31826802013-10-19 00:09:25 -070013770
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013771static PyMethodDef posix_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -070013772
13773 OS_STAT_METHODDEF
13774 OS_ACCESS_METHODDEF
13775 OS_TTYNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013776 OS_CHDIR_METHODDEF
13777 OS_CHFLAGS_METHODDEF
13778 OS_CHMOD_METHODDEF
13779 OS_FCHMOD_METHODDEF
13780 OS_LCHMOD_METHODDEF
13781 OS_CHOWN_METHODDEF
13782 OS_FCHOWN_METHODDEF
13783 OS_LCHOWN_METHODDEF
13784 OS_LCHFLAGS_METHODDEF
13785 OS_CHROOT_METHODDEF
13786 OS_CTERMID_METHODDEF
13787 OS_GETCWD_METHODDEF
13788 OS_GETCWDB_METHODDEF
13789 OS_LINK_METHODDEF
13790 OS_LISTDIR_METHODDEF
13791 OS_LSTAT_METHODDEF
13792 OS_MKDIR_METHODDEF
13793 OS_NICE_METHODDEF
13794 OS_GETPRIORITY_METHODDEF
13795 OS_SETPRIORITY_METHODDEF
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000013796 OS_POSIX_SPAWN_METHODDEF
Joannah Nanjekye92b83222019-01-16 16:29:26 +030013797 OS_POSIX_SPAWNP_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013798 OS_READLINK_METHODDEF
Pablo Galindoaac4d032019-05-31 19:39:47 +010013799 OS_COPY_FILE_RANGE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013800 OS_RENAME_METHODDEF
13801 OS_REPLACE_METHODDEF
13802 OS_RMDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013803 OS_SYMLINK_METHODDEF
13804 OS_SYSTEM_METHODDEF
13805 OS_UMASK_METHODDEF
13806 OS_UNAME_METHODDEF
13807 OS_UNLINK_METHODDEF
13808 OS_REMOVE_METHODDEF
13809 OS_UTIME_METHODDEF
13810 OS_TIMES_METHODDEF
13811 OS__EXIT_METHODDEF
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020013812 OS__FCOPYFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013813 OS_EXECV_METHODDEF
13814 OS_EXECVE_METHODDEF
13815 OS_SPAWNV_METHODDEF
13816 OS_SPAWNVE_METHODDEF
13817 OS_FORK1_METHODDEF
13818 OS_FORK_METHODDEF
Antoine Pitrou346cbd32017-05-27 17:50:54 +020013819 OS_REGISTER_AT_FORK_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013820 OS_SCHED_GET_PRIORITY_MAX_METHODDEF
13821 OS_SCHED_GET_PRIORITY_MIN_METHODDEF
13822 OS_SCHED_GETPARAM_METHODDEF
13823 OS_SCHED_GETSCHEDULER_METHODDEF
13824 OS_SCHED_RR_GET_INTERVAL_METHODDEF
13825 OS_SCHED_SETPARAM_METHODDEF
13826 OS_SCHED_SETSCHEDULER_METHODDEF
13827 OS_SCHED_YIELD_METHODDEF
13828 OS_SCHED_SETAFFINITY_METHODDEF
13829 OS_SCHED_GETAFFINITY_METHODDEF
13830 OS_OPENPTY_METHODDEF
13831 OS_FORKPTY_METHODDEF
13832 OS_GETEGID_METHODDEF
13833 OS_GETEUID_METHODDEF
13834 OS_GETGID_METHODDEF
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +020013835#ifdef HAVE_GETGROUPLIST
13836 {"getgrouplist", posix_getgrouplist, METH_VARARGS, posix_getgrouplist__doc__},
13837#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013838 OS_GETGROUPS_METHODDEF
13839 OS_GETPID_METHODDEF
13840 OS_GETPGRP_METHODDEF
13841 OS_GETPPID_METHODDEF
13842 OS_GETUID_METHODDEF
13843 OS_GETLOGIN_METHODDEF
13844 OS_KILL_METHODDEF
13845 OS_KILLPG_METHODDEF
13846 OS_PLOCK_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013847#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -070013848 OS_STARTFILE_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013849#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013850 OS_SETUID_METHODDEF
13851 OS_SETEUID_METHODDEF
13852 OS_SETREUID_METHODDEF
13853 OS_SETGID_METHODDEF
13854 OS_SETEGID_METHODDEF
13855 OS_SETREGID_METHODDEF
13856 OS_SETGROUPS_METHODDEF
Antoine Pitroub7572f02009-12-02 20:46:48 +000013857#ifdef HAVE_INITGROUPS
Victor Stinner8c62be82010-05-06 00:08:46 +000013858 {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__},
Antoine Pitroub7572f02009-12-02 20:46:48 +000013859#endif /* HAVE_INITGROUPS */
Larry Hastings2f936352014-08-05 14:04:04 +100013860 OS_GETPGID_METHODDEF
13861 OS_SETPGRP_METHODDEF
13862 OS_WAIT_METHODDEF
13863 OS_WAIT3_METHODDEF
13864 OS_WAIT4_METHODDEF
13865 OS_WAITID_METHODDEF
13866 OS_WAITPID_METHODDEF
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -080013867 OS_PIDFD_OPEN_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013868 OS_GETSID_METHODDEF
13869 OS_SETSID_METHODDEF
13870 OS_SETPGID_METHODDEF
13871 OS_TCGETPGRP_METHODDEF
13872 OS_TCSETPGRP_METHODDEF
13873 OS_OPEN_METHODDEF
13874 OS_CLOSE_METHODDEF
13875 OS_CLOSERANGE_METHODDEF
13876 OS_DEVICE_ENCODING_METHODDEF
13877 OS_DUP_METHODDEF
13878 OS_DUP2_METHODDEF
13879 OS_LOCKF_METHODDEF
13880 OS_LSEEK_METHODDEF
13881 OS_READ_METHODDEF
13882 OS_READV_METHODDEF
13883 OS_PREAD_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013884 OS_PREADV_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013885 OS_WRITE_METHODDEF
13886 OS_WRITEV_METHODDEF
13887 OS_PWRITE_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013888 OS_PWRITEV_METHODDEF
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013889#ifdef HAVE_SENDFILE
Serhiy Storchaka62be7422018-11-27 13:27:31 +020013890 {"sendfile", (PyCFunction)(void(*)(void))posix_sendfile, METH_VARARGS | METH_KEYWORDS,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013891 posix_sendfile__doc__},
13892#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013893 OS_FSTAT_METHODDEF
13894 OS_ISATTY_METHODDEF
13895 OS_PIPE_METHODDEF
13896 OS_PIPE2_METHODDEF
13897 OS_MKFIFO_METHODDEF
13898 OS_MKNOD_METHODDEF
13899 OS_MAJOR_METHODDEF
13900 OS_MINOR_METHODDEF
13901 OS_MAKEDEV_METHODDEF
13902 OS_FTRUNCATE_METHODDEF
13903 OS_TRUNCATE_METHODDEF
13904 OS_POSIX_FALLOCATE_METHODDEF
13905 OS_POSIX_FADVISE_METHODDEF
13906 OS_PUTENV_METHODDEF
13907 OS_UNSETENV_METHODDEF
13908 OS_STRERROR_METHODDEF
13909 OS_FCHDIR_METHODDEF
13910 OS_FSYNC_METHODDEF
13911 OS_SYNC_METHODDEF
13912 OS_FDATASYNC_METHODDEF
13913 OS_WCOREDUMP_METHODDEF
13914 OS_WIFCONTINUED_METHODDEF
13915 OS_WIFSTOPPED_METHODDEF
13916 OS_WIFSIGNALED_METHODDEF
13917 OS_WIFEXITED_METHODDEF
13918 OS_WEXITSTATUS_METHODDEF
13919 OS_WTERMSIG_METHODDEF
13920 OS_WSTOPSIG_METHODDEF
13921 OS_FSTATVFS_METHODDEF
13922 OS_STATVFS_METHODDEF
13923 OS_CONFSTR_METHODDEF
13924 OS_SYSCONF_METHODDEF
13925 OS_FPATHCONF_METHODDEF
13926 OS_PATHCONF_METHODDEF
13927 OS_ABORT_METHODDEF
Serhiy Storchakaf0b50152015-05-13 00:52:39 +030013928 OS__GETFULLPATHNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013929 OS__GETDISKUSAGE_METHODDEF
13930 OS__GETFINALPATHNAME_METHODDEF
13931 OS__GETVOLUMEPATHNAME_METHODDEF
13932 OS_GETLOADAVG_METHODDEF
13933 OS_URANDOM_METHODDEF
13934 OS_SETRESUID_METHODDEF
13935 OS_SETRESGID_METHODDEF
13936 OS_GETRESUID_METHODDEF
13937 OS_GETRESGID_METHODDEF
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000013938
Larry Hastings2f936352014-08-05 14:04:04 +100013939 OS_GETXATTR_METHODDEF
13940 OS_SETXATTR_METHODDEF
13941 OS_REMOVEXATTR_METHODDEF
13942 OS_LISTXATTR_METHODDEF
13943
Antoine Pitroubcf2b592012-02-08 23:28:36 +010013944#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
13945 {"get_terminal_size", get_terminal_size, METH_VARARGS, termsize__doc__},
13946#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013947 OS_CPU_COUNT_METHODDEF
13948 OS_GET_INHERITABLE_METHODDEF
13949 OS_SET_INHERITABLE_METHODDEF
13950 OS_GET_HANDLE_INHERITABLE_METHODDEF
13951 OS_SET_HANDLE_INHERITABLE_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013952#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013953 OS_GET_BLOCKING_METHODDEF
13954 OS_SET_BLOCKING_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013955#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013956 OS_SCANDIR_METHODDEF
Ethan Furman410ef8e2016-06-04 12:06:26 -070013957 OS_FSPATH_METHODDEF
Victor Stinner9b1f4742016-09-06 16:18:52 -070013958 OS_GETRANDOM_METHODDEF
Zackery Spytz43fdbd22019-05-29 13:57:07 -060013959 OS_MEMFD_CREATE_METHODDEF
Steve Dower2438cdf2019-03-29 16:37:16 -070013960#ifdef MS_WINDOWS
13961 OS__ADD_DLL_DIRECTORY_METHODDEF
13962 OS__REMOVE_DLL_DIRECTORY_METHODDEF
13963#endif
Victor Stinner8c62be82010-05-06 00:08:46 +000013964 {NULL, NULL} /* Sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013965};
13966
Barry Warsaw4a342091996-12-19 23:50:02 +000013967static int
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013968all_ins(PyObject *m)
Barry Warsaw4a342091996-12-19 23:50:02 +000013969{
Guido van Rossum94f6f721999-01-06 18:42:14 +000013970#ifdef F_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013971 if (PyModule_AddIntMacro(m, F_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013972#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013973#ifdef R_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013974 if (PyModule_AddIntMacro(m, R_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013975#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013976#ifdef W_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013977 if (PyModule_AddIntMacro(m, W_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013978#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013979#ifdef X_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013980 if (PyModule_AddIntMacro(m, X_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013981#endif
Fred Drakec9680921999-12-13 16:37:25 +000013982#ifdef NGROUPS_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013983 if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
Fred Drakec9680921999-12-13 16:37:25 +000013984#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013985#ifdef TMP_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013986 if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013987#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013988#ifdef WCONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013989 if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013990#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013991#ifdef WNOHANG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013992 if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013993#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013994#ifdef WUNTRACED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013995 if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013996#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013997#ifdef O_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013998 if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013999#endif
14000#ifdef O_WRONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014001 if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014002#endif
14003#ifdef O_RDWR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014004 if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014005#endif
14006#ifdef O_NDELAY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014007 if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014008#endif
14009#ifdef O_NONBLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014010 if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014011#endif
14012#ifdef O_APPEND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014013 if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014014#endif
14015#ifdef O_DSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014016 if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014017#endif
14018#ifdef O_RSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014019 if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014020#endif
14021#ifdef O_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014022 if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014023#endif
14024#ifdef O_NOCTTY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014025 if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014026#endif
14027#ifdef O_CREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014028 if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014029#endif
14030#ifdef O_EXCL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014031 if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014032#endif
14033#ifdef O_TRUNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014034 if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000014035#endif
Guido van Rossum98d9d091997-08-08 21:48:51 +000014036#ifdef O_BINARY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014037 if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000014038#endif
14039#ifdef O_TEXT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014040 if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000014041#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020014042#ifdef O_XATTR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014043 if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020014044#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014045#ifdef O_LARGEFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014046 if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014047#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020014048#ifndef __GNU__
Skip Montanaro5ff14922005-05-16 02:42:22 +000014049#ifdef O_SHLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014050 if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000014051#endif
14052#ifdef O_EXLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014053 if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000014054#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020014055#endif
Jesus Ceacf381202012-04-24 20:44:40 +020014056#ifdef O_EXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014057 if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020014058#endif
14059#ifdef O_SEARCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014060 if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020014061#endif
Benjamin Peterson3b965a22013-03-13 10:27:41 -050014062#ifdef O_PATH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014063 if (PyModule_AddIntMacro(m, O_PATH)) return -1;
Benjamin Peterson3b965a22013-03-13 10:27:41 -050014064#endif
Jesus Ceacf381202012-04-24 20:44:40 +020014065#ifdef O_TTY_INIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014066 if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020014067#endif
Christian Heimes177b3f92013-08-16 14:35:09 +020014068#ifdef O_TMPFILE
14069 if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
14070#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014071#ifdef PRIO_PROCESS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014072 if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014073#endif
14074#ifdef PRIO_PGRP
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014075 if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014076#endif
14077#ifdef PRIO_USER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014078 if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014079#endif
Charles-François Natali1e045b12011-05-22 20:42:32 +020014080#ifdef O_CLOEXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014081 if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
Charles-François Natali1e045b12011-05-22 20:42:32 +020014082#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020014083#ifdef O_ACCMODE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014084 if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020014085#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000014086
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014087
Jesus Cea94363612012-06-22 18:32:07 +020014088#ifdef SEEK_HOLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014089 if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020014090#endif
14091#ifdef SEEK_DATA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014092 if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020014093#endif
14094
Tim Peters5aa91602002-01-30 05:46:57 +000014095/* MS Windows */
14096#ifdef O_NOINHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000014097 /* Don't inherit in child processes. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014098 if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014099#endif
14100#ifdef _O_SHORT_LIVED
Victor Stinner8c62be82010-05-06 00:08:46 +000014101 /* Optimize for short life (keep in memory). */
14102 /* MS forgot to define this one with a non-underscore form too. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014103 if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014104#endif
14105#ifdef O_TEMPORARY
Victor Stinner8c62be82010-05-06 00:08:46 +000014106 /* Automatically delete when last handle is closed. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014107 if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014108#endif
14109#ifdef O_RANDOM
Victor Stinner8c62be82010-05-06 00:08:46 +000014110 /* Optimize for random access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014111 if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014112#endif
14113#ifdef O_SEQUENTIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000014114 /* Optimize for sequential access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014115 if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000014116#endif
14117
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014118/* GNU extensions. */
Alexandre Vassalottibee32532008-05-16 18:15:12 +000014119#ifdef O_ASYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000014120 /* Send a SIGIO signal whenever input or output
14121 becomes available on file descriptor */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014122 if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
Alexandre Vassalottibee32532008-05-16 18:15:12 +000014123#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014124#ifdef O_DIRECT
Victor Stinner8c62be82010-05-06 00:08:46 +000014125 /* Direct disk access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014126 if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014127#endif
14128#ifdef O_DIRECTORY
Victor Stinner8c62be82010-05-06 00:08:46 +000014129 /* Must be a directory. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014130 if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014131#endif
14132#ifdef O_NOFOLLOW
Victor Stinner8c62be82010-05-06 00:08:46 +000014133 /* Do not follow links. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014134 if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000014135#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020014136#ifdef O_NOLINKS
14137 /* Fails if link count of the named file is greater than 1 */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014138 if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020014139#endif
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000014140#ifdef O_NOATIME
Victor Stinner8c62be82010-05-06 00:08:46 +000014141 /* Do not update the access time. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014142 if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000014143#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +000014144
Victor Stinner8c62be82010-05-06 00:08:46 +000014145 /* These come from sysexits.h */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014146#ifdef EX_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014147 if (PyModule_AddIntMacro(m, EX_OK)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014148#endif /* EX_OK */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014149#ifdef EX_USAGE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014150 if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014151#endif /* EX_USAGE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014152#ifdef EX_DATAERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014153 if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014154#endif /* EX_DATAERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014155#ifdef EX_NOINPUT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014156 if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014157#endif /* EX_NOINPUT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014158#ifdef EX_NOUSER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014159 if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014160#endif /* EX_NOUSER */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014161#ifdef EX_NOHOST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014162 if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014163#endif /* EX_NOHOST */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014164#ifdef EX_UNAVAILABLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014165 if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014166#endif /* EX_UNAVAILABLE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014167#ifdef EX_SOFTWARE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014168 if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014169#endif /* EX_SOFTWARE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014170#ifdef EX_OSERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014171 if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014172#endif /* EX_OSERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014173#ifdef EX_OSFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014174 if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014175#endif /* EX_OSFILE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014176#ifdef EX_CANTCREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014177 if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014178#endif /* EX_CANTCREAT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014179#ifdef EX_IOERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014180 if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014181#endif /* EX_IOERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014182#ifdef EX_TEMPFAIL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014183 if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014184#endif /* EX_TEMPFAIL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014185#ifdef EX_PROTOCOL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014186 if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014187#endif /* EX_PROTOCOL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014188#ifdef EX_NOPERM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014189 if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014190#endif /* EX_NOPERM */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014191#ifdef EX_CONFIG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014192 if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014193#endif /* EX_CONFIG */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014194#ifdef EX_NOTFOUND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014195 if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014196#endif /* EX_NOTFOUND */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014197
Amaury Forgeot d'Arc66d00ad2010-09-10 18:11:45 +000014198 /* statvfs */
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014199#ifdef ST_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014200 if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014201#endif /* ST_RDONLY */
14202#ifdef ST_NOSUID
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014203 if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014204#endif /* ST_NOSUID */
14205
doko@ubuntu.comca616a22013-12-08 15:23:07 +010014206 /* GNU extensions */
14207#ifdef ST_NODEV
14208 if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
14209#endif /* ST_NODEV */
14210#ifdef ST_NOEXEC
14211 if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
14212#endif /* ST_NOEXEC */
14213#ifdef ST_SYNCHRONOUS
14214 if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
14215#endif /* ST_SYNCHRONOUS */
14216#ifdef ST_MANDLOCK
14217 if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
14218#endif /* ST_MANDLOCK */
14219#ifdef ST_WRITE
14220 if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
14221#endif /* ST_WRITE */
14222#ifdef ST_APPEND
14223 if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
14224#endif /* ST_APPEND */
14225#ifdef ST_NOATIME
14226 if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
14227#endif /* ST_NOATIME */
14228#ifdef ST_NODIRATIME
14229 if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
14230#endif /* ST_NODIRATIME */
14231#ifdef ST_RELATIME
14232 if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
14233#endif /* ST_RELATIME */
14234
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014235 /* FreeBSD sendfile() constants */
14236#ifdef SF_NODISKIO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014237 if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014238#endif
14239#ifdef SF_MNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014240 if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014241#endif
14242#ifdef SF_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014243 if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014244#endif
14245
Ross Lagerwall7807c352011-03-17 20:20:30 +020014246 /* constants for posix_fadvise */
14247#ifdef POSIX_FADV_NORMAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014248 if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014249#endif
14250#ifdef POSIX_FADV_SEQUENTIAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014251 if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014252#endif
14253#ifdef POSIX_FADV_RANDOM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014254 if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014255#endif
14256#ifdef POSIX_FADV_NOREUSE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014257 if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014258#endif
14259#ifdef POSIX_FADV_WILLNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014260 if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014261#endif
14262#ifdef POSIX_FADV_DONTNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014263 if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014264#endif
14265
14266 /* constants for waitid */
14267#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014268 if (PyModule_AddIntMacro(m, P_PID)) return -1;
14269 if (PyModule_AddIntMacro(m, P_PGID)) return -1;
14270 if (PyModule_AddIntMacro(m, P_ALL)) return -1;
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080014271#ifdef P_PIDFD
14272 if (PyModule_AddIntMacro(m, P_PIDFD)) return -1;
14273#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014274#endif
14275#ifdef WEXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014276 if (PyModule_AddIntMacro(m, WEXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014277#endif
14278#ifdef WNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014279 if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014280#endif
14281#ifdef WSTOPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014282 if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014283#endif
14284#ifdef CLD_EXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014285 if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014286#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014287#ifdef CLD_KILLED
14288 if (PyModule_AddIntMacro(m, CLD_KILLED)) return -1;
14289#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014290#ifdef CLD_DUMPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014291 if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014292#endif
14293#ifdef CLD_TRAPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014294 if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014295#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014296#ifdef CLD_STOPPED
14297 if (PyModule_AddIntMacro(m, CLD_STOPPED)) return -1;
14298#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014299#ifdef CLD_CONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014300 if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014301#endif
14302
14303 /* constants for lockf */
14304#ifdef F_LOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014305 if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014306#endif
14307#ifdef F_TLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014308 if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014309#endif
14310#ifdef F_ULOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014311 if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014312#endif
14313#ifdef F_TEST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014314 if (PyModule_AddIntMacro(m, F_TEST)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014315#endif
14316
Pablo Galindo4defba32018-01-27 16:16:37 +000014317#ifdef RWF_DSYNC
14318 if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
14319#endif
14320#ifdef RWF_HIPRI
14321 if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
14322#endif
14323#ifdef RWF_SYNC
14324 if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
14325#endif
14326#ifdef RWF_NOWAIT
14327 if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
14328#endif
14329
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000014330/* constants for posix_spawn */
14331#ifdef HAVE_POSIX_SPAWN
14332 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
14333 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
14334 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
14335#endif
14336
pxinwrf2d7ac72019-05-21 18:46:37 +080014337#if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014338 if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
14339 if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014340 if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
pxinwrf2d7ac72019-05-21 18:46:37 +080014341#endif
14342#ifdef HAVE_SPAWNV
14343 if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014344 if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
Guido van Rossum246bc171999-02-01 23:54:31 +000014345#endif
14346
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014347#ifdef HAVE_SCHED_H
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014348#ifdef SCHED_OTHER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014349 if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014350#endif
14351#ifdef SCHED_FIFO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014352 if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014353#endif
14354#ifdef SCHED_RR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014355 if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014356#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014357#ifdef SCHED_SPORADIC
messi Liao0d322182017-06-13 22:30:43 +080014358 if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014359#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014360#ifdef SCHED_BATCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014361 if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014362#endif
14363#ifdef SCHED_IDLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014364 if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014365#endif
14366#ifdef SCHED_RESET_ON_FORK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014367 if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014368#endif
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014369#ifdef SCHED_SYS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014370 if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014371#endif
14372#ifdef SCHED_IA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014373 if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014374#endif
14375#ifdef SCHED_FSS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014376 if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014377#endif
14378#ifdef SCHED_FX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014379 if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014380#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014381#endif
14382
Benjamin Peterson9428d532011-09-14 11:45:52 -040014383#ifdef USE_XATTRS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014384 if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
14385 if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
14386 if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
Benjamin Peterson799bd802011-08-31 22:15:17 -040014387#endif
14388
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014389#if HAVE_DECL_RTLD_LAZY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014390 if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014391#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014392#if HAVE_DECL_RTLD_NOW
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014393 if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014394#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014395#if HAVE_DECL_RTLD_GLOBAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014396 if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014397#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014398#if HAVE_DECL_RTLD_LOCAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014399 if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014400#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014401#if HAVE_DECL_RTLD_NODELETE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014402 if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014403#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014404#if HAVE_DECL_RTLD_NOLOAD
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014405 if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014406#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014407#if HAVE_DECL_RTLD_DEEPBIND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014408 if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014409#endif
Michael Feltc5ae1692017-12-19 13:58:49 +010014410#if HAVE_DECL_RTLD_MEMBER
14411 if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
14412#endif
Victor Stinner8b905bd2011-10-25 13:34:04 +020014413
Victor Stinner9b1f4742016-09-06 16:18:52 -070014414#ifdef HAVE_GETRANDOM_SYSCALL
14415 if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
14416 if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
14417#endif
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014418#ifdef HAVE_MEMFD_CREATE
14419 if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
14420 if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
14421#ifdef MFD_HUGETLB
14422 if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014423#endif
14424#ifdef MFD_HUGE_SHIFT
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014425 if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014426#endif
14427#ifdef MFD_HUGE_MASK
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014428 if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014429#endif
14430#ifdef MFD_HUGE_64KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014431 if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014432#endif
14433#ifdef MFD_HUGE_512KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014434 if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014435#endif
14436#ifdef MFD_HUGE_1MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014437 if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014438#endif
14439#ifdef MFD_HUGE_2MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014440 if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014441#endif
14442#ifdef MFD_HUGE_8MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014443 if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014444#endif
14445#ifdef MFD_HUGE_16MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014446 if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014447#endif
14448#ifdef MFD_HUGE_32MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014449 if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014450#endif
14451#ifdef MFD_HUGE_256MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014452 if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014453#endif
14454#ifdef MFD_HUGE_512MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014455 if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014456#endif
14457#ifdef MFD_HUGE_1GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014458 if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014459#endif
14460#ifdef MFD_HUGE_2GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014461 if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014462#endif
14463#ifdef MFD_HUGE_16GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014464 if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
14465#endif
14466#endif
Victor Stinner9b1f4742016-09-06 16:18:52 -070014467
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020014468#if defined(__APPLE__)
14469 if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
14470#endif
14471
Steve Dower2438cdf2019-03-29 16:37:16 -070014472#ifdef MS_WINDOWS
14473 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
14474 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
14475 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
14476 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
14477 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
14478#endif
14479
Victor Stinner8c62be82010-05-06 00:08:46 +000014480 return 0;
Barry Warsaw4a342091996-12-19 23:50:02 +000014481}
14482
14483
Martin v. Löwis1a214512008-06-11 05:26:20 +000014484static struct PyModuleDef posixmodule = {
Victor Stinner8c62be82010-05-06 00:08:46 +000014485 PyModuleDef_HEAD_INIT,
14486 MODNAME,
14487 posix__doc__,
Eddie Elizondob3966632019-11-05 07:16:14 -080014488 sizeof(_posixstate),
Victor Stinner8c62be82010-05-06 00:08:46 +000014489 posix_methods,
14490 NULL,
Eddie Elizondob3966632019-11-05 07:16:14 -080014491 _posix_traverse,
14492 _posix_clear,
14493 _posix_free,
Martin v. Löwis1a214512008-06-11 05:26:20 +000014494};
14495
14496
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014497static const char * const have_functions[] = {
Larry Hastings9cf065c2012-06-22 16:30:09 -070014498
14499#ifdef HAVE_FACCESSAT
14500 "HAVE_FACCESSAT",
14501#endif
14502
14503#ifdef HAVE_FCHDIR
14504 "HAVE_FCHDIR",
14505#endif
14506
14507#ifdef HAVE_FCHMOD
14508 "HAVE_FCHMOD",
14509#endif
14510
14511#ifdef HAVE_FCHMODAT
14512 "HAVE_FCHMODAT",
14513#endif
14514
14515#ifdef HAVE_FCHOWN
14516 "HAVE_FCHOWN",
14517#endif
14518
Larry Hastings00964ed2013-08-12 13:49:30 -040014519#ifdef HAVE_FCHOWNAT
14520 "HAVE_FCHOWNAT",
14521#endif
14522
Larry Hastings9cf065c2012-06-22 16:30:09 -070014523#ifdef HAVE_FEXECVE
14524 "HAVE_FEXECVE",
14525#endif
14526
14527#ifdef HAVE_FDOPENDIR
14528 "HAVE_FDOPENDIR",
14529#endif
14530
Georg Brandl306336b2012-06-24 12:55:33 +020014531#ifdef HAVE_FPATHCONF
14532 "HAVE_FPATHCONF",
14533#endif
14534
Larry Hastings9cf065c2012-06-22 16:30:09 -070014535#ifdef HAVE_FSTATAT
14536 "HAVE_FSTATAT",
14537#endif
14538
14539#ifdef HAVE_FSTATVFS
14540 "HAVE_FSTATVFS",
14541#endif
14542
Steve Dowerfe0a41a2015-03-20 19:50:46 -070014543#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Georg Brandl306336b2012-06-24 12:55:33 +020014544 "HAVE_FTRUNCATE",
14545#endif
14546
Larry Hastings9cf065c2012-06-22 16:30:09 -070014547#ifdef HAVE_FUTIMENS
14548 "HAVE_FUTIMENS",
14549#endif
14550
14551#ifdef HAVE_FUTIMES
14552 "HAVE_FUTIMES",
14553#endif
14554
14555#ifdef HAVE_FUTIMESAT
14556 "HAVE_FUTIMESAT",
14557#endif
14558
14559#ifdef HAVE_LINKAT
14560 "HAVE_LINKAT",
14561#endif
14562
14563#ifdef HAVE_LCHFLAGS
14564 "HAVE_LCHFLAGS",
14565#endif
14566
14567#ifdef HAVE_LCHMOD
14568 "HAVE_LCHMOD",
14569#endif
14570
14571#ifdef HAVE_LCHOWN
14572 "HAVE_LCHOWN",
14573#endif
14574
14575#ifdef HAVE_LSTAT
14576 "HAVE_LSTAT",
14577#endif
14578
14579#ifdef HAVE_LUTIMES
14580 "HAVE_LUTIMES",
14581#endif
14582
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014583#ifdef HAVE_MEMFD_CREATE
14584 "HAVE_MEMFD_CREATE",
14585#endif
14586
Larry Hastings9cf065c2012-06-22 16:30:09 -070014587#ifdef HAVE_MKDIRAT
14588 "HAVE_MKDIRAT",
14589#endif
14590
14591#ifdef HAVE_MKFIFOAT
14592 "HAVE_MKFIFOAT",
14593#endif
14594
14595#ifdef HAVE_MKNODAT
14596 "HAVE_MKNODAT",
14597#endif
14598
14599#ifdef HAVE_OPENAT
14600 "HAVE_OPENAT",
14601#endif
14602
14603#ifdef HAVE_READLINKAT
14604 "HAVE_READLINKAT",
14605#endif
14606
14607#ifdef HAVE_RENAMEAT
14608 "HAVE_RENAMEAT",
14609#endif
14610
14611#ifdef HAVE_SYMLINKAT
14612 "HAVE_SYMLINKAT",
14613#endif
14614
14615#ifdef HAVE_UNLINKAT
14616 "HAVE_UNLINKAT",
14617#endif
14618
14619#ifdef HAVE_UTIMENSAT
14620 "HAVE_UTIMENSAT",
14621#endif
14622
14623#ifdef MS_WINDOWS
14624 "MS_WINDOWS",
14625#endif
14626
14627 NULL
14628};
14629
14630
Mark Hammondfe51c6d2002-08-02 02:27:13 +000014631PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +000014632INITFUNC(void)
Guido van Rossumb6775db1994-08-01 11:34:53 +000014633{
Victor Stinner8c62be82010-05-06 00:08:46 +000014634 PyObject *m, *v;
Larry Hastings9cf065c2012-06-22 16:30:09 -070014635 PyObject *list;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014636 const char * const *trace;
Tim Peters5aa91602002-01-30 05:46:57 +000014637
Eddie Elizondob3966632019-11-05 07:16:14 -080014638 m = PyState_FindModule(&posixmodule);
14639 if (m != NULL) {
14640 Py_INCREF(m);
14641 return m;
14642 }
14643
Victor Stinner8c62be82010-05-06 00:08:46 +000014644 m = PyModule_Create(&posixmodule);
14645 if (m == NULL)
14646 return NULL;
Tim Peters5aa91602002-01-30 05:46:57 +000014647
Victor Stinner8c62be82010-05-06 00:08:46 +000014648 /* Initialize environ dictionary */
14649 v = convertenviron();
14650 Py_XINCREF(v);
14651 if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
14652 return NULL;
14653 Py_DECREF(v);
Fred Drakec9680921999-12-13 16:37:25 +000014654
Victor Stinner8c62be82010-05-06 00:08:46 +000014655 if (all_ins(m))
14656 return NULL;
Barry Warsaw4a342091996-12-19 23:50:02 +000014657
Victor Stinner8c62be82010-05-06 00:08:46 +000014658 if (setup_confname_tables(m))
14659 return NULL;
Fred Drakebec628d1999-12-15 18:31:10 +000014660
Victor Stinner8c62be82010-05-06 00:08:46 +000014661 Py_INCREF(PyExc_OSError);
14662 PyModule_AddObject(m, "error", PyExc_OSError);
Fred Drake762e2061999-08-26 17:23:54 +000014663
Ross Lagerwall7807c352011-03-17 20:20:30 +020014664#if defined(HAVE_WAITID) && !defined(__APPLE__)
Eddie Elizondob3966632019-11-05 07:16:14 -080014665 waitid_result_desc.name = MODNAME ".waitid_result";
14666 PyObject *WaitidResultType = (PyObject *)PyStructSequence_NewType(&waitid_result_desc);
14667 if (WaitidResultType == NULL) {
14668 return NULL;
14669 }
14670 Py_INCREF(WaitidResultType);
14671 PyModule_AddObject(m, "waitid_result", WaitidResultType);
Hai Shif707d942020-03-16 21:15:01 +080014672 get_posix_state(m)->WaitidResultType = WaitidResultType;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014673#endif
14674
Eddie Elizondob3966632019-11-05 07:16:14 -080014675 stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
14676 stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
14677 stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
14678 stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
14679 PyObject *StatResultType = (PyObject *)PyStructSequence_NewType(&stat_result_desc);
14680 if (StatResultType == NULL) {
14681 return NULL;
14682 }
14683 Py_INCREF(StatResultType);
14684 PyModule_AddObject(m, "stat_result", StatResultType);
Hai Shif707d942020-03-16 21:15:01 +080014685 get_posix_state(m)->StatResultType = StatResultType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014686 structseq_new = ((PyTypeObject *)StatResultType)->tp_new;
14687 ((PyTypeObject *)StatResultType)->tp_new = statresult_new;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014688
Eddie Elizondob3966632019-11-05 07:16:14 -080014689 statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
14690 PyObject *StatVFSResultType = (PyObject *)PyStructSequence_NewType(&statvfs_result_desc);
14691 if (StatVFSResultType == NULL) {
14692 return NULL;
14693 }
14694 Py_INCREF(StatVFSResultType);
14695 PyModule_AddObject(m, "statvfs_result", StatVFSResultType);
Hai Shif707d942020-03-16 21:15:01 +080014696 get_posix_state(m)->StatVFSResultType = StatVFSResultType;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014697#ifdef NEED_TICKS_PER_SECOND
14698# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Eddie Elizondob3966632019-11-05 07:16:14 -080014699 ticks_per_second = sysconf(_SC_CLK_TCK);
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014700# elif defined(HZ)
Eddie Elizondob3966632019-11-05 07:16:14 -080014701 ticks_per_second = HZ;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014702# else
Eddie Elizondob3966632019-11-05 07:16:14 -080014703 ticks_per_second = 60; /* magic fallback value; may be bogus */
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014704# endif
14705#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014706
William Orr81574b82018-10-01 22:19:56 -070014707#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Eddie Elizondob3966632019-11-05 07:16:14 -080014708 sched_param_desc.name = MODNAME ".sched_param";
14709 PyObject *SchedParamType = (PyObject *)PyStructSequence_NewType(&sched_param_desc);
14710 if (SchedParamType == NULL) {
14711 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000014712 }
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014713 Py_INCREF(SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -080014714 PyModule_AddObject(m, "sched_param", SchedParamType);
Hai Shif707d942020-03-16 21:15:01 +080014715 get_posix_state(m)->SchedParamType = SchedParamType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014716 ((PyTypeObject *)SchedParamType)->tp_new = os_sched_param;
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014717#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +000014718
Eddie Elizondob3966632019-11-05 07:16:14 -080014719 /* initialize TerminalSize_info */
14720 PyObject *TerminalSizeType = (PyObject *)PyStructSequence_NewType(&TerminalSize_desc);
14721 if (TerminalSizeType == NULL) {
14722 return NULL;
14723 }
14724 Py_INCREF(TerminalSizeType);
14725 PyModule_AddObject(m, "terminal_size", TerminalSizeType);
Hai Shif707d942020-03-16 21:15:01 +080014726 get_posix_state(m)->TerminalSizeType = TerminalSizeType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014727
14728 /* initialize scandir types */
14729 PyObject *ScandirIteratorType = PyType_FromSpec(&ScandirIteratorType_spec);
14730 if (ScandirIteratorType == NULL) {
14731 return NULL;
14732 }
Hai Shif707d942020-03-16 21:15:01 +080014733 get_posix_state(m)->ScandirIteratorType = ScandirIteratorType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014734
14735 PyObject *DirEntryType = PyType_FromSpec(&DirEntryType_spec);
14736 if (DirEntryType == NULL) {
14737 return NULL;
14738 }
14739 Py_INCREF(DirEntryType);
14740 PyModule_AddObject(m, "DirEntry", DirEntryType);
Hai Shif707d942020-03-16 21:15:01 +080014741 get_posix_state(m)->DirEntryType = DirEntryType;
Eddie Elizondob3966632019-11-05 07:16:14 -080014742
Larry Hastings605a62d2012-06-24 04:33:36 -070014743 times_result_desc.name = MODNAME ".times_result";
Eddie Elizondob3966632019-11-05 07:16:14 -080014744 PyObject *TimesResultType = (PyObject *)PyStructSequence_NewType(&times_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014745 if (TimesResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014746 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014747 }
Eddie Elizondob3966632019-11-05 07:16:14 -080014748 Py_INCREF(TimesResultType);
14749 PyModule_AddObject(m, "times_result", TimesResultType);
Hai Shif707d942020-03-16 21:15:01 +080014750 get_posix_state(m)->TimesResultType = TimesResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070014751
Eddie Elizondob3966632019-11-05 07:16:14 -080014752 PyTypeObject *UnameResultType = PyStructSequence_NewType(&uname_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014753 if (UnameResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014754 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014755 }
Eddie Elizondob3966632019-11-05 07:16:14 -080014756 Py_INCREF(UnameResultType);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014757 PyModule_AddObject(m, "uname_result", (PyObject *)UnameResultType);
Hai Shif707d942020-03-16 21:15:01 +080014758 get_posix_state(m)->UnameResultType = (PyObject *)UnameResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070014759
Thomas Wouters477c8d52006-05-27 19:21:47 +000014760#ifdef __APPLE__
Victor Stinner8c62be82010-05-06 00:08:46 +000014761 /*
14762 * Step 2 of weak-linking support on Mac OS X.
14763 *
14764 * The code below removes functions that are not available on the
14765 * currently active platform.
14766 *
14767 * This block allow one to use a python binary that was build on
Larry Hastings9cf065c2012-06-22 16:30:09 -070014768 * OSX 10.4 on OSX 10.3, without losing access to new APIs on
Victor Stinner8c62be82010-05-06 00:08:46 +000014769 * OSX 10.4.
14770 */
Thomas Wouters477c8d52006-05-27 19:21:47 +000014771#ifdef HAVE_FSTATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014772 if (fstatvfs == NULL) {
14773 if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
14774 return NULL;
14775 }
14776 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014777#endif /* HAVE_FSTATVFS */
14778
14779#ifdef HAVE_STATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014780 if (statvfs == NULL) {
14781 if (PyObject_DelAttrString(m, "statvfs") == -1) {
14782 return NULL;
14783 }
14784 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014785#endif /* HAVE_STATVFS */
14786
14787# ifdef HAVE_LCHOWN
Victor Stinner8c62be82010-05-06 00:08:46 +000014788 if (lchown == NULL) {
14789 if (PyObject_DelAttrString(m, "lchown") == -1) {
14790 return NULL;
14791 }
14792 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014793#endif /* HAVE_LCHOWN */
14794
14795
14796#endif /* __APPLE__ */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014797
Hai Shif707d942020-03-16 21:15:01 +080014798 if ((get_posix_state(m)->billion = PyLong_FromLong(1000000000)) == NULL)
Eddie Elizondob3966632019-11-05 07:16:14 -080014799 return NULL;
14800#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
Hai Shif707d942020-03-16 21:15:01 +080014801 get_posix_state(m)->struct_rusage = PyUnicode_InternFromString("struct_rusage");
14802 if (get_posix_state(m)->struct_rusage == NULL)
Eddie Elizondob3966632019-11-05 07:16:14 -080014803 return NULL;
14804#endif
Hai Shif707d942020-03-16 21:15:01 +080014805 get_posix_state(m)->st_mode = PyUnicode_InternFromString("st_mode");
14806 if (get_posix_state(m)->st_mode == NULL)
Larry Hastings6fe20b32012-04-19 15:07:49 -070014807 return NULL;
14808
Larry Hastings9cf065c2012-06-22 16:30:09 -070014809 /* suppress "function not used" warnings */
14810 {
14811 int ignored;
14812 fd_specified("", -1);
14813 follow_symlinks_specified("", 1);
14814 dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
14815 dir_fd_converter(Py_None, &ignored);
14816 dir_fd_unavailable(Py_None, &ignored);
14817 }
14818
14819 /*
14820 * provide list of locally available functions
14821 * so os.py can populate support_* lists
14822 */
14823 list = PyList_New(0);
14824 if (!list)
14825 return NULL;
14826 for (trace = have_functions; *trace; trace++) {
14827 PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
14828 if (!unicode)
14829 return NULL;
14830 if (PyList_Append(list, unicode))
14831 return NULL;
14832 Py_DECREF(unicode);
14833 }
14834 PyModule_AddObject(m, "_have_functions", list);
Ned Deilyeb3be662016-08-15 14:40:38 -040014835
Victor Stinner8c62be82010-05-06 00:08:46 +000014836 return m;
Guido van Rossumb6775db1994-08-01 11:34:53 +000014837}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014838
14839#ifdef __cplusplus
14840}
14841#endif