blob: ec3da4fb2fc6edf3cf6c9b588654cf72036fec53 [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 Stinnercaba55b2018-08-03 15:33:52 +0200454 run_at_forkers(_PyInterpreterState_Get()->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 Stinnercaba55b2018-08-03 15:33:52 +0200465 run_at_forkers(_PyInterpreterState_Get()->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 Stinnercaba55b2018-08-03 15:33:52 +0200479 run_at_forkers(_PyInterpreterState_Get()->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
845#define _posixstate(o) ((_posixstate *)PyModule_GetState(o))
846#define _posixstate_global ((_posixstate *)PyModule_GetState(PyState_FindModule(&posixmodule)))
Larry Hastings9cf065c2012-06-22 16:30:09 -0700847
Larry Hastings9cf065c2012-06-22 16:30:09 -0700848/*
849 * A PyArg_ParseTuple "converter" function
850 * that handles filesystem paths in the manner
851 * preferred by the os module.
852 *
853 * path_converter accepts (Unicode) strings and their
854 * subclasses, and bytes and their subclasses. What
855 * it does with the argument depends on the platform:
856 *
857 * * On Windows, if we get a (Unicode) string we
858 * extract the wchar_t * and return it; if we get
Steve Dowercc16be82016-09-08 10:35:16 -0700859 * bytes we decode to wchar_t * and return that.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700860 *
861 * * On all other platforms, strings are encoded
862 * to bytes using PyUnicode_FSConverter, then we
863 * extract the char * from the bytes object and
864 * return that.
865 *
866 * path_converter also optionally accepts signed
867 * integers (representing open file descriptors) instead
868 * of path strings.
869 *
870 * Input fields:
871 * path.nullable
872 * If nonzero, the path is permitted to be None.
873 * path.allow_fd
874 * If nonzero, the path is permitted to be a file handle
875 * (a signed int) instead of a string.
876 * path.function_name
877 * If non-NULL, path_converter will use that as the name
878 * of the function in error messages.
Larry Hastings31826802013-10-19 00:09:25 -0700879 * (If path.function_name is NULL it omits the function name.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700880 * path.argument_name
881 * If non-NULL, path_converter will use that as the name
882 * of the parameter in error messages.
883 * (If path.argument_name is NULL it uses "path".)
884 *
885 * Output fields:
886 * path.wide
887 * Points to the path if it was expressed as Unicode
888 * and was not encoded. (Only used on Windows.)
889 * path.narrow
890 * Points to the path if it was expressed as bytes,
Steve Dowercc16be82016-09-08 10:35:16 -0700891 * or it was Unicode and was encoded to bytes. (On Windows,
Martin Panterb1321fb2016-10-10 00:38:21 +0000892 * is a non-zero integer if the path was expressed as bytes.
Steve Dowercc16be82016-09-08 10:35:16 -0700893 * The type is deliberately incompatible to prevent misuse.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700894 * path.fd
895 * Contains a file descriptor if path.accept_fd was true
896 * and the caller provided a signed integer instead of any
897 * sort of string.
898 *
899 * WARNING: if your "path" parameter is optional, and is
900 * unspecified, path_converter will never get called.
901 * So if you set allow_fd, you *MUST* initialize path.fd = -1
902 * yourself!
903 * path.length
904 * The length of the path in characters, if specified as
905 * a string.
906 * path.object
Xiang Zhang04316c42017-01-08 23:26:57 +0800907 * The original object passed in (if get a PathLike object,
908 * the result of PyOS_FSPath() is treated as the original object).
909 * Own a reference to the object.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700910 * path.cleanup
911 * For internal use only. May point to a temporary object.
912 * (Pay no attention to the man behind the curtain.)
913 *
914 * At most one of path.wide or path.narrow will be non-NULL.
915 * If path was None and path.nullable was set,
916 * or if path was an integer and path.allow_fd was set,
917 * both path.wide and path.narrow will be NULL
918 * and path.length will be 0.
Georg Brandlf7875592012-06-24 13:58:31 +0200919 *
Larry Hastings9cf065c2012-06-22 16:30:09 -0700920 * path_converter takes care to not write to the path_t
921 * unless it's successful. However it must reset the
922 * "cleanup" field each time it's called.
923 *
924 * Use as follows:
925 * path_t path;
926 * memset(&path, 0, sizeof(path));
927 * PyArg_ParseTuple(args, "O&", path_converter, &path);
928 * // ... use values from path ...
929 * path_cleanup(&path);
930 *
931 * (Note that if PyArg_Parse fails you don't need to call
932 * path_cleanup(). However it is safe to do so.)
933 */
934typedef struct {
Victor Stinner292c8352012-10-30 02:17:38 +0100935 const char *function_name;
936 const char *argument_name;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700937 int nullable;
938 int allow_fd;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300939 const wchar_t *wide;
Steve Dowercc16be82016-09-08 10:35:16 -0700940#ifdef MS_WINDOWS
941 BOOL narrow;
942#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300943 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700944#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700945 int fd;
946 Py_ssize_t length;
947 PyObject *object;
948 PyObject *cleanup;
949} path_t;
950
Steve Dowercc16be82016-09-08 10:35:16 -0700951#ifdef MS_WINDOWS
952#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
953 {function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
954#else
Larry Hastings2f936352014-08-05 14:04:04 +1000955#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
956 {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
Steve Dowercc16be82016-09-08 10:35:16 -0700957#endif
Larry Hastings31826802013-10-19 00:09:25 -0700958
Larry Hastings9cf065c2012-06-22 16:30:09 -0700959static void
Xiang Zhang04316c42017-01-08 23:26:57 +0800960path_cleanup(path_t *path)
961{
962 Py_CLEAR(path->object);
963 Py_CLEAR(path->cleanup);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700964}
965
966static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300967path_converter(PyObject *o, void *p)
968{
Larry Hastings9cf065c2012-06-22 16:30:09 -0700969 path_t *path = (path_t *)p;
Xiang Zhang04316c42017-01-08 23:26:57 +0800970 PyObject *bytes = NULL;
971 Py_ssize_t length = 0;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700972 int is_index, is_buffer, is_bytes, is_unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300973 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700974#ifdef MS_WINDOWS
Xiang Zhang04316c42017-01-08 23:26:57 +0800975 PyObject *wo = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700976 const wchar_t *wide;
977#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700978
979#define FORMAT_EXCEPTION(exc, fmt) \
980 PyErr_Format(exc, "%s%s" fmt, \
981 path->function_name ? path->function_name : "", \
982 path->function_name ? ": " : "", \
983 path->argument_name ? path->argument_name : "path")
984
985 /* Py_CLEANUP_SUPPORTED support */
986 if (o == NULL) {
987 path_cleanup(path);
988 return 1;
989 }
990
Brett Cannon3f9183b2016-08-26 14:44:48 -0700991 /* Ensure it's always safe to call path_cleanup(). */
Xiang Zhang04316c42017-01-08 23:26:57 +0800992 path->object = path->cleanup = NULL;
993 /* path->object owns a reference to the original object */
994 Py_INCREF(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700995
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300996 if ((o == Py_None) && path->nullable) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700997 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700998#ifdef MS_WINDOWS
999 path->narrow = FALSE;
1000#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001001 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001002#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07001003 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001004 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001005 }
1006
Brett Cannon3f9183b2016-08-26 14:44:48 -07001007 /* Only call this here so that we don't treat the return value of
1008 os.fspath() as an fd or buffer. */
1009 is_index = path->allow_fd && PyIndex_Check(o);
1010 is_buffer = PyObject_CheckBuffer(o);
1011 is_bytes = PyBytes_Check(o);
1012 is_unicode = PyUnicode_Check(o);
1013
1014 if (!is_index && !is_buffer && !is_unicode && !is_bytes) {
1015 /* Inline PyOS_FSPath() for better error messages. */
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001016 PyObject *func, *res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001017
1018 func = _PyObject_LookupSpecial(o, &PyId___fspath__);
1019 if (NULL == func) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001020 goto error_format;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001021 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001022 res = _PyObject_CallNoArg(func);
Brett Cannon3f9183b2016-08-26 14:44:48 -07001023 Py_DECREF(func);
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001024 if (NULL == res) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001025 goto error_exit;
1026 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001027 else if (PyUnicode_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001028 is_unicode = 1;
1029 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001030 else if (PyBytes_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001031 is_bytes = 1;
1032 }
1033 else {
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001034 PyErr_Format(PyExc_TypeError,
1035 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -08001036 "not %.200s", _PyType_Name(Py_TYPE(o)),
1037 _PyType_Name(Py_TYPE(res)));
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001038 Py_DECREF(res);
1039 goto error_exit;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001040 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001041
1042 /* still owns a reference to the original object */
1043 Py_DECREF(o);
1044 o = res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001045 }
1046
1047 if (is_unicode) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001048#ifdef MS_WINDOWS
Victor Stinner26c03bd2016-09-19 11:55:44 +02001049 wide = PyUnicode_AsUnicodeAndSize(o, &length);
Victor Stinner59799a82013-11-13 14:17:30 +01001050 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001051 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001052 }
Victor Stinner59799a82013-11-13 14:17:30 +01001053 if (length > 32767) {
1054 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001055 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001056 }
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001057 if (wcslen(wide) != length) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001058 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001059 goto error_exit;
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001060 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001061
1062 path->wide = wide;
Xiang Zhang04316c42017-01-08 23:26:57 +08001063 path->narrow = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001064 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001065 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001066#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001067 if (!PyUnicode_FSConverter(o, &bytes)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001068 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001069 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001070#endif
1071 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001072 else if (is_bytes) {
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001073 bytes = o;
1074 Py_INCREF(bytes);
1075 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001076 else if (is_buffer) {
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03001077 /* XXX Replace PyObject_CheckBuffer with PyBytes_Check in other code
Ville Skyttä49b27342017-08-03 09:00:59 +03001078 after removing support of non-bytes buffer objects. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001079 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1080 "%s%s%s should be %s, not %.200s",
1081 path->function_name ? path->function_name : "",
1082 path->function_name ? ": " : "",
1083 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001084 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1085 "integer or None" :
1086 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1087 path->nullable ? "string, bytes, os.PathLike or None" :
1088 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001089 _PyType_Name(Py_TYPE(o)))) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001090 goto error_exit;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001091 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001092 bytes = PyBytes_FromObject(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001093 if (!bytes) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001094 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001095 }
1096 }
Steve Dowercc16be82016-09-08 10:35:16 -07001097 else if (is_index) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001098 if (!_fd_converter(o, &path->fd)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001099 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001100 }
1101 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001102#ifdef MS_WINDOWS
1103 path->narrow = FALSE;
1104#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001105 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001106#endif
Xiang Zhang04316c42017-01-08 23:26:57 +08001107 goto success_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001108 }
1109 else {
Xiang Zhang04316c42017-01-08 23:26:57 +08001110 error_format:
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001111 PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
1112 path->function_name ? path->function_name : "",
1113 path->function_name ? ": " : "",
1114 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001115 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1116 "integer or None" :
1117 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1118 path->nullable ? "string, bytes, os.PathLike or None" :
1119 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001120 _PyType_Name(Py_TYPE(o)));
Xiang Zhang04316c42017-01-08 23:26:57 +08001121 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001122 }
1123
Larry Hastings9cf065c2012-06-22 16:30:09 -07001124 length = PyBytes_GET_SIZE(bytes);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001125 narrow = PyBytes_AS_STRING(bytes);
Victor Stinner706768c2014-08-16 01:03:39 +02001126 if ((size_t)length != strlen(narrow)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03001127 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001128 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001129 }
1130
Steve Dowercc16be82016-09-08 10:35:16 -07001131#ifdef MS_WINDOWS
1132 wo = PyUnicode_DecodeFSDefaultAndSize(
1133 narrow,
1134 length
1135 );
1136 if (!wo) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001137 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001138 }
1139
Xiang Zhang04316c42017-01-08 23:26:57 +08001140 wide = PyUnicode_AsUnicodeAndSize(wo, &length);
Steve Dowercc16be82016-09-08 10:35:16 -07001141 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001142 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001143 }
1144 if (length > 32767) {
1145 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001146 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001147 }
1148 if (wcslen(wide) != length) {
1149 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001150 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001151 }
1152 path->wide = wide;
1153 path->narrow = TRUE;
Xiang Zhang04316c42017-01-08 23:26:57 +08001154 path->cleanup = wo;
1155 Py_DECREF(bytes);
Steve Dowercc16be82016-09-08 10:35:16 -07001156#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001157 path->wide = NULL;
1158 path->narrow = narrow;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001159 if (bytes == o) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001160 /* Still a reference owned by path->object, don't have to
1161 worry about path->narrow is used after free. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001162 Py_DECREF(bytes);
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001163 }
1164 else {
1165 path->cleanup = bytes;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001166 }
Xiang Zhang04316c42017-01-08 23:26:57 +08001167#endif
1168 path->fd = -1;
1169
1170 success_exit:
1171 path->length = length;
1172 path->object = o;
1173 return Py_CLEANUP_SUPPORTED;
1174
1175 error_exit:
1176 Py_XDECREF(o);
1177 Py_XDECREF(bytes);
1178#ifdef MS_WINDOWS
1179 Py_XDECREF(wo);
1180#endif
1181 return 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001182}
1183
1184static void
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001185argument_unavailable_error(const char *function_name, const char *argument_name)
1186{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001187 PyErr_Format(PyExc_NotImplementedError,
1188 "%s%s%s unavailable on this platform",
1189 (function_name != NULL) ? function_name : "",
1190 (function_name != NULL) ? ": ": "",
1191 argument_name);
1192}
1193
1194static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001195dir_fd_unavailable(PyObject *o, void *p)
1196{
1197 int dir_fd;
1198 if (!dir_fd_converter(o, &dir_fd))
Larry Hastings9cf065c2012-06-22 16:30:09 -07001199 return 0;
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001200 if (dir_fd != DEFAULT_DIR_FD) {
1201 argument_unavailable_error(NULL, "dir_fd");
1202 return 0;
1203 }
1204 *(int *)p = dir_fd;
1205 return 1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001206}
1207
1208static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001209fd_specified(const char *function_name, int fd)
1210{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001211 if (fd == -1)
1212 return 0;
1213
1214 argument_unavailable_error(function_name, "fd");
1215 return 1;
1216}
1217
1218static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001219follow_symlinks_specified(const char *function_name, int follow_symlinks)
1220{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001221 if (follow_symlinks)
1222 return 0;
1223
1224 argument_unavailable_error(function_name, "follow_symlinks");
1225 return 1;
1226}
1227
1228static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001229path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
1230{
Steve Dowercc16be82016-09-08 10:35:16 -07001231 if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
1232#ifndef MS_WINDOWS
1233 && !path->narrow
1234#endif
1235 ) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001236 PyErr_Format(PyExc_ValueError,
1237 "%s: can't specify dir_fd without matching path",
1238 function_name);
1239 return 1;
1240 }
1241 return 0;
1242}
1243
1244static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001245dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
1246{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001247 if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
1248 PyErr_Format(PyExc_ValueError,
1249 "%s: can't specify both dir_fd and fd",
1250 function_name);
1251 return 1;
1252 }
1253 return 0;
1254}
1255
1256static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001257fd_and_follow_symlinks_invalid(const char *function_name, int fd,
1258 int follow_symlinks)
1259{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001260 if ((fd > 0) && (!follow_symlinks)) {
1261 PyErr_Format(PyExc_ValueError,
1262 "%s: cannot use fd and follow_symlinks together",
1263 function_name);
1264 return 1;
1265 }
1266 return 0;
1267}
1268
1269static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001270dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
1271 int follow_symlinks)
1272{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001273 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
1274 PyErr_Format(PyExc_ValueError,
1275 "%s: cannot use dir_fd and follow_symlinks together",
1276 function_name);
1277 return 1;
1278 }
1279 return 0;
1280}
1281
Larry Hastings2f936352014-08-05 14:04:04 +10001282#ifdef MS_WINDOWS
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001283 typedef long long Py_off_t;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001284#else
Larry Hastings2f936352014-08-05 14:04:04 +10001285 typedef off_t Py_off_t;
1286#endif
1287
1288static int
1289Py_off_t_converter(PyObject *arg, void *addr)
1290{
1291#ifdef HAVE_LARGEFILE_SUPPORT
1292 *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
1293#else
1294 *((Py_off_t *)addr) = PyLong_AsLong(arg);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001295#endif
1296 if (PyErr_Occurred())
1297 return 0;
1298 return 1;
1299}
Larry Hastings2f936352014-08-05 14:04:04 +10001300
1301static PyObject *
1302PyLong_FromPy_off_t(Py_off_t offset)
1303{
1304#ifdef HAVE_LARGEFILE_SUPPORT
1305 return PyLong_FromLongLong(offset);
1306#else
1307 return PyLong_FromLong(offset);
Ross Lagerwallb1e5d592011-09-19 08:30:43 +02001308#endif
Larry Hastings2f936352014-08-05 14:04:04 +10001309}
1310
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001311#ifdef HAVE_SIGSET_T
1312/* Convert an iterable of integers to a sigset.
1313 Return 1 on success, return 0 and raise an exception on error. */
1314int
1315_Py_Sigset_Converter(PyObject *obj, void *addr)
1316{
1317 sigset_t *mask = (sigset_t *)addr;
1318 PyObject *iterator, *item;
1319 long signum;
1320 int overflow;
1321
Rémi Lapeyref0900192019-05-04 01:30:53 +02001322 // The extra parens suppress the unreachable-code warning with clang on MacOS
1323 if (sigemptyset(mask) < (0)) {
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001324 /* Probably only if mask == NULL. */
1325 PyErr_SetFromErrno(PyExc_OSError);
1326 return 0;
1327 }
1328
1329 iterator = PyObject_GetIter(obj);
1330 if (iterator == NULL) {
1331 return 0;
1332 }
1333
1334 while ((item = PyIter_Next(iterator)) != NULL) {
1335 signum = PyLong_AsLongAndOverflow(item, &overflow);
1336 Py_DECREF(item);
1337 if (signum <= 0 || signum >= NSIG) {
1338 if (overflow || signum != -1 || !PyErr_Occurred()) {
1339 PyErr_Format(PyExc_ValueError,
1340 "signal number %ld out of range", signum);
1341 }
1342 goto error;
1343 }
1344 if (sigaddset(mask, (int)signum)) {
1345 if (errno != EINVAL) {
1346 /* Probably impossible */
1347 PyErr_SetFromErrno(PyExc_OSError);
1348 goto error;
1349 }
1350 /* For backwards compatibility, allow idioms such as
1351 * `range(1, NSIG)` but warn about invalid signal numbers
1352 */
1353 const char msg[] =
1354 "invalid signal number %ld, please use valid_signals()";
1355 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
1356 goto error;
1357 }
1358 }
1359 }
1360 if (!PyErr_Occurred()) {
1361 Py_DECREF(iterator);
1362 return 1;
1363 }
1364
1365error:
1366 Py_DECREF(iterator);
1367 return 0;
1368}
1369#endif /* HAVE_SIGSET_T */
1370
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001371#ifdef MS_WINDOWS
Brian Curtinf5e76d02010-11-24 13:14:05 +00001372
1373static int
Brian Curtind25aef52011-06-13 15:16:04 -05001374win32_get_reparse_tag(HANDLE reparse_point_handle, ULONG *reparse_tag)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001375{
Martin Panter70214ad2016-08-04 02:38:59 +00001376 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1377 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001378 DWORD n_bytes_returned;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001379
1380 if (0 == DeviceIoControl(
1381 reparse_point_handle,
1382 FSCTL_GET_REPARSE_POINT,
1383 NULL, 0, /* in buffer */
1384 target_buffer, sizeof(target_buffer),
1385 &n_bytes_returned,
1386 NULL)) /* we're not using OVERLAPPED_IO */
Brian Curtind25aef52011-06-13 15:16:04 -05001387 return FALSE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001388
1389 if (reparse_tag)
1390 *reparse_tag = rdb->ReparseTag;
1391
Brian Curtind25aef52011-06-13 15:16:04 -05001392 return TRUE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001393}
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001394
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001395#endif /* MS_WINDOWS */
Brian Curtinf5e76d02010-11-24 13:14:05 +00001396
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001397/* Return a dictionary corresponding to the POSIX environment table */
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001398#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Jack Jansenea0c3822002-08-01 21:57:49 +00001399/* On Darwin/MacOSX a shared library or framework has no access to
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001400** environ directly, we must obtain it with _NSGetEnviron(). See also
1401** man environ(7).
Jack Jansenea0c3822002-08-01 21:57:49 +00001402*/
1403#include <crt_externs.h>
pxinwrf2d7ac72019-05-21 18:46:37 +08001404#elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001405extern char **environ;
Guido van Rossuma4916fa1996-05-23 22:58:55 +00001406#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001407
Barry Warsaw53699e91996-12-10 23:23:01 +00001408static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001409convertenviron(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001410{
Victor Stinner8c62be82010-05-06 00:08:46 +00001411 PyObject *d;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001412#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00001413 wchar_t **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001414#else
Victor Stinner8c62be82010-05-06 00:08:46 +00001415 char **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001416#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +00001417
Victor Stinner8c62be82010-05-06 00:08:46 +00001418 d = PyDict_New();
1419 if (d == NULL)
1420 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001421#ifdef MS_WINDOWS
1422 /* _wenviron must be initialized in this way if the program is started
1423 through main() instead of wmain(). */
1424 _wgetenv(L"");
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001425 e = _wenviron;
Benoit Hudson723f71a2019-12-06 14:15:03 -05001426#elif defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
1427 /* environ is not accessible as an extern in a shared object on OSX; use
1428 _NSGetEnviron to resolve it. The value changes if you add environment
1429 variables between calls to Py_Initialize, so don't cache the value. */
1430 e = *_NSGetEnviron();
Victor Stinner8c62be82010-05-06 00:08:46 +00001431#else
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001432 e = environ;
1433#endif
1434 if (e == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +00001435 return d;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001436 for (; *e != NULL; e++) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001437 PyObject *k;
1438 PyObject *v;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001439#ifdef MS_WINDOWS
1440 const wchar_t *p = wcschr(*e, L'=');
1441#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03001442 const char *p = strchr(*e, '=');
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001443#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001444 if (p == NULL)
1445 continue;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001446#ifdef MS_WINDOWS
1447 k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
1448#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001449 k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001450#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001451 if (k == NULL) {
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001452 Py_DECREF(d);
1453 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001454 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001455#ifdef MS_WINDOWS
1456 v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
1457#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001458 v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001459#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001460 if (v == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001461 Py_DECREF(k);
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001462 Py_DECREF(d);
1463 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001464 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001465 if (PyDict_GetItemWithError(d, k) == NULL) {
1466 if (PyErr_Occurred() || PyDict_SetItem(d, k, v) != 0) {
1467 Py_DECREF(v);
1468 Py_DECREF(k);
1469 Py_DECREF(d);
1470 return NULL;
1471 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001472 }
1473 Py_DECREF(k);
1474 Py_DECREF(v);
Guido van Rossumd48f2521997-12-05 22:19:34 +00001475 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001476 return d;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001477}
1478
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001479/* Set a POSIX-specific error from errno, and return NULL */
1480
Barry Warsawd58d7641998-07-23 16:14:40 +00001481static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001482posix_error(void)
Guido van Rossumad0ee831995-03-01 10:34:45 +00001483{
Victor Stinner8c62be82010-05-06 00:08:46 +00001484 return PyErr_SetFromErrno(PyExc_OSError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001485}
Mark Hammondef8b6542001-05-13 08:04:26 +00001486
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001487#ifdef MS_WINDOWS
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001488static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001489win32_error(const char* function, const char* filename)
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001490{
Victor Stinner8c62be82010-05-06 00:08:46 +00001491 /* XXX We should pass the function name along in the future.
1492 (winreg.c also wants to pass the function name.)
1493 This would however require an additional param to the
1494 Windows error object, which is non-trivial.
1495 */
1496 errno = GetLastError();
1497 if (filename)
1498 return PyErr_SetFromWindowsErrWithFilename(errno, filename);
1499 else
1500 return PyErr_SetFromWindowsErr(errno);
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001501}
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001502
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001503static PyObject *
Steve Dower2438cdf2019-03-29 16:37:16 -07001504win32_error_object_err(const char* function, PyObject* filename, DWORD err)
Victor Stinnereb5657a2011-09-30 01:44:27 +02001505{
1506 /* XXX - see win32_error for comments on 'function' */
Victor Stinnereb5657a2011-09-30 01:44:27 +02001507 if (filename)
1508 return PyErr_SetExcFromWindowsErrWithFilenameObject(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001509 PyExc_OSError,
Steve Dower2438cdf2019-03-29 16:37:16 -07001510 err,
Victor Stinnereb5657a2011-09-30 01:44:27 +02001511 filename);
1512 else
Steve Dower2438cdf2019-03-29 16:37:16 -07001513 return PyErr_SetFromWindowsErr(err);
1514}
1515
1516static PyObject *
1517win32_error_object(const char* function, PyObject* filename)
1518{
1519 errno = GetLastError();
1520 return win32_error_object_err(function, filename, errno);
Victor Stinnereb5657a2011-09-30 01:44:27 +02001521}
1522
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001523#endif /* MS_WINDOWS */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001524
Larry Hastings9cf065c2012-06-22 16:30:09 -07001525static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001526posix_path_object_error(PyObject *path)
1527{
1528 return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
1529}
1530
1531static PyObject *
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001532path_object_error(PyObject *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001533{
1534#ifdef MS_WINDOWS
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001535 return PyErr_SetExcFromWindowsErrWithFilenameObject(
1536 PyExc_OSError, 0, path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001537#else
Alexey Izbyshev83460312018-10-20 03:28:22 +03001538 return posix_path_object_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001539#endif
1540}
1541
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001542static PyObject *
1543path_object_error2(PyObject *path, PyObject *path2)
1544{
1545#ifdef MS_WINDOWS
1546 return PyErr_SetExcFromWindowsErrWithFilenameObjects(
1547 PyExc_OSError, 0, path, path2);
1548#else
1549 return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
1550#endif
1551}
1552
1553static PyObject *
1554path_error(path_t *path)
1555{
1556 return path_object_error(path->object);
1557}
Larry Hastings31826802013-10-19 00:09:25 -07001558
Larry Hastingsb0827312014-02-09 22:05:19 -08001559static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001560posix_path_error(path_t *path)
1561{
1562 return posix_path_object_error(path->object);
1563}
1564
1565static PyObject *
Larry Hastingsb0827312014-02-09 22:05:19 -08001566path_error2(path_t *path, path_t *path2)
1567{
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001568 return path_object_error2(path->object, path2->object);
Larry Hastingsb0827312014-02-09 22:05:19 -08001569}
1570
1571
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001572/* POSIX generic methods */
1573
Larry Hastings2f936352014-08-05 14:04:04 +10001574static int
1575fildes_converter(PyObject *o, void *p)
Fred Drake4d1e64b2002-04-15 19:40:07 +00001576{
Victor Stinner8c62be82010-05-06 00:08:46 +00001577 int fd;
Larry Hastings2f936352014-08-05 14:04:04 +10001578 int *pointer = (int *)p;
1579 fd = PyObject_AsFileDescriptor(o);
Victor Stinner8c62be82010-05-06 00:08:46 +00001580 if (fd < 0)
Larry Hastings2f936352014-08-05 14:04:04 +10001581 return 0;
Larry Hastings2f936352014-08-05 14:04:04 +10001582 *pointer = fd;
1583 return 1;
1584}
1585
1586static PyObject *
1587posix_fildes_fd(int fd, int (*func)(int))
1588{
1589 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001590 int async_err = 0;
1591
1592 do {
1593 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001594 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001595 res = (*func)(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001596 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001597 Py_END_ALLOW_THREADS
1598 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1599 if (res != 0)
1600 return (!async_err) ? posix_error() : NULL;
1601 Py_RETURN_NONE;
Fred Drake4d1e64b2002-04-15 19:40:07 +00001602}
Guido van Rossum21142a01999-01-08 21:05:37 +00001603
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001604
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001605#ifdef MS_WINDOWS
Thomas Wouters477c8d52006-05-27 19:21:47 +00001606/* This is a reimplementation of the C library's chdir function,
1607 but one that produces Win32 errors instead of DOS error codes.
1608 chdir is essentially a wrapper around SetCurrentDirectory; however,
1609 it also needs to set "magic" environment variables indicating
1610 the per-drive current directory, which are of the form =<drive>: */
Benjamin Peterson206e3072008-10-19 14:07:49 +00001611static BOOL __stdcall
Thomas Wouters477c8d52006-05-27 19:21:47 +00001612win32_wchdir(LPCWSTR path)
1613{
Victor Stinnered537822015-12-13 21:40:26 +01001614 wchar_t path_buf[MAX_PATH], *new_path = path_buf;
Victor Stinner8c62be82010-05-06 00:08:46 +00001615 int result;
1616 wchar_t env[4] = L"=x:";
Thomas Wouters477c8d52006-05-27 19:21:47 +00001617
Victor Stinner8c62be82010-05-06 00:08:46 +00001618 if(!SetCurrentDirectoryW(path))
1619 return FALSE;
Victor Stinnered537822015-12-13 21:40:26 +01001620 result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001621 if (!result)
1622 return FALSE;
Victor Stinnere847d712015-12-14 00:21:50 +01001623 if (result > Py_ARRAY_LENGTH(path_buf)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001624 new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00001625 if (!new_path) {
1626 SetLastError(ERROR_OUTOFMEMORY);
1627 return FALSE;
1628 }
1629 result = GetCurrentDirectoryW(result, new_path);
1630 if (!result) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001631 PyMem_RawFree(new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001632 return FALSE;
1633 }
1634 }
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001635 int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
1636 wcsncmp(new_path, L"//", 2) == 0);
1637 if (!is_unc_like_path) {
1638 env[1] = new_path[0];
1639 result = SetEnvironmentVariableW(env, new_path);
1640 }
Victor Stinnered537822015-12-13 21:40:26 +01001641 if (new_path != path_buf)
Victor Stinnerb6404912013-07-07 16:21:41 +02001642 PyMem_RawFree(new_path);
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001643 return result ? TRUE : FALSE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001644}
1645#endif
1646
Martin v. Löwis14694662006-02-03 12:54:16 +00001647#ifdef MS_WINDOWS
1648/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
1649 - time stamps are restricted to second resolution
1650 - file modification times suffer from forth-and-back conversions between
1651 UTC and local time
1652 Therefore, we implement our own stat, based on the Win32 API directly.
1653*/
Victor Stinner8c62be82010-05-06 00:08:46 +00001654#define HAVE_STAT_NSEC 1
Zachary Ware63f277b2014-06-19 09:46:37 -05001655#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001656#define HAVE_STRUCT_STAT_ST_REPARSE_TAG 1
Martin v. Löwis14694662006-02-03 12:54:16 +00001657
Victor Stinner6036e442015-03-08 01:58:04 +01001658static void
Steve Dowercc16be82016-09-08 10:35:16 -07001659find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
1660 BY_HANDLE_FILE_INFORMATION *info,
1661 ULONG *reparse_tag)
Victor Stinner6036e442015-03-08 01:58:04 +01001662{
1663 memset(info, 0, sizeof(*info));
1664 info->dwFileAttributes = pFileData->dwFileAttributes;
1665 info->ftCreationTime = pFileData->ftCreationTime;
1666 info->ftLastAccessTime = pFileData->ftLastAccessTime;
1667 info->ftLastWriteTime = pFileData->ftLastWriteTime;
1668 info->nFileSizeHigh = pFileData->nFileSizeHigh;
1669 info->nFileSizeLow = pFileData->nFileSizeLow;
1670/* info->nNumberOfLinks = 1; */
1671 if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
1672 *reparse_tag = pFileData->dwReserved0;
1673 else
1674 *reparse_tag = 0;
1675}
1676
Guido van Rossumd8faa362007-04-27 19:54:29 +00001677static BOOL
Steve Dowercc16be82016-09-08 10:35:16 -07001678attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001679{
Victor Stinner8c62be82010-05-06 00:08:46 +00001680 HANDLE hFindFile;
1681 WIN32_FIND_DATAW FileData;
1682 hFindFile = FindFirstFileW(pszFile, &FileData);
1683 if (hFindFile == INVALID_HANDLE_VALUE)
1684 return FALSE;
1685 FindClose(hFindFile);
Steve Dowercc16be82016-09-08 10:35:16 -07001686 find_data_to_file_info(&FileData, info, reparse_tag);
Victor Stinner8c62be82010-05-06 00:08:46 +00001687 return TRUE;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001688}
1689
Brian Curtind25aef52011-06-13 15:16:04 -05001690static int
Steve Dowercc16be82016-09-08 10:35:16 -07001691win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
Brian Curtind25aef52011-06-13 15:16:04 -05001692 BOOL traverse)
1693{
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001694 HANDLE hFile;
1695 BY_HANDLE_FILE_INFORMATION fileInfo;
1696 FILE_ATTRIBUTE_TAG_INFO tagInfo = { 0 };
1697 DWORD fileType, error;
1698 BOOL isUnhandledTag = FALSE;
1699 int retval = 0;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001700
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001701 DWORD access = FILE_READ_ATTRIBUTES;
1702 DWORD flags = FILE_FLAG_BACKUP_SEMANTICS; /* Allow opening directories. */
1703 if (!traverse) {
1704 flags |= FILE_FLAG_OPEN_REPARSE_POINT;
1705 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001706
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001707 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING, flags, NULL);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001708 if (hFile == INVALID_HANDLE_VALUE) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001709 /* Either the path doesn't exist, or the caller lacks access. */
1710 error = GetLastError();
1711 switch (error) {
1712 case ERROR_ACCESS_DENIED: /* Cannot sync or read attributes. */
1713 case ERROR_SHARING_VIOLATION: /* It's a paging file. */
1714 /* Try reading the parent directory. */
1715 if (!attributes_from_dir(path, &fileInfo, &tagInfo.ReparseTag)) {
1716 /* Cannot read the parent directory. */
1717 SetLastError(error);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001718 return -1;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001719 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001720 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1721 if (traverse ||
1722 !IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1723 /* The stat call has to traverse but cannot, so fail. */
1724 SetLastError(error);
Brian Curtind25aef52011-06-13 15:16:04 -05001725 return -1;
Mark Becwarb82bfac2019-02-02 16:08:23 -05001726 }
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001727 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001728 break;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001729
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001730 case ERROR_INVALID_PARAMETER:
1731 /* \\.\con requires read or write access. */
1732 hFile = CreateFileW(path, access | GENERIC_READ,
1733 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1734 OPEN_EXISTING, flags, NULL);
1735 if (hFile == INVALID_HANDLE_VALUE) {
1736 SetLastError(error);
1737 return -1;
1738 }
1739 break;
1740
1741 case ERROR_CANT_ACCESS_FILE:
1742 /* bpo37834: open unhandled reparse points if traverse fails. */
1743 if (traverse) {
1744 traverse = FALSE;
1745 isUnhandledTag = TRUE;
1746 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING,
1747 flags | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
1748 }
1749 if (hFile == INVALID_HANDLE_VALUE) {
1750 SetLastError(error);
1751 return -1;
1752 }
1753 break;
1754
1755 default:
1756 return -1;
1757 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001758 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001759
1760 if (hFile != INVALID_HANDLE_VALUE) {
1761 /* Handle types other than files on disk. */
1762 fileType = GetFileType(hFile);
1763 if (fileType != FILE_TYPE_DISK) {
1764 if (fileType == FILE_TYPE_UNKNOWN && GetLastError() != 0) {
1765 retval = -1;
1766 goto cleanup;
1767 }
1768 DWORD fileAttributes = GetFileAttributesW(path);
1769 memset(result, 0, sizeof(*result));
1770 if (fileAttributes != INVALID_FILE_ATTRIBUTES &&
1771 fileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1772 /* \\.\pipe\ or \\.\mailslot\ */
1773 result->st_mode = _S_IFDIR;
1774 } else if (fileType == FILE_TYPE_CHAR) {
1775 /* \\.\nul */
1776 result->st_mode = _S_IFCHR;
1777 } else if (fileType == FILE_TYPE_PIPE) {
1778 /* \\.\pipe\spam */
1779 result->st_mode = _S_IFIFO;
1780 }
1781 /* FILE_TYPE_UNKNOWN, e.g. \\.\mailslot\waitfor.exe\spam */
1782 goto cleanup;
1783 }
1784
1785 /* Query the reparse tag, and traverse a non-link. */
1786 if (!traverse) {
1787 if (!GetFileInformationByHandleEx(hFile, FileAttributeTagInfo,
1788 &tagInfo, sizeof(tagInfo))) {
1789 /* Allow devices that do not support FileAttributeTagInfo. */
1790 switch (GetLastError()) {
1791 case ERROR_INVALID_PARAMETER:
1792 case ERROR_INVALID_FUNCTION:
1793 case ERROR_NOT_SUPPORTED:
1794 tagInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1795 tagInfo.ReparseTag = 0;
1796 break;
1797 default:
1798 retval = -1;
1799 goto cleanup;
1800 }
1801 } else if (tagInfo.FileAttributes &
1802 FILE_ATTRIBUTE_REPARSE_POINT) {
1803 if (IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1804 if (isUnhandledTag) {
1805 /* Traversing previously failed for either this link
1806 or its target. */
1807 SetLastError(ERROR_CANT_ACCESS_FILE);
1808 retval = -1;
1809 goto cleanup;
1810 }
1811 /* Traverse a non-link, but not if traversing already failed
1812 for an unhandled tag. */
1813 } else if (!isUnhandledTag) {
1814 CloseHandle(hFile);
1815 return win32_xstat_impl(path, result, TRUE);
1816 }
1817 }
1818 }
1819
1820 if (!GetFileInformationByHandle(hFile, &fileInfo)) {
1821 switch (GetLastError()) {
1822 case ERROR_INVALID_PARAMETER:
1823 case ERROR_INVALID_FUNCTION:
1824 case ERROR_NOT_SUPPORTED:
Steve Dower772ec0f2019-09-04 14:42:54 -07001825 /* Volumes and physical disks are block devices, e.g.
1826 \\.\C: and \\.\PhysicalDrive0. */
1827 memset(result, 0, sizeof(*result));
1828 result->st_mode = 0x6000; /* S_IFBLK */
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001829 goto cleanup;
1830 }
Steve Dower772ec0f2019-09-04 14:42:54 -07001831 retval = -1;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001832 goto cleanup;
1833 }
1834 }
1835
1836 _Py_attribute_data_to_stat(&fileInfo, tagInfo.ReparseTag, result);
1837
1838 if (!(fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
1839 /* Fix the file execute permissions. This hack sets S_IEXEC if
1840 the filename has an extension that is commonly used by files
1841 that CreateProcessW can execute. A real implementation calls
1842 GetSecurityInfo, OpenThreadToken/OpenProcessToken, and
1843 AccessCheck to check for generic read, write, and execute
1844 access. */
1845 const wchar_t *fileExtension = wcsrchr(path, '.');
1846 if (fileExtension) {
1847 if (_wcsicmp(fileExtension, L".exe") == 0 ||
1848 _wcsicmp(fileExtension, L".bat") == 0 ||
1849 _wcsicmp(fileExtension, L".cmd") == 0 ||
1850 _wcsicmp(fileExtension, L".com") == 0) {
1851 result->st_mode |= 0111;
1852 }
1853 }
1854 }
1855
1856cleanup:
1857 if (hFile != INVALID_HANDLE_VALUE) {
Steve Dower772ec0f2019-09-04 14:42:54 -07001858 /* Preserve last error if we are failing */
1859 error = retval ? GetLastError() : 0;
1860 if (!CloseHandle(hFile)) {
1861 retval = -1;
1862 } else if (retval) {
1863 /* Restore last error */
1864 SetLastError(error);
1865 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001866 }
1867
1868 return retval;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001869}
1870
1871static int
Steve Dowercc16be82016-09-08 10:35:16 -07001872win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001873{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001874 /* Protocol violation: we explicitly clear errno, instead of
1875 setting it to a POSIX error. Callers should use GetLastError. */
Brian Curtind25aef52011-06-13 15:16:04 -05001876 int code = win32_xstat_impl(path, result, traverse);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001877 errno = 0;
1878 return code;
1879}
Brian Curtind25aef52011-06-13 15:16:04 -05001880/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
Brian Curtind40e6f72010-07-08 21:39:08 +00001881
1882 In Posix, stat automatically traverses symlinks and returns the stat
1883 structure for the target. In Windows, the equivalent GetFileAttributes by
1884 default does not traverse symlinks and instead returns attributes for
1885 the symlink.
1886
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001887 Instead, we will open the file (which *does* traverse symlinks by default)
1888 and GetFileInformationByHandle(). */
Brian Curtind40e6f72010-07-08 21:39:08 +00001889
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001890static int
Steve Dowercc16be82016-09-08 10:35:16 -07001891win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
Martin v. Löwis14694662006-02-03 12:54:16 +00001892{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001893 return win32_xstat(path, result, FALSE);
Martin v. Löwis14694662006-02-03 12:54:16 +00001894}
1895
Victor Stinner8c62be82010-05-06 00:08:46 +00001896static int
Steve Dowercc16be82016-09-08 10:35:16 -07001897win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
Brian Curtind40e6f72010-07-08 21:39:08 +00001898{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001899 return win32_xstat(path, result, TRUE);
Brian Curtind40e6f72010-07-08 21:39:08 +00001900}
1901
Martin v. Löwis14694662006-02-03 12:54:16 +00001902#endif /* MS_WINDOWS */
1903
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001904PyDoc_STRVAR(stat_result__doc__,
Larry Hastings9cf065c2012-06-22 16:30:09 -07001905"stat_result: Result from stat, fstat, or lstat.\n\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001906This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001907 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001908or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1909\n\
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001910Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1911or st_flags, they are available as attributes only.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001912\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001913See os.stat for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001914
1915static PyStructSequence_Field stat_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001916 {"st_mode", "protection bits"},
1917 {"st_ino", "inode"},
1918 {"st_dev", "device"},
1919 {"st_nlink", "number of hard links"},
1920 {"st_uid", "user ID of owner"},
1921 {"st_gid", "group ID of owner"},
1922 {"st_size", "total size, in bytes"},
1923 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1924 {NULL, "integer time of last access"},
1925 {NULL, "integer time of last modification"},
1926 {NULL, "integer time of last change"},
1927 {"st_atime", "time of last access"},
1928 {"st_mtime", "time of last modification"},
1929 {"st_ctime", "time of last change"},
Larry Hastings6fe20b32012-04-19 15:07:49 -07001930 {"st_atime_ns", "time of last access in nanoseconds"},
1931 {"st_mtime_ns", "time of last modification in nanoseconds"},
1932 {"st_ctime_ns", "time of last change in nanoseconds"},
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001933#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00001934 {"st_blksize", "blocksize for filesystem I/O"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001935#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001936#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00001937 {"st_blocks", "number of blocks allocated"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001938#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001939#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00001940 {"st_rdev", "device type (if inode device)"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001941#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001942#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00001943 {"st_flags", "user defined flags for file"},
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001944#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001945#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00001946 {"st_gen", "generation number"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001947#endif
1948#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00001949 {"st_birthtime", "time of creation"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001950#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05001951#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1952 {"st_file_attributes", "Windows file attribute bits"},
1953#endif
jcea6c51d512018-01-28 14:00:08 +01001954#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1955 {"st_fstype", "Type of filesystem"},
1956#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001957#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
1958 {"st_reparse_tag", "Windows reparse tag"},
1959#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001960 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001961};
1962
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001963#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Larry Hastings6fe20b32012-04-19 15:07:49 -07001964#define ST_BLKSIZE_IDX 16
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001965#else
Larry Hastings6fe20b32012-04-19 15:07:49 -07001966#define ST_BLKSIZE_IDX 15
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001967#endif
1968
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001969#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001970#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
1971#else
1972#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
1973#endif
1974
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001975#ifdef HAVE_STRUCT_STAT_ST_RDEV
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001976#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
1977#else
1978#define ST_RDEV_IDX ST_BLOCKS_IDX
1979#endif
1980
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001981#ifdef HAVE_STRUCT_STAT_ST_FLAGS
1982#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
1983#else
1984#define ST_FLAGS_IDX ST_RDEV_IDX
1985#endif
1986
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001987#ifdef HAVE_STRUCT_STAT_ST_GEN
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001988#define ST_GEN_IDX (ST_FLAGS_IDX+1)
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001989#else
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001990#define ST_GEN_IDX ST_FLAGS_IDX
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001991#endif
1992
1993#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1994#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
1995#else
1996#define ST_BIRTHTIME_IDX ST_GEN_IDX
1997#endif
1998
Zachary Ware63f277b2014-06-19 09:46:37 -05001999#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2000#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_IDX+1)
2001#else
2002#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_IDX
2003#endif
2004
jcea6c51d512018-01-28 14:00:08 +01002005#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2006#define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
2007#else
2008#define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
2009#endif
2010
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002011#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2012#define ST_REPARSE_TAG_IDX (ST_FSTYPE_IDX+1)
2013#else
2014#define ST_REPARSE_TAG_IDX ST_FSTYPE_IDX
2015#endif
2016
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002017static PyStructSequence_Desc stat_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002018 "stat_result", /* name */
2019 stat_result__doc__, /* doc */
2020 stat_result_fields,
2021 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002022};
2023
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002024PyDoc_STRVAR(statvfs_result__doc__,
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002025"statvfs_result: Result from statvfs or fstatvfs.\n\n\
2026This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00002027 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
Guido van Rossuma4dc73e2001-10-18 20:53:15 +00002028or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002029\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002030See os.statvfs for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002031
2032static PyStructSequence_Field statvfs_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002033 {"f_bsize", },
2034 {"f_frsize", },
2035 {"f_blocks", },
2036 {"f_bfree", },
2037 {"f_bavail", },
2038 {"f_files", },
2039 {"f_ffree", },
2040 {"f_favail", },
2041 {"f_flag", },
2042 {"f_namemax",},
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +01002043 {"f_fsid", },
Victor Stinner8c62be82010-05-06 00:08:46 +00002044 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002045};
2046
2047static PyStructSequence_Desc statvfs_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002048 "statvfs_result", /* name */
2049 statvfs_result__doc__, /* doc */
2050 statvfs_result_fields,
2051 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002052};
2053
Ross Lagerwall7807c352011-03-17 20:20:30 +02002054#if defined(HAVE_WAITID) && !defined(__APPLE__)
2055PyDoc_STRVAR(waitid_result__doc__,
2056"waitid_result: Result from waitid.\n\n\
2057This object may be accessed either as a tuple of\n\
2058 (si_pid, si_uid, si_signo, si_status, si_code),\n\
2059or via the attributes si_pid, si_uid, and so on.\n\
2060\n\
2061See os.waitid for more information.");
2062
2063static PyStructSequence_Field waitid_result_fields[] = {
2064 {"si_pid", },
2065 {"si_uid", },
2066 {"si_signo", },
2067 {"si_status", },
2068 {"si_code", },
2069 {0}
2070};
2071
2072static PyStructSequence_Desc waitid_result_desc = {
2073 "waitid_result", /* name */
2074 waitid_result__doc__, /* doc */
2075 waitid_result_fields,
2076 5
2077};
Benjamin Petersonbad9c2f2011-08-02 18:42:14 -05002078#endif
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002079static newfunc structseq_new;
2080
2081static PyObject *
2082statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2083{
Victor Stinner8c62be82010-05-06 00:08:46 +00002084 PyStructSequence *result;
2085 int i;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002086
Victor Stinner8c62be82010-05-06 00:08:46 +00002087 result = (PyStructSequence*)structseq_new(type, args, kwds);
2088 if (!result)
2089 return NULL;
2090 /* If we have been initialized from a tuple,
2091 st_?time might be set to None. Initialize it
2092 from the int slots. */
2093 for (i = 7; i <= 9; i++) {
2094 if (result->ob_item[i+3] == Py_None) {
2095 Py_DECREF(Py_None);
2096 Py_INCREF(result->ob_item[i]);
2097 result->ob_item[i+3] = result->ob_item[i];
2098 }
2099 }
2100 return (PyObject*)result;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002101}
2102
Eddie Elizondob3966632019-11-05 07:16:14 -08002103static int
2104_posix_clear(PyObject *module)
2105{
2106 Py_CLEAR(_posixstate(module)->billion);
Eddie Elizondob3966632019-11-05 07:16:14 -08002107 Py_CLEAR(_posixstate(module)->DirEntryType);
2108 Py_CLEAR(_posixstate(module)->ScandirIteratorType);
2109#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
2110 Py_CLEAR(_posixstate(module)->SchedParamType);
2111#endif
2112 Py_CLEAR(_posixstate(module)->StatResultType);
2113 Py_CLEAR(_posixstate(module)->StatVFSResultType);
2114 Py_CLEAR(_posixstate(module)->TerminalSizeType);
2115 Py_CLEAR(_posixstate(module)->TimesResultType);
2116 Py_CLEAR(_posixstate(module)->UnameResultType);
2117#if defined(HAVE_WAITID) && !defined(__APPLE__)
2118 Py_CLEAR(_posixstate(module)->WaitidResultType);
2119#endif
2120#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
2121 Py_CLEAR(_posixstate(module)->struct_rusage);
2122#endif
2123 Py_CLEAR(_posixstate(module)->st_mode);
2124 return 0;
2125}
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002126
Eddie Elizondob3966632019-11-05 07:16:14 -08002127static int
2128_posix_traverse(PyObject *module, visitproc visit, void *arg)
2129{
2130 Py_VISIT(_posixstate(module)->billion);
Eddie Elizondob3966632019-11-05 07:16:14 -08002131 Py_VISIT(_posixstate(module)->DirEntryType);
2132 Py_VISIT(_posixstate(module)->ScandirIteratorType);
2133#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
2134 Py_VISIT(_posixstate(module)->SchedParamType);
2135#endif
2136 Py_VISIT(_posixstate(module)->StatResultType);
2137 Py_VISIT(_posixstate(module)->StatVFSResultType);
2138 Py_VISIT(_posixstate(module)->TerminalSizeType);
2139 Py_VISIT(_posixstate(module)->TimesResultType);
2140 Py_VISIT(_posixstate(module)->UnameResultType);
2141#if defined(HAVE_WAITID) && !defined(__APPLE__)
2142 Py_VISIT(_posixstate(module)->WaitidResultType);
2143#endif
2144#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
2145 Py_VISIT(_posixstate(module)->struct_rusage);
2146#endif
2147 Py_VISIT(_posixstate(module)->st_mode);
2148 return 0;
2149}
2150
2151static void
2152_posix_free(void *module)
2153{
2154 _posix_clear((PyObject *)module);
2155}
Larry Hastings6fe20b32012-04-19 15:07:49 -07002156
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002157static void
Victor Stinner4195b5c2012-02-08 23:03:19 +01002158fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002159{
Larry Hastings6fe20b32012-04-19 15:07:49 -07002160 PyObject *s = _PyLong_FromTime_t(sec);
2161 PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
2162 PyObject *s_in_ns = NULL;
2163 PyObject *ns_total = NULL;
2164 PyObject *float_s = NULL;
2165
2166 if (!(s && ns_fractional))
2167 goto exit;
2168
Eddie Elizondob3966632019-11-05 07:16:14 -08002169 s_in_ns = PyNumber_Multiply(s, _posixstate_global->billion);
Larry Hastings6fe20b32012-04-19 15:07:49 -07002170 if (!s_in_ns)
2171 goto exit;
2172
2173 ns_total = PyNumber_Add(s_in_ns, ns_fractional);
2174 if (!ns_total)
2175 goto exit;
2176
Victor Stinner01b5aab2017-10-24 02:02:00 -07002177 float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
2178 if (!float_s) {
2179 goto exit;
Larry Hastings6fe20b32012-04-19 15:07:49 -07002180 }
2181
2182 PyStructSequence_SET_ITEM(v, index, s);
2183 PyStructSequence_SET_ITEM(v, index+3, float_s);
2184 PyStructSequence_SET_ITEM(v, index+6, ns_total);
2185 s = NULL;
2186 float_s = NULL;
2187 ns_total = NULL;
2188exit:
2189 Py_XDECREF(s);
2190 Py_XDECREF(ns_fractional);
2191 Py_XDECREF(s_in_ns);
2192 Py_XDECREF(ns_total);
2193 Py_XDECREF(float_s);
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002194}
2195
Tim Peters5aa91602002-01-30 05:46:57 +00002196/* pack a system stat C structure into the Python stat tuple
Fred Drake699f3522000-06-29 21:12:41 +00002197 (used by posix_stat() and posix_fstat()) */
2198static PyObject*
Victor Stinner4195b5c2012-02-08 23:03:19 +01002199_pystat_fromstructstat(STRUCT_STAT *st)
Fred Drake699f3522000-06-29 21:12:41 +00002200{
Victor Stinner8c62be82010-05-06 00:08:46 +00002201 unsigned long ansec, mnsec, cnsec;
Eddie Elizondob3966632019-11-05 07:16:14 -08002202 PyObject *StatResultType = _posixstate_global->StatResultType;
2203 PyObject *v = PyStructSequence_New((PyTypeObject *)StatResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +00002204 if (v == NULL)
2205 return NULL;
Fred Drake699f3522000-06-29 21:12:41 +00002206
Victor Stinner8c62be82010-05-06 00:08:46 +00002207 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode));
Victor Stinner0f6d7332017-03-09 17:34:28 +01002208 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(st->st_ino));
xdegaye50e86032017-05-22 11:15:08 +02002209 PyStructSequence_SET_ITEM(v, 1, PyLong_FromUnsignedLongLong(st->st_ino));
Serhiy Storchaka404fa922013-01-02 18:22:23 +02002210#ifdef MS_WINDOWS
2211 PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002212#else
Serhiy Storchakab2653b32015-01-18 11:12:11 +02002213 PyStructSequence_SET_ITEM(v, 2, _PyLong_FromDev(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002214#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002215 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02002216#if defined(MS_WINDOWS)
2217 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong(0));
2218 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong(0));
2219#else
2220 PyStructSequence_SET_ITEM(v, 4, _PyLong_FromUid(st->st_uid));
2221 PyStructSequence_SET_ITEM(v, 5, _PyLong_FromGid(st->st_gid));
2222#endif
xdegaye50e86032017-05-22 11:15:08 +02002223 Py_BUILD_ASSERT(sizeof(long long) >= sizeof(st->st_size));
2224 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLongLong(st->st_size));
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002225
Martin v. Löwis14694662006-02-03 12:54:16 +00002226#if defined(HAVE_STAT_TV_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002227 ansec = st->st_atim.tv_nsec;
2228 mnsec = st->st_mtim.tv_nsec;
2229 cnsec = st->st_ctim.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002230#elif defined(HAVE_STAT_TV_NSEC2)
Victor Stinner8c62be82010-05-06 00:08:46 +00002231 ansec = st->st_atimespec.tv_nsec;
2232 mnsec = st->st_mtimespec.tv_nsec;
2233 cnsec = st->st_ctimespec.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002234#elif defined(HAVE_STAT_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002235 ansec = st->st_atime_nsec;
2236 mnsec = st->st_mtime_nsec;
2237 cnsec = st->st_ctime_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002238#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002239 ansec = mnsec = cnsec = 0;
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002240#endif
Victor Stinner4195b5c2012-02-08 23:03:19 +01002241 fill_time(v, 7, st->st_atime, ansec);
2242 fill_time(v, 8, st->st_mtime, mnsec);
2243 fill_time(v, 9, st->st_ctime, cnsec);
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002244
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002245#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00002246 PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
2247 PyLong_FromLong((long)st->st_blksize));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002248#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002249#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00002250 PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
2251 PyLong_FromLong((long)st->st_blocks));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002252#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002253#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00002254 PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
2255 PyLong_FromLong((long)st->st_rdev));
Fred Drake699f3522000-06-29 21:12:41 +00002256#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002257#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00002258 PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
2259 PyLong_FromLong((long)st->st_gen));
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002260#endif
2261#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00002262 {
Victor Stinner4195b5c2012-02-08 23:03:19 +01002263 PyObject *val;
2264 unsigned long bsec,bnsec;
2265 bsec = (long)st->st_birthtime;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002266#ifdef HAVE_STAT_TV_NSEC2
Victor Stinner4195b5c2012-02-08 23:03:19 +01002267 bnsec = st->st_birthtimespec.tv_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002268#else
Victor Stinner4195b5c2012-02-08 23:03:19 +01002269 bnsec = 0;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002270#endif
Victor Stinner01b5aab2017-10-24 02:02:00 -07002271 val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
Victor Stinner4195b5c2012-02-08 23:03:19 +01002272 PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
2273 val);
Victor Stinner8c62be82010-05-06 00:08:46 +00002274 }
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002275#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002276#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00002277 PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
2278 PyLong_FromLong((long)st->st_flags));
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002279#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05002280#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2281 PyStructSequence_SET_ITEM(v, ST_FILE_ATTRIBUTES_IDX,
2282 PyLong_FromUnsignedLong(st->st_file_attributes));
2283#endif
jcea6c51d512018-01-28 14:00:08 +01002284#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2285 PyStructSequence_SET_ITEM(v, ST_FSTYPE_IDX,
2286 PyUnicode_FromString(st->st_fstype));
2287#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002288#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2289 PyStructSequence_SET_ITEM(v, ST_REPARSE_TAG_IDX,
2290 PyLong_FromUnsignedLong(st->st_reparse_tag));
2291#endif
Fred Drake699f3522000-06-29 21:12:41 +00002292
Victor Stinner8c62be82010-05-06 00:08:46 +00002293 if (PyErr_Occurred()) {
2294 Py_DECREF(v);
2295 return NULL;
2296 }
Fred Drake699f3522000-06-29 21:12:41 +00002297
Victor Stinner8c62be82010-05-06 00:08:46 +00002298 return v;
Fred Drake699f3522000-06-29 21:12:41 +00002299}
2300
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002301/* POSIX methods */
2302
Guido van Rossum94f6f721999-01-06 18:42:14 +00002303
2304static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002305posix_do_stat(const char *function_name, path_t *path,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002306 int dir_fd, int follow_symlinks)
Guido van Rossum94f6f721999-01-06 18:42:14 +00002307{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002308 STRUCT_STAT st;
2309 int result;
2310
2311#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
2312 if (follow_symlinks_specified(function_name, follow_symlinks))
2313 return NULL;
2314#endif
2315
2316 if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
2317 dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
2318 fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
2319 return NULL;
2320
2321 Py_BEGIN_ALLOW_THREADS
2322 if (path->fd != -1)
2323 result = FSTAT(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002324#ifdef MS_WINDOWS
Steve Dower513d7472016-09-08 10:41:50 -07002325 else if (follow_symlinks)
Steve Dowercc16be82016-09-08 10:35:16 -07002326 result = win32_stat(path->wide, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002327 else
Steve Dowercc16be82016-09-08 10:35:16 -07002328 result = win32_lstat(path->wide, &st);
2329#else
2330 else
2331#if defined(HAVE_LSTAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002332 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
2333 result = LSTAT(path->narrow, &st);
2334 else
Steve Dowercc16be82016-09-08 10:35:16 -07002335#endif /* HAVE_LSTAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002336#ifdef HAVE_FSTATAT
2337 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks)
2338 result = fstatat(dir_fd, path->narrow, &st,
2339 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2340 else
Steve Dowercc16be82016-09-08 10:35:16 -07002341#endif /* HAVE_FSTATAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002342 result = STAT(path->narrow, &st);
Steve Dowercc16be82016-09-08 10:35:16 -07002343#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002344 Py_END_ALLOW_THREADS
2345
Victor Stinner292c8352012-10-30 02:17:38 +01002346 if (result != 0) {
2347 return path_error(path);
2348 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07002349
2350 return _pystat_fromstructstat(&st);
2351}
2352
Larry Hastings2f936352014-08-05 14:04:04 +10002353/*[python input]
2354
2355for s in """
2356
2357FACCESSAT
2358FCHMODAT
2359FCHOWNAT
2360FSTATAT
2361LINKAT
2362MKDIRAT
2363MKFIFOAT
2364MKNODAT
2365OPENAT
2366READLINKAT
2367SYMLINKAT
2368UNLINKAT
2369
2370""".strip().split():
2371 s = s.strip()
2372 print("""
2373#ifdef HAVE_{s}
2374 #define {s}_DIR_FD_CONVERTER dir_fd_converter
Larry Hastings31826802013-10-19 00:09:25 -07002375#else
Larry Hastings2f936352014-08-05 14:04:04 +10002376 #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings31826802013-10-19 00:09:25 -07002377#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002378""".rstrip().format(s=s))
2379
2380for s in """
2381
2382FCHDIR
2383FCHMOD
2384FCHOWN
2385FDOPENDIR
2386FEXECVE
2387FPATHCONF
2388FSTATVFS
2389FTRUNCATE
2390
2391""".strip().split():
2392 s = s.strip()
2393 print("""
2394#ifdef HAVE_{s}
2395 #define PATH_HAVE_{s} 1
2396#else
2397 #define PATH_HAVE_{s} 0
2398#endif
2399
2400""".rstrip().format(s=s))
2401[python start generated code]*/
2402
2403#ifdef HAVE_FACCESSAT
2404 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
2405#else
2406 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
2407#endif
2408
2409#ifdef HAVE_FCHMODAT
2410 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
2411#else
2412 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
2413#endif
2414
2415#ifdef HAVE_FCHOWNAT
2416 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
2417#else
2418 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
2419#endif
2420
2421#ifdef HAVE_FSTATAT
2422 #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
2423#else
2424 #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
2425#endif
2426
2427#ifdef HAVE_LINKAT
2428 #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
2429#else
2430 #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2431#endif
2432
2433#ifdef HAVE_MKDIRAT
2434 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
2435#else
2436 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
2437#endif
2438
2439#ifdef HAVE_MKFIFOAT
2440 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
2441#else
2442 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
2443#endif
2444
2445#ifdef HAVE_MKNODAT
2446 #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
2447#else
2448 #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
2449#endif
2450
2451#ifdef HAVE_OPENAT
2452 #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
2453#else
2454 #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
2455#endif
2456
2457#ifdef HAVE_READLINKAT
2458 #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
2459#else
2460 #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2461#endif
2462
2463#ifdef HAVE_SYMLINKAT
2464 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
2465#else
2466 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2467#endif
2468
2469#ifdef HAVE_UNLINKAT
2470 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
2471#else
2472 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2473#endif
2474
2475#ifdef HAVE_FCHDIR
2476 #define PATH_HAVE_FCHDIR 1
2477#else
2478 #define PATH_HAVE_FCHDIR 0
2479#endif
2480
2481#ifdef HAVE_FCHMOD
2482 #define PATH_HAVE_FCHMOD 1
2483#else
2484 #define PATH_HAVE_FCHMOD 0
2485#endif
2486
2487#ifdef HAVE_FCHOWN
2488 #define PATH_HAVE_FCHOWN 1
2489#else
2490 #define PATH_HAVE_FCHOWN 0
2491#endif
2492
2493#ifdef HAVE_FDOPENDIR
2494 #define PATH_HAVE_FDOPENDIR 1
2495#else
2496 #define PATH_HAVE_FDOPENDIR 0
2497#endif
2498
2499#ifdef HAVE_FEXECVE
2500 #define PATH_HAVE_FEXECVE 1
2501#else
2502 #define PATH_HAVE_FEXECVE 0
2503#endif
2504
2505#ifdef HAVE_FPATHCONF
2506 #define PATH_HAVE_FPATHCONF 1
2507#else
2508 #define PATH_HAVE_FPATHCONF 0
2509#endif
2510
2511#ifdef HAVE_FSTATVFS
2512 #define PATH_HAVE_FSTATVFS 1
2513#else
2514 #define PATH_HAVE_FSTATVFS 0
2515#endif
2516
2517#ifdef HAVE_FTRUNCATE
2518 #define PATH_HAVE_FTRUNCATE 1
2519#else
2520 #define PATH_HAVE_FTRUNCATE 0
2521#endif
2522/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
Larry Hastings31826802013-10-19 00:09:25 -07002523
Steve Dowerfe0a41a2015-03-20 19:50:46 -07002524#ifdef MS_WINDOWS
2525 #undef PATH_HAVE_FTRUNCATE
2526 #define PATH_HAVE_FTRUNCATE 1
2527#endif
Larry Hastings31826802013-10-19 00:09:25 -07002528
Larry Hastings61272b72014-01-07 12:41:53 -08002529/*[python input]
Larry Hastings31826802013-10-19 00:09:25 -07002530
2531class path_t_converter(CConverter):
2532
2533 type = "path_t"
2534 impl_by_reference = True
2535 parse_by_reference = True
2536
2537 converter = 'path_converter'
2538
2539 def converter_init(self, *, allow_fd=False, nullable=False):
Larry Hastings31826802013-10-19 00:09:25 -07002540 # right now path_t doesn't support default values.
2541 # to support a default value, you'll need to override initialize().
Larry Hastings2f936352014-08-05 14:04:04 +10002542 if self.default not in (unspecified, None):
Larry Hastings7726ac92014-01-31 22:03:12 -08002543 fail("Can't specify a default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002544
Larry Hastings2f936352014-08-05 14:04:04 +10002545 if self.c_default not in (None, 'Py_None'):
2546 raise RuntimeError("Can't specify a c_default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002547
2548 self.nullable = nullable
2549 self.allow_fd = allow_fd
2550
Larry Hastings7726ac92014-01-31 22:03:12 -08002551 def pre_render(self):
2552 def strify(value):
Larry Hastings2f936352014-08-05 14:04:04 +10002553 if isinstance(value, str):
2554 return value
Larry Hastings7726ac92014-01-31 22:03:12 -08002555 return str(int(bool(value)))
2556
2557 # add self.py_name here when merging with posixmodule conversion
Larry Hastings2f936352014-08-05 14:04:04 +10002558 self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
Larry Hastings31826802013-10-19 00:09:25 -07002559 self.function.name,
Larry Hastings2f936352014-08-05 14:04:04 +10002560 self.name,
Larry Hastings7726ac92014-01-31 22:03:12 -08002561 strify(self.nullable),
2562 strify(self.allow_fd),
Larry Hastings31826802013-10-19 00:09:25 -07002563 )
2564
2565 def cleanup(self):
2566 return "path_cleanup(&" + self.name + ");\n"
2567
2568
2569class dir_fd_converter(CConverter):
2570 type = 'int'
Larry Hastings31826802013-10-19 00:09:25 -07002571
Larry Hastings2f936352014-08-05 14:04:04 +10002572 def converter_init(self, requires=None):
Larry Hastings31826802013-10-19 00:09:25 -07002573 if self.default in (unspecified, None):
2574 self.c_default = 'DEFAULT_DIR_FD'
Larry Hastings2f936352014-08-05 14:04:04 +10002575 if isinstance(requires, str):
2576 self.converter = requires.upper() + '_DIR_FD_CONVERTER'
2577 else:
2578 self.converter = 'dir_fd_converter'
Larry Hastings31826802013-10-19 00:09:25 -07002579
Larry Hastings2f936352014-08-05 14:04:04 +10002580class fildes_converter(CConverter):
2581 type = 'int'
2582 converter = 'fildes_converter'
2583
2584class uid_t_converter(CConverter):
2585 type = "uid_t"
2586 converter = '_Py_Uid_Converter'
2587
2588class gid_t_converter(CConverter):
2589 type = "gid_t"
2590 converter = '_Py_Gid_Converter'
2591
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02002592class dev_t_converter(CConverter):
2593 type = 'dev_t'
2594 converter = '_Py_Dev_Converter'
2595
2596class dev_t_return_converter(unsigned_long_return_converter):
2597 type = 'dev_t'
2598 conversion_fn = '_PyLong_FromDev'
2599 unsigned_cast = '(dev_t)'
2600
Larry Hastings2f936352014-08-05 14:04:04 +10002601class FSConverter_converter(CConverter):
2602 type = 'PyObject *'
2603 converter = 'PyUnicode_FSConverter'
2604 def converter_init(self):
2605 if self.default is not unspecified:
2606 fail("FSConverter_converter does not support default values")
2607 self.c_default = 'NULL'
2608
2609 def cleanup(self):
2610 return "Py_XDECREF(" + self.name + ");\n"
2611
2612class pid_t_converter(CConverter):
2613 type = 'pid_t'
2614 format_unit = '" _Py_PARSE_PID "'
2615
2616class idtype_t_converter(int_converter):
2617 type = 'idtype_t'
2618
2619class id_t_converter(CConverter):
2620 type = 'id_t'
2621 format_unit = '" _Py_PARSE_PID "'
2622
Benjamin Petersonca470632016-09-06 13:47:26 -07002623class intptr_t_converter(CConverter):
2624 type = 'intptr_t'
Larry Hastings2f936352014-08-05 14:04:04 +10002625 format_unit = '" _Py_PARSE_INTPTR "'
2626
2627class Py_off_t_converter(CConverter):
2628 type = 'Py_off_t'
2629 converter = 'Py_off_t_converter'
2630
2631class Py_off_t_return_converter(long_return_converter):
2632 type = 'Py_off_t'
2633 conversion_fn = 'PyLong_FromPy_off_t'
2634
2635class path_confname_converter(CConverter):
2636 type="int"
2637 converter="conv_path_confname"
2638
2639class confstr_confname_converter(path_confname_converter):
2640 converter='conv_confstr_confname'
2641
2642class sysconf_confname_converter(path_confname_converter):
2643 converter="conv_sysconf_confname"
2644
2645class sched_param_converter(CConverter):
2646 type = 'struct sched_param'
2647 converter = 'convert_sched_param'
2648 impl_by_reference = True;
Larry Hastings31826802013-10-19 00:09:25 -07002649
Larry Hastings61272b72014-01-07 12:41:53 -08002650[python start generated code]*/
Victor Stinner581139c2016-09-06 15:54:20 -07002651/*[python end generated code: output=da39a3ee5e6b4b0d input=418fce0e01144461]*/
Larry Hastings31826802013-10-19 00:09:25 -07002652
Larry Hastings61272b72014-01-07 12:41:53 -08002653/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002654
Larry Hastings2a727912014-01-16 11:32:01 -08002655os.stat
Larry Hastings31826802013-10-19 00:09:25 -07002656
2657 path : path_t(allow_fd=True)
BNMetricsb9427072018-11-02 15:20:19 +00002658 Path to be examined; can be string, bytes, a path-like object or
Xiang Zhang4459e002017-01-22 13:04:17 +08002659 open-file-descriptor int.
Larry Hastings31826802013-10-19 00:09:25 -07002660
2661 *
2662
Larry Hastings2f936352014-08-05 14:04:04 +10002663 dir_fd : dir_fd(requires='fstatat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002664 If not None, it should be a file descriptor open to a directory,
2665 and path should be a relative string; path will then be relative to
2666 that directory.
2667
2668 follow_symlinks: bool = True
2669 If False, and the last element of the path is a symbolic link,
2670 stat will examine the symbolic link itself instead of the file
2671 the link points to.
2672
2673Perform a stat system call on the given path.
2674
2675dir_fd and follow_symlinks may not be implemented
2676 on your platform. If they are unavailable, using them will raise a
2677 NotImplementedError.
2678
2679It's an error to use dir_fd or follow_symlinks when specifying path as
2680 an open file descriptor.
2681
Larry Hastings61272b72014-01-07 12:41:53 -08002682[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002683
Larry Hastings31826802013-10-19 00:09:25 -07002684static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002685os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002686/*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
Larry Hastings31826802013-10-19 00:09:25 -07002687{
2688 return posix_do_stat("stat", path, dir_fd, follow_symlinks);
2689}
2690
Larry Hastings2f936352014-08-05 14:04:04 +10002691
2692/*[clinic input]
2693os.lstat
2694
2695 path : path_t
2696
2697 *
2698
2699 dir_fd : dir_fd(requires='fstatat') = None
2700
2701Perform a stat system call on the given path, without following symbolic links.
2702
2703Like stat(), but do not follow symbolic links.
2704Equivalent to stat(path, follow_symlinks=False).
2705[clinic start generated code]*/
2706
Larry Hastings2f936352014-08-05 14:04:04 +10002707static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002708os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
2709/*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002710{
2711 int follow_symlinks = 0;
2712 return posix_do_stat("lstat", path, dir_fd, follow_symlinks);
2713}
Larry Hastings31826802013-10-19 00:09:25 -07002714
Larry Hastings2f936352014-08-05 14:04:04 +10002715
Larry Hastings61272b72014-01-07 12:41:53 -08002716/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10002717os.access -> bool
Larry Hastings31826802013-10-19 00:09:25 -07002718
Benjamin Peterson768f3b42016-09-05 15:29:33 -07002719 path: path_t
BNMetricsb9427072018-11-02 15:20:19 +00002720 Path to be tested; can be string, bytes, or a path-like object.
Larry Hastings31826802013-10-19 00:09:25 -07002721
2722 mode: int
2723 Operating-system mode bitfield. Can be F_OK to test existence,
2724 or the inclusive-OR of R_OK, W_OK, and X_OK.
2725
2726 *
2727
Larry Hastings2f936352014-08-05 14:04:04 +10002728 dir_fd : dir_fd(requires='faccessat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002729 If not None, it should be a file descriptor open to a directory,
2730 and path should be relative; path will then be relative to that
2731 directory.
2732
2733 effective_ids: bool = False
2734 If True, access will use the effective uid/gid instead of
2735 the real uid/gid.
2736
2737 follow_symlinks: bool = True
2738 If False, and the last element of the path is a symbolic link,
2739 access will examine the symbolic link itself instead of the file
2740 the link points to.
2741
2742Use the real uid/gid to test for access to a path.
2743
2744{parameters}
2745dir_fd, effective_ids, and follow_symlinks may not be implemented
2746 on your platform. If they are unavailable, using them will raise a
2747 NotImplementedError.
2748
2749Note that most operations will use the effective uid/gid, therefore this
2750 routine can be used in a suid/sgid environment to test if the invoking user
2751 has the specified access to the path.
2752
Larry Hastings61272b72014-01-07 12:41:53 -08002753[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002754
Larry Hastings2f936352014-08-05 14:04:04 +10002755static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002756os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002757 int effective_ids, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002758/*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
Larry Hastings31826802013-10-19 00:09:25 -07002759{
Larry Hastings2f936352014-08-05 14:04:04 +10002760 int return_value;
Victor Stinner8c62be82010-05-06 00:08:46 +00002761
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002762#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002763 DWORD attr;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002764#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07002765 int result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002766#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07002767
Larry Hastings9cf065c2012-06-22 16:30:09 -07002768#ifndef HAVE_FACCESSAT
2769 if (follow_symlinks_specified("access", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002770 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002771
2772 if (effective_ids) {
2773 argument_unavailable_error("access", "effective_ids");
Larry Hastings2f936352014-08-05 14:04:04 +10002774 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002775 }
2776#endif
2777
2778#ifdef MS_WINDOWS
2779 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002780 attr = GetFileAttributesW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002781 Py_END_ALLOW_THREADS
2782
2783 /*
Georg Brandlf7875592012-06-24 13:58:31 +02002784 * Access is possible if
Larry Hastings9cf065c2012-06-22 16:30:09 -07002785 * * we didn't get a -1, and
2786 * * write access wasn't requested,
2787 * * or the file isn't read-only,
2788 * * or it's a directory.
2789 * (Directories cannot be read-only on Windows.)
2790 */
Larry Hastings2f936352014-08-05 14:04:04 +10002791 return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
Georg Brandl5bb7aa92012-06-23 12:48:40 +02002792 (!(mode & 2) ||
Larry Hastings9cf065c2012-06-22 16:30:09 -07002793 !(attr & FILE_ATTRIBUTE_READONLY) ||
Larry Hastings2f936352014-08-05 14:04:04 +10002794 (attr & FILE_ATTRIBUTE_DIRECTORY));
Larry Hastings9cf065c2012-06-22 16:30:09 -07002795#else
2796
2797 Py_BEGIN_ALLOW_THREADS
2798#ifdef HAVE_FACCESSAT
2799 if ((dir_fd != DEFAULT_DIR_FD) ||
2800 effective_ids ||
2801 !follow_symlinks) {
2802 int flags = 0;
2803 if (!follow_symlinks)
2804 flags |= AT_SYMLINK_NOFOLLOW;
2805 if (effective_ids)
2806 flags |= AT_EACCESS;
Larry Hastings31826802013-10-19 00:09:25 -07002807 result = faccessat(dir_fd, path->narrow, mode, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002808 }
2809 else
2810#endif
Larry Hastings31826802013-10-19 00:09:25 -07002811 result = access(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002812 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10002813 return_value = !result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002814#endif
2815
Larry Hastings9cf065c2012-06-22 16:30:09 -07002816 return return_value;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002817}
2818
Guido van Rossumd371ff11999-01-25 16:12:23 +00002819#ifndef F_OK
2820#define F_OK 0
2821#endif
2822#ifndef R_OK
2823#define R_OK 4
2824#endif
2825#ifndef W_OK
2826#define W_OK 2
2827#endif
2828#ifndef X_OK
2829#define X_OK 1
2830#endif
2831
Larry Hastings31826802013-10-19 00:09:25 -07002832
Guido van Rossumd371ff11999-01-25 16:12:23 +00002833#ifdef HAVE_TTYNAME
Larry Hastings61272b72014-01-07 12:41:53 -08002834/*[clinic input]
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002835os.ttyname
Larry Hastings31826802013-10-19 00:09:25 -07002836
2837 fd: int
2838 Integer file descriptor handle.
2839
2840 /
2841
2842Return the name of the terminal device connected to 'fd'.
Larry Hastings61272b72014-01-07 12:41:53 -08002843[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002844
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002845static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002846os_ttyname_impl(PyObject *module, int fd)
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002847/*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
Larry Hastings31826802013-10-19 00:09:25 -07002848{
Guido van Rossum94f6f721999-01-06 18:42:14 +00002849
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002850 long size = sysconf(_SC_TTY_NAME_MAX);
2851 if (size == -1) {
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002852 return posix_error();
2853 }
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002854 char *buffer = (char *)PyMem_RawMalloc(size);
2855 if (buffer == NULL) {
2856 return PyErr_NoMemory();
2857 }
2858 int ret = ttyname_r(fd, buffer, size);
2859 if (ret != 0) {
2860 PyMem_RawFree(buffer);
2861 errno = ret;
2862 return posix_error();
2863 }
2864 PyObject *res = PyUnicode_DecodeFSDefault(buffer);
2865 PyMem_RawFree(buffer);
2866 return res;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002867}
Guido van Rossumd371ff11999-01-25 16:12:23 +00002868#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +00002869
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002870#ifdef HAVE_CTERMID
Larry Hastings2f936352014-08-05 14:04:04 +10002871/*[clinic input]
2872os.ctermid
2873
2874Return the name of the controlling terminal for this process.
2875[clinic start generated code]*/
2876
Larry Hastings2f936352014-08-05 14:04:04 +10002877static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002878os_ctermid_impl(PyObject *module)
2879/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002880{
Victor Stinner8c62be82010-05-06 00:08:46 +00002881 char *ret;
2882 char buffer[L_ctermid];
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002883
Greg Wardb48bc172000-03-01 21:51:56 +00002884#ifdef USE_CTERMID_R
Victor Stinner8c62be82010-05-06 00:08:46 +00002885 ret = ctermid_r(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002886#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002887 ret = ctermid(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002888#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002889 if (ret == NULL)
2890 return posix_error();
Victor Stinner5fe6de82010-08-15 09:12:51 +00002891 return PyUnicode_DecodeFSDefault(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002892}
Larry Hastings2f936352014-08-05 14:04:04 +10002893#endif /* HAVE_CTERMID */
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002894
Larry Hastings2f936352014-08-05 14:04:04 +10002895
2896/*[clinic input]
2897os.chdir
2898
2899 path: path_t(allow_fd='PATH_HAVE_FCHDIR')
2900
2901Change the current working directory to the specified path.
2902
2903path may always be specified as a string.
2904On some platforms, path may also be specified as an open file descriptor.
2905 If this functionality is unavailable, using it raises an exception.
2906[clinic start generated code]*/
2907
Larry Hastings2f936352014-08-05 14:04:04 +10002908static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002909os_chdir_impl(PyObject *module, path_t *path)
2910/*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002911{
2912 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002913
2914 Py_BEGIN_ALLOW_THREADS
2915#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07002916 /* on unix, success = 0, on windows, success = !0 */
2917 result = !win32_wchdir(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002918#else
2919#ifdef HAVE_FCHDIR
Larry Hastings2f936352014-08-05 14:04:04 +10002920 if (path->fd != -1)
2921 result = fchdir(path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002922 else
2923#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002924 result = chdir(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002925#endif
2926 Py_END_ALLOW_THREADS
2927
2928 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002929 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002930 }
2931
Larry Hastings2f936352014-08-05 14:04:04 +10002932 Py_RETURN_NONE;
2933}
2934
2935
2936#ifdef HAVE_FCHDIR
2937/*[clinic input]
2938os.fchdir
2939
2940 fd: fildes
2941
2942Change to the directory of the given file descriptor.
2943
2944fd must be opened on a directory, not a file.
2945Equivalent to os.chdir(fd).
2946
2947[clinic start generated code]*/
2948
Fred Drake4d1e64b2002-04-15 19:40:07 +00002949static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002950os_fchdir_impl(PyObject *module, int fd)
2951/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
Fred Drake4d1e64b2002-04-15 19:40:07 +00002952{
Larry Hastings2f936352014-08-05 14:04:04 +10002953 return posix_fildes_fd(fd, fchdir);
Fred Drake4d1e64b2002-04-15 19:40:07 +00002954}
2955#endif /* HAVE_FCHDIR */
2956
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00002957
Larry Hastings2f936352014-08-05 14:04:04 +10002958/*[clinic input]
2959os.chmod
2960
2961 path: path_t(allow_fd='PATH_HAVE_FCHMOD')
BNMetricsb9427072018-11-02 15:20:19 +00002962 Path to be modified. May always be specified as a str, bytes, or a path-like object.
Larry Hastings2f936352014-08-05 14:04:04 +10002963 On some platforms, path may also be specified as an open file descriptor.
2964 If this functionality is unavailable, using it raises an exception.
2965
2966 mode: int
2967 Operating-system mode bitfield.
2968
2969 *
2970
2971 dir_fd : dir_fd(requires='fchmodat') = None
2972 If not None, it should be a file descriptor open to a directory,
2973 and path should be relative; path will then be relative to that
2974 directory.
2975
2976 follow_symlinks: bool = True
2977 If False, and the last element of the path is a symbolic link,
2978 chmod will modify the symbolic link itself instead of the file
2979 the link points to.
2980
2981Change the access permissions of a file.
2982
2983It is an error to use dir_fd or follow_symlinks when specifying path as
2984 an open file descriptor.
2985dir_fd and follow_symlinks may not be implemented on your platform.
2986 If they are unavailable, using them will raise a NotImplementedError.
2987
2988[clinic start generated code]*/
2989
Larry Hastings2f936352014-08-05 14:04:04 +10002990static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002991os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002992 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002993/*[clinic end generated code: output=5cf6a94915cc7bff input=989081551c00293b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002994{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002995 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002996
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002997#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002998 DWORD attr;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002999#endif
Hirokazu Yamamoto892a37a2009-06-28 11:07:03 +00003000
Larry Hastings9cf065c2012-06-22 16:30:09 -07003001#ifdef HAVE_FCHMODAT
3002 int fchmodat_nofollow_unsupported = 0;
3003#endif
3004
Larry Hastings9cf065c2012-06-22 16:30:09 -07003005#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
3006 if (follow_symlinks_specified("chmod", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003007 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003008#endif
3009
3010#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003011 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003012 attr = GetFileAttributesW(path->wide);
Tim Golden23005082013-10-25 11:22:37 +01003013 if (attr == INVALID_FILE_ATTRIBUTES)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003014 result = 0;
3015 else {
3016 if (mode & _S_IWRITE)
Victor Stinner8c62be82010-05-06 00:08:46 +00003017 attr &= ~FILE_ATTRIBUTE_READONLY;
3018 else
3019 attr |= FILE_ATTRIBUTE_READONLY;
Steve Dowercc16be82016-09-08 10:35:16 -07003020 result = SetFileAttributesW(path->wide, attr);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003021 }
3022 Py_END_ALLOW_THREADS
3023
3024 if (!result) {
Larry Hastings2f936352014-08-05 14:04:04 +10003025 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003026 }
3027#else /* MS_WINDOWS */
3028 Py_BEGIN_ALLOW_THREADS
3029#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003030 if (path->fd != -1)
3031 result = fchmod(path->fd, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003032 else
3033#endif
3034#ifdef HAVE_LCHMOD
3035 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003036 result = lchmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003037 else
3038#endif
3039#ifdef HAVE_FCHMODAT
3040 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
3041 /*
3042 * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
3043 * The documentation specifically shows how to use it,
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003044 * and then says it isn't implemented yet.
3045 * (true on linux with glibc 2.15, and openindiana 3.x)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003046 *
3047 * Once it is supported, os.chmod will automatically
3048 * support dir_fd and follow_symlinks=False. (Hopefully.)
3049 * Until then, we need to be careful what exception we raise.
3050 */
Larry Hastings2f936352014-08-05 14:04:04 +10003051 result = fchmodat(dir_fd, path->narrow, mode,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003052 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3053 /*
3054 * But wait! We can't throw the exception without allowing threads,
3055 * and we can't do that in this nested scope. (Macro trickery, sigh.)
3056 */
3057 fchmodat_nofollow_unsupported =
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003058 result &&
3059 ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
3060 !follow_symlinks;
Victor Stinner8c62be82010-05-06 00:08:46 +00003061 }
3062 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00003063#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003064 result = chmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003065 Py_END_ALLOW_THREADS
3066
3067 if (result) {
3068#ifdef HAVE_FCHMODAT
3069 if (fchmodat_nofollow_unsupported) {
3070 if (dir_fd != DEFAULT_DIR_FD)
3071 dir_fd_and_follow_symlinks_invalid("chmod",
3072 dir_fd, follow_symlinks);
3073 else
3074 follow_symlinks_specified("chmod", follow_symlinks);
Anthony Sottile233ef242017-12-14 08:57:55 -08003075 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003076 }
3077 else
3078#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003079 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003080 }
3081#endif
3082
Larry Hastings2f936352014-08-05 14:04:04 +10003083 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003084}
3085
Larry Hastings9cf065c2012-06-22 16:30:09 -07003086
Christian Heimes4e30a842007-11-30 22:12:06 +00003087#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003088/*[clinic input]
3089os.fchmod
3090
3091 fd: int
3092 mode: int
3093
3094Change the access permissions of the file given by file descriptor fd.
3095
3096Equivalent to os.chmod(fd, mode).
3097[clinic start generated code]*/
3098
Larry Hastings2f936352014-08-05 14:04:04 +10003099static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003100os_fchmod_impl(PyObject *module, int fd, int mode)
3101/*[clinic end generated code: output=afd9bc05b4e426b3 input=8ab11975ca01ee5b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003102{
3103 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003104 int async_err = 0;
3105
3106 do {
3107 Py_BEGIN_ALLOW_THREADS
3108 res = fchmod(fd, mode);
3109 Py_END_ALLOW_THREADS
3110 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3111 if (res != 0)
3112 return (!async_err) ? posix_error() : NULL;
3113
Victor Stinner8c62be82010-05-06 00:08:46 +00003114 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003115}
3116#endif /* HAVE_FCHMOD */
3117
Larry Hastings2f936352014-08-05 14:04:04 +10003118
Christian Heimes4e30a842007-11-30 22:12:06 +00003119#ifdef HAVE_LCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003120/*[clinic input]
3121os.lchmod
3122
3123 path: path_t
3124 mode: int
3125
3126Change the access permissions of a file, without following symbolic links.
3127
3128If path is a symlink, this affects the link itself rather than the target.
3129Equivalent to chmod(path, mode, follow_symlinks=False)."
3130[clinic start generated code]*/
3131
Larry Hastings2f936352014-08-05 14:04:04 +10003132static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003133os_lchmod_impl(PyObject *module, path_t *path, int mode)
3134/*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003135{
Victor Stinner8c62be82010-05-06 00:08:46 +00003136 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003137 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003138 res = lchmod(path->narrow, mode);
Victor Stinner8c62be82010-05-06 00:08:46 +00003139 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003140 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003141 path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003142 return NULL;
3143 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003144 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003145}
3146#endif /* HAVE_LCHMOD */
3147
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003148
Thomas Wouterscf297e42007-02-23 15:07:44 +00003149#ifdef HAVE_CHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003150/*[clinic input]
3151os.chflags
3152
3153 path: path_t
3154 flags: unsigned_long(bitwise=True)
3155 follow_symlinks: bool=True
3156
3157Set file flags.
3158
3159If follow_symlinks is False, and the last element of the path is a symbolic
3160 link, chflags will change flags on the symbolic link itself instead of the
3161 file the link points to.
3162follow_symlinks may not be implemented on your platform. If it is
3163unavailable, using it will raise a NotImplementedError.
3164
3165[clinic start generated code]*/
3166
Larry Hastings2f936352014-08-05 14:04:04 +10003167static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003168os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
Larry Hastings89964c42015-04-14 18:07:59 -04003169 int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003170/*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003171{
3172 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003173
3174#ifndef HAVE_LCHFLAGS
3175 if (follow_symlinks_specified("chflags", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003176 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003177#endif
3178
Victor Stinner8c62be82010-05-06 00:08:46 +00003179 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003180#ifdef HAVE_LCHFLAGS
3181 if (!follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +10003182 result = lchflags(path->narrow, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003183 else
3184#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003185 result = chflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003186 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003187
Larry Hastings2f936352014-08-05 14:04:04 +10003188 if (result)
3189 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003190
Larry Hastings2f936352014-08-05 14:04:04 +10003191 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003192}
3193#endif /* HAVE_CHFLAGS */
3194
Larry Hastings2f936352014-08-05 14:04:04 +10003195
Thomas Wouterscf297e42007-02-23 15:07:44 +00003196#ifdef HAVE_LCHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003197/*[clinic input]
3198os.lchflags
3199
3200 path: path_t
3201 flags: unsigned_long(bitwise=True)
3202
3203Set file flags.
3204
3205This function will not follow symbolic links.
3206Equivalent to chflags(path, flags, follow_symlinks=False).
3207[clinic start generated code]*/
3208
Larry Hastings2f936352014-08-05 14:04:04 +10003209static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003210os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
3211/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003212{
Victor Stinner8c62be82010-05-06 00:08:46 +00003213 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003214 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003215 res = lchflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003216 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003217 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003218 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003219 }
Victor Stinner292c8352012-10-30 02:17:38 +01003220 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003221}
3222#endif /* HAVE_LCHFLAGS */
3223
Larry Hastings2f936352014-08-05 14:04:04 +10003224
Martin v. Löwis244edc82001-10-04 22:44:26 +00003225#ifdef HAVE_CHROOT
Larry Hastings2f936352014-08-05 14:04:04 +10003226/*[clinic input]
3227os.chroot
3228 path: path_t
3229
3230Change root directory to path.
3231
3232[clinic start generated code]*/
3233
Larry Hastings2f936352014-08-05 14:04:04 +10003234static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003235os_chroot_impl(PyObject *module, path_t *path)
3236/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003237{
3238 int res;
3239 Py_BEGIN_ALLOW_THREADS
3240 res = chroot(path->narrow);
3241 Py_END_ALLOW_THREADS
3242 if (res < 0)
3243 return path_error(path);
3244 Py_RETURN_NONE;
3245}
3246#endif /* HAVE_CHROOT */
3247
Martin v. Löwis244edc82001-10-04 22:44:26 +00003248
Guido van Rossum21142a01999-01-08 21:05:37 +00003249#ifdef HAVE_FSYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003250/*[clinic input]
3251os.fsync
3252
3253 fd: fildes
3254
3255Force write of fd to disk.
3256[clinic start generated code]*/
3257
Larry Hastings2f936352014-08-05 14:04:04 +10003258static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003259os_fsync_impl(PyObject *module, int fd)
3260/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003261{
3262 return posix_fildes_fd(fd, fsync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003263}
3264#endif /* HAVE_FSYNC */
3265
Larry Hastings2f936352014-08-05 14:04:04 +10003266
Ross Lagerwall7807c352011-03-17 20:20:30 +02003267#ifdef HAVE_SYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003268/*[clinic input]
3269os.sync
3270
3271Force write of everything to disk.
3272[clinic start generated code]*/
3273
Larry Hastings2f936352014-08-05 14:04:04 +10003274static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003275os_sync_impl(PyObject *module)
3276/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
Ross Lagerwall7807c352011-03-17 20:20:30 +02003277{
3278 Py_BEGIN_ALLOW_THREADS
3279 sync();
3280 Py_END_ALLOW_THREADS
3281 Py_RETURN_NONE;
3282}
Larry Hastings2f936352014-08-05 14:04:04 +10003283#endif /* HAVE_SYNC */
3284
Ross Lagerwall7807c352011-03-17 20:20:30 +02003285
Guido van Rossum21142a01999-01-08 21:05:37 +00003286#ifdef HAVE_FDATASYNC
Guido van Rossum7f58e2e2000-09-22 17:26:14 +00003287#ifdef __hpux
Guido van Rossumecc23b02000-09-22 16:01:05 +00003288extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
3289#endif
3290
Larry Hastings2f936352014-08-05 14:04:04 +10003291/*[clinic input]
3292os.fdatasync
3293
3294 fd: fildes
3295
3296Force write of fd to disk without forcing update of metadata.
3297[clinic start generated code]*/
3298
Larry Hastings2f936352014-08-05 14:04:04 +10003299static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003300os_fdatasync_impl(PyObject *module, int fd)
3301/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003302{
3303 return posix_fildes_fd(fd, fdatasync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003304}
3305#endif /* HAVE_FDATASYNC */
3306
3307
Fredrik Lundh10723342000-07-10 16:38:09 +00003308#ifdef HAVE_CHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003309/*[clinic input]
3310os.chown
3311
3312 path : path_t(allow_fd='PATH_HAVE_FCHOWN')
BNMetricsb9427072018-11-02 15:20:19 +00003313 Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
Larry Hastings2f936352014-08-05 14:04:04 +10003314
3315 uid: uid_t
3316
3317 gid: gid_t
3318
3319 *
3320
3321 dir_fd : dir_fd(requires='fchownat') = None
3322 If not None, it should be a file descriptor open to a directory,
3323 and path should be relative; path will then be relative to that
3324 directory.
3325
3326 follow_symlinks: bool = True
3327 If False, and the last element of the path is a symbolic link,
3328 stat will examine the symbolic link itself instead of the file
3329 the link points to.
3330
3331Change the owner and group id of path to the numeric uid and gid.\
3332
3333path may always be specified as a string.
3334On some platforms, path may also be specified as an open file descriptor.
3335 If this functionality is unavailable, using it raises an exception.
3336If dir_fd is not None, it should be a file descriptor open to a directory,
3337 and path should be relative; path will then be relative to that directory.
3338If follow_symlinks is False, and the last element of the path is a symbolic
3339 link, chown will modify the symbolic link itself instead of the file the
3340 link points to.
3341It is an error to use dir_fd or follow_symlinks when specifying path as
3342 an open file descriptor.
3343dir_fd and follow_symlinks may not be implemented on your platform.
3344 If they are unavailable, using them will raise a NotImplementedError.
3345
3346[clinic start generated code]*/
3347
Larry Hastings2f936352014-08-05 14:04:04 +10003348static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003349os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
Larry Hastings89964c42015-04-14 18:07:59 -04003350 int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003351/*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003352{
3353 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003354
3355#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
3356 if (follow_symlinks_specified("chown", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003357 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003358#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003359 if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
3360 fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
3361 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003362
3363#ifdef __APPLE__
3364 /*
3365 * This is for Mac OS X 10.3, which doesn't have lchown.
3366 * (But we still have an lchown symbol because of weak-linking.)
3367 * It doesn't have fchownat either. So there's no possibility
3368 * of a graceful failover.
Georg Brandlf7875592012-06-24 13:58:31 +02003369 */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003370 if ((!follow_symlinks) && (lchown == NULL)) {
3371 follow_symlinks_specified("chown", follow_symlinks);
Larry Hastings2f936352014-08-05 14:04:04 +10003372 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003373 }
3374#endif
3375
Victor Stinner8c62be82010-05-06 00:08:46 +00003376 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003377#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003378 if (path->fd != -1)
3379 result = fchown(path->fd, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003380 else
3381#endif
3382#ifdef HAVE_LCHOWN
3383 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003384 result = lchown(path->narrow, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003385 else
3386#endif
3387#ifdef HAVE_FCHOWNAT
3388 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003389 result = fchownat(dir_fd, path->narrow, uid, gid,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003390 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3391 else
3392#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003393 result = chown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003394 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003395
Larry Hastings2f936352014-08-05 14:04:04 +10003396 if (result)
3397 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003398
Larry Hastings2f936352014-08-05 14:04:04 +10003399 Py_RETURN_NONE;
Guido van Rossumb6775db1994-08-01 11:34:53 +00003400}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003401#endif /* HAVE_CHOWN */
Guido van Rossumb6775db1994-08-01 11:34:53 +00003402
Larry Hastings2f936352014-08-05 14:04:04 +10003403
Christian Heimes4e30a842007-11-30 22:12:06 +00003404#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003405/*[clinic input]
3406os.fchown
3407
3408 fd: int
3409 uid: uid_t
3410 gid: gid_t
3411
3412Change the owner and group id of the file specified by file descriptor.
3413
3414Equivalent to os.chown(fd, uid, gid).
3415
3416[clinic start generated code]*/
3417
Larry Hastings2f936352014-08-05 14:04:04 +10003418static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003419os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
3420/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003421{
Victor Stinner8c62be82010-05-06 00:08:46 +00003422 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003423 int async_err = 0;
3424
3425 do {
3426 Py_BEGIN_ALLOW_THREADS
3427 res = fchown(fd, uid, gid);
3428 Py_END_ALLOW_THREADS
3429 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3430 if (res != 0)
3431 return (!async_err) ? posix_error() : NULL;
3432
Victor Stinner8c62be82010-05-06 00:08:46 +00003433 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003434}
3435#endif /* HAVE_FCHOWN */
3436
Larry Hastings2f936352014-08-05 14:04:04 +10003437
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003438#ifdef HAVE_LCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003439/*[clinic input]
3440os.lchown
3441
3442 path : path_t
3443 uid: uid_t
3444 gid: gid_t
3445
3446Change the owner and group id of path to the numeric uid and gid.
3447
3448This function will not follow symbolic links.
3449Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
3450[clinic start generated code]*/
3451
Larry Hastings2f936352014-08-05 14:04:04 +10003452static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003453os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
3454/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003455{
Victor Stinner8c62be82010-05-06 00:08:46 +00003456 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003457 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10003458 res = lchown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003459 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003460 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003461 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003462 }
Larry Hastings2f936352014-08-05 14:04:04 +10003463 Py_RETURN_NONE;
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003464}
3465#endif /* HAVE_LCHOWN */
3466
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003467
Barry Warsaw53699e91996-12-10 23:23:01 +00003468static PyObject *
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003469posix_getcwd(int use_bytes)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003470{
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003471#ifdef MS_WINDOWS
Victor Stinner689830e2019-06-26 17:31:12 +02003472 wchar_t wbuf[MAXPATHLEN];
3473 wchar_t *wbuf2 = wbuf;
3474 DWORD len;
3475
3476 Py_BEGIN_ALLOW_THREADS
3477 len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
3478 /* If the buffer is large enough, len does not include the
3479 terminating \0. If the buffer is too small, len includes
3480 the space needed for the terminator. */
3481 if (len >= Py_ARRAY_LENGTH(wbuf)) {
Victor Stinnerec3e20a2019-06-28 18:01:59 +02003482 if (len <= PY_SSIZE_T_MAX / sizeof(wchar_t)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02003483 wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00003484 }
Victor Stinner689830e2019-06-26 17:31:12 +02003485 else {
3486 wbuf2 = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003487 }
Victor Stinner689830e2019-06-26 17:31:12 +02003488 if (wbuf2) {
3489 len = GetCurrentDirectoryW(len, wbuf2);
Victor Stinner8c62be82010-05-06 00:08:46 +00003490 }
Victor Stinner689830e2019-06-26 17:31:12 +02003491 }
3492 Py_END_ALLOW_THREADS
3493
3494 if (!wbuf2) {
3495 PyErr_NoMemory();
3496 return NULL;
3497 }
3498 if (!len) {
Victor Stinnerb024e842012-10-31 22:24:06 +01003499 if (wbuf2 != wbuf)
Victor Stinnerb6404912013-07-07 16:21:41 +02003500 PyMem_RawFree(wbuf2);
Victor Stinner689830e2019-06-26 17:31:12 +02003501 return PyErr_SetFromWindowsErr(0);
Victor Stinner8c62be82010-05-06 00:08:46 +00003502 }
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01003503
Victor Stinner689830e2019-06-26 17:31:12 +02003504 PyObject *resobj = PyUnicode_FromWideChar(wbuf2, len);
3505 if (wbuf2 != wbuf) {
3506 PyMem_RawFree(wbuf2);
3507 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003508
Victor Stinner689830e2019-06-26 17:31:12 +02003509 if (use_bytes) {
3510 if (resobj == NULL) {
3511 return NULL;
3512 }
3513 Py_SETREF(resobj, PyUnicode_EncodeFSDefault(resobj));
3514 }
3515
3516 return resobj;
3517#else
3518 const size_t chunk = 1024;
3519
3520 char *buf = NULL;
3521 char *cwd = NULL;
3522 size_t buflen = 0;
3523
Victor Stinner8c62be82010-05-06 00:08:46 +00003524 Py_BEGIN_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003525 do {
Victor Stinner689830e2019-06-26 17:31:12 +02003526 char *newbuf;
3527 if (buflen <= PY_SSIZE_T_MAX - chunk) {
3528 buflen += chunk;
3529 newbuf = PyMem_RawRealloc(buf, buflen);
3530 }
3531 else {
3532 newbuf = NULL;
3533 }
3534 if (newbuf == NULL) {
3535 PyMem_RawFree(buf);
3536 buf = NULL;
Victor Stinnerc44f7072016-03-14 18:07:53 +01003537 break;
3538 }
Victor Stinner689830e2019-06-26 17:31:12 +02003539 buf = newbuf;
Victor Stinner4403d7d2015-04-25 00:16:10 +02003540
Victor Stinner4403d7d2015-04-25 00:16:10 +02003541 cwd = getcwd(buf, buflen);
3542 } while (cwd == NULL && errno == ERANGE);
Victor Stinner8c62be82010-05-06 00:08:46 +00003543 Py_END_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003544
Victor Stinner689830e2019-06-26 17:31:12 +02003545 if (buf == NULL) {
3546 return PyErr_NoMemory();
3547 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003548 if (cwd == NULL) {
3549 PyMem_RawFree(buf);
Victor Stinner8c62be82010-05-06 00:08:46 +00003550 return posix_error();
Victor Stinner4403d7d2015-04-25 00:16:10 +02003551 }
3552
Victor Stinner689830e2019-06-26 17:31:12 +02003553 PyObject *obj;
3554 if (use_bytes) {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003555 obj = PyBytes_FromStringAndSize(buf, strlen(buf));
Victor Stinner689830e2019-06-26 17:31:12 +02003556 }
3557 else {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003558 obj = PyUnicode_DecodeFSDefault(buf);
Victor Stinner689830e2019-06-26 17:31:12 +02003559 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003560 PyMem_RawFree(buf);
3561
3562 return obj;
Victor Stinner689830e2019-06-26 17:31:12 +02003563#endif /* !MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003564}
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003565
Larry Hastings2f936352014-08-05 14:04:04 +10003566
3567/*[clinic input]
3568os.getcwd
3569
3570Return a unicode string representing the current working directory.
3571[clinic start generated code]*/
3572
Larry Hastings2f936352014-08-05 14:04:04 +10003573static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003574os_getcwd_impl(PyObject *module)
3575/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003576{
3577 return posix_getcwd(0);
3578}
3579
Larry Hastings2f936352014-08-05 14:04:04 +10003580
3581/*[clinic input]
3582os.getcwdb
3583
3584Return a bytes string representing the current working directory.
3585[clinic start generated code]*/
3586
Larry Hastings2f936352014-08-05 14:04:04 +10003587static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003588os_getcwdb_impl(PyObject *module)
3589/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003590{
3591 return posix_getcwd(1);
3592}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003593
Larry Hastings2f936352014-08-05 14:04:04 +10003594
Larry Hastings9cf065c2012-06-22 16:30:09 -07003595#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
3596#define HAVE_LINK 1
3597#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003598
Guido van Rossumb6775db1994-08-01 11:34:53 +00003599#ifdef HAVE_LINK
Larry Hastings2f936352014-08-05 14:04:04 +10003600/*[clinic input]
3601
3602os.link
3603
3604 src : path_t
3605 dst : path_t
3606 *
3607 src_dir_fd : dir_fd = None
3608 dst_dir_fd : dir_fd = None
3609 follow_symlinks: bool = True
3610
3611Create a hard link to a file.
3612
3613If either src_dir_fd or dst_dir_fd is not None, it should be a file
3614 descriptor open to a directory, and the respective path string (src or dst)
3615 should be relative; the path will then be relative to that directory.
3616If follow_symlinks is False, and the last element of src is a symbolic
3617 link, link will create a link to the symbolic link itself instead of the
3618 file the link points to.
3619src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
3620 platform. If they are unavailable, using them will raise a
3621 NotImplementedError.
3622[clinic start generated code]*/
3623
Larry Hastings2f936352014-08-05 14:04:04 +10003624static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003625os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003626 int dst_dir_fd, int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003627/*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003628{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003629#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07003630 BOOL result = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003631#else
3632 int result;
3633#endif
3634
Larry Hastings9cf065c2012-06-22 16:30:09 -07003635#ifndef HAVE_LINKAT
3636 if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
3637 argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10003638 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003639 }
3640#endif
3641
Steve Dowercc16be82016-09-08 10:35:16 -07003642#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10003643 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003644 PyErr_SetString(PyExc_NotImplementedError,
3645 "link: src and dst must be the same type");
Larry Hastings2f936352014-08-05 14:04:04 +10003646 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003647 }
Steve Dowercc16be82016-09-08 10:35:16 -07003648#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003649
Brian Curtin1b9df392010-11-24 20:24:31 +00003650#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003651 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08003652 result = CreateHardLinkW(dst->wide, src->wide, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003653 Py_END_ALLOW_THREADS
Brian Curtin1b9df392010-11-24 20:24:31 +00003654
Larry Hastings2f936352014-08-05 14:04:04 +10003655 if (!result)
3656 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003657#else
3658 Py_BEGIN_ALLOW_THREADS
Larry Hastings67cbf7b2012-06-22 17:06:48 -07003659#ifdef HAVE_LINKAT
Larry Hastings9cf065c2012-06-22 16:30:09 -07003660 if ((src_dir_fd != DEFAULT_DIR_FD) ||
3661 (dst_dir_fd != DEFAULT_DIR_FD) ||
3662 (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003663 result = linkat(src_dir_fd, src->narrow,
3664 dst_dir_fd, dst->narrow,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003665 follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
3666 else
Steve Dowercc16be82016-09-08 10:35:16 -07003667#endif /* HAVE_LINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10003668 result = link(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003669 Py_END_ALLOW_THREADS
Brian Curtinfc889c42010-11-28 23:59:46 +00003670
Larry Hastings2f936352014-08-05 14:04:04 +10003671 if (result)
3672 return path_error2(src, dst);
Steve Dowercc16be82016-09-08 10:35:16 -07003673#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003674
Larry Hastings2f936352014-08-05 14:04:04 +10003675 Py_RETURN_NONE;
Brian Curtin1b9df392010-11-24 20:24:31 +00003676}
Larry Hastings9cf065c2012-06-22 16:30:09 -07003677#endif
3678
Brian Curtin1b9df392010-11-24 20:24:31 +00003679
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003680#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
Barry Warsaw53699e91996-12-10 23:23:01 +00003681static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003682_listdir_windows_no_opendir(path_t *path, PyObject *list)
Guido van Rossumb6775db1994-08-01 11:34:53 +00003683{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003684 PyObject *v;
3685 HANDLE hFindFile = INVALID_HANDLE_VALUE;
3686 BOOL result;
Steve Dowercc16be82016-09-08 10:35:16 -07003687 wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003688 /* only claim to have space for MAX_PATH */
Victor Stinner75875072013-11-24 19:23:25 +01003689 Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003690 wchar_t *wnamebuf = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003691
Steve Dowercc16be82016-09-08 10:35:16 -07003692 WIN32_FIND_DATAW wFileData;
3693 const wchar_t *po_wchars;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003694
Steve Dowercc16be82016-09-08 10:35:16 -07003695 if (!path->wide) { /* Default arg: "." */
3696 po_wchars = L".";
3697 len = 1;
3698 } else {
3699 po_wchars = path->wide;
3700 len = wcslen(path->wide);
3701 }
3702 /* The +5 is so we can append "\\*.*\0" */
3703 wnamebuf = PyMem_New(wchar_t, len + 5);
3704 if (!wnamebuf) {
3705 PyErr_NoMemory();
Larry Hastings9cf065c2012-06-22 16:30:09 -07003706 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003707 }
Steve Dowercc16be82016-09-08 10:35:16 -07003708 wcscpy(wnamebuf, po_wchars);
Victor Stinner8c62be82010-05-06 00:08:46 +00003709 if (len > 0) {
Steve Dowercc16be82016-09-08 10:35:16 -07003710 wchar_t wch = wnamebuf[len-1];
3711 if (wch != SEP && wch != ALTSEP && wch != L':')
3712 wnamebuf[len++] = SEP;
3713 wcscpy(wnamebuf + len, L"*.*");
Victor Stinner8c62be82010-05-06 00:08:46 +00003714 }
Steve Dowercc16be82016-09-08 10:35:16 -07003715 if ((list = PyList_New(0)) == NULL) {
3716 goto exit;
3717 }
Antoine Pitroub73caab2010-08-09 23:39:31 +00003718 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003719 hFindFile = FindFirstFileW(wnamebuf, &wFileData);
Antoine Pitroub73caab2010-08-09 23:39:31 +00003720 Py_END_ALLOW_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +00003721 if (hFindFile == INVALID_HANDLE_VALUE) {
3722 int error = GetLastError();
3723 if (error == ERROR_FILE_NOT_FOUND)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003724 goto exit;
3725 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003726 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003727 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003728 }
3729 do {
3730 /* Skip over . and .. */
Steve Dowercc16be82016-09-08 10:35:16 -07003731 if (wcscmp(wFileData.cFileName, L".") != 0 &&
3732 wcscmp(wFileData.cFileName, L"..") != 0) {
3733 v = PyUnicode_FromWideChar(wFileData.cFileName,
3734 wcslen(wFileData.cFileName));
3735 if (path->narrow && v) {
3736 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3737 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003738 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003739 Py_DECREF(list);
3740 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003741 break;
3742 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003743 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003744 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003745 Py_DECREF(list);
3746 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003747 break;
3748 }
3749 Py_DECREF(v);
3750 }
3751 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003752 result = FindNextFileW(hFindFile, &wFileData);
Victor Stinner8c62be82010-05-06 00:08:46 +00003753 Py_END_ALLOW_THREADS
3754 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
3755 it got to the end of the directory. */
3756 if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003757 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003758 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003759 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003760 }
3761 } while (result == TRUE);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003762
Larry Hastings9cf065c2012-06-22 16:30:09 -07003763exit:
3764 if (hFindFile != INVALID_HANDLE_VALUE) {
3765 if (FindClose(hFindFile) == FALSE) {
3766 if (list != NULL) {
3767 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003768 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003769 }
3770 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003771 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003772 PyMem_Free(wnamebuf);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003773
Larry Hastings9cf065c2012-06-22 16:30:09 -07003774 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003775} /* end of _listdir_windows_no_opendir */
3776
3777#else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
3778
3779static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003780_posix_listdir(path_t *path, PyObject *list)
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003781{
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003782 PyObject *v;
3783 DIR *dirp = NULL;
3784 struct dirent *ep;
3785 int return_str; /* if false, return bytes */
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003786#ifdef HAVE_FDOPENDIR
3787 int fd = -1;
3788#endif
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003789
Victor Stinner8c62be82010-05-06 00:08:46 +00003790 errno = 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003791#ifdef HAVE_FDOPENDIR
Gregory P. Smith40a21602013-03-20 20:52:50 -07003792 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003793 /* closedir() closes the FD, so we duplicate it */
Victor Stinnerdaf45552013-08-28 00:53:59 +02003794 fd = _Py_dup(path->fd);
Victor Stinnerf3266652013-12-19 13:24:49 +01003795 if (fd == -1)
3796 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003797
Larry Hastingsfdaea062012-06-25 04:42:23 -07003798 return_str = 1;
3799
Larry Hastings9cf065c2012-06-22 16:30:09 -07003800 Py_BEGIN_ALLOW_THREADS
3801 dirp = fdopendir(fd);
3802 Py_END_ALLOW_THREADS
3803 }
3804 else
3805#endif
3806 {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003807 const char *name;
Gregory P. Smith40a21602013-03-20 20:52:50 -07003808 if (path->narrow) {
3809 name = path->narrow;
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03003810 /* only return bytes if they specified a bytes-like object */
3811 return_str = !PyObject_CheckBuffer(path->object);
Larry Hastingsfdaea062012-06-25 04:42:23 -07003812 }
3813 else {
3814 name = ".";
3815 return_str = 1;
3816 }
3817
Larry Hastings9cf065c2012-06-22 16:30:09 -07003818 Py_BEGIN_ALLOW_THREADS
3819 dirp = opendir(name);
3820 Py_END_ALLOW_THREADS
3821 }
3822
3823 if (dirp == NULL) {
Gregory P. Smith40a21602013-03-20 20:52:50 -07003824 list = path_error(path);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003825#ifdef HAVE_FDOPENDIR
3826 if (fd != -1) {
3827 Py_BEGIN_ALLOW_THREADS
3828 close(fd);
3829 Py_END_ALLOW_THREADS
3830 }
3831#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003832 goto exit;
3833 }
3834 if ((list = PyList_New(0)) == NULL) {
3835 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003836 }
3837 for (;;) {
3838 errno = 0;
3839 Py_BEGIN_ALLOW_THREADS
3840 ep = readdir(dirp);
3841 Py_END_ALLOW_THREADS
3842 if (ep == NULL) {
3843 if (errno == 0) {
3844 break;
3845 } else {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003846 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003847 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003848 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003849 }
3850 }
3851 if (ep->d_name[0] == '.' &&
3852 (NAMLEN(ep) == 1 ||
3853 (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
3854 continue;
Larry Hastingsfdaea062012-06-25 04:42:23 -07003855 if (return_str)
Victor Stinnera45598a2010-05-14 16:35:39 +00003856 v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
3857 else
3858 v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
Victor Stinner8c62be82010-05-06 00:08:46 +00003859 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003860 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003861 break;
3862 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003863 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003864 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003865 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003866 break;
3867 }
3868 Py_DECREF(v);
3869 }
Guido van Rossum0ee42cd1991-04-08 21:01:03 +00003870
Larry Hastings9cf065c2012-06-22 16:30:09 -07003871exit:
3872 if (dirp != NULL) {
3873 Py_BEGIN_ALLOW_THREADS
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003874#ifdef HAVE_FDOPENDIR
Larry Hastings9cf065c2012-06-22 16:30:09 -07003875 if (fd > -1)
3876 rewinddir(dirp);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003877#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003878 closedir(dirp);
3879 Py_END_ALLOW_THREADS
3880 }
3881
Larry Hastings9cf065c2012-06-22 16:30:09 -07003882 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003883} /* end of _posix_listdir */
3884#endif /* which OS */
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003885
Larry Hastings2f936352014-08-05 14:04:04 +10003886
3887/*[clinic input]
3888os.listdir
3889
3890 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
3891
3892Return a list containing the names of the files in the directory.
3893
BNMetricsb9427072018-11-02 15:20:19 +00003894path can be specified as either str, bytes, or a path-like object. If path is bytes,
Larry Hastings2f936352014-08-05 14:04:04 +10003895 the filenames returned will also be bytes; in all other circumstances
3896 the filenames returned will be str.
3897If path is None, uses the path='.'.
3898On some platforms, path may also be specified as an open file descriptor;\
3899 the file descriptor must refer to a directory.
3900 If this functionality is unavailable, using it raises NotImplementedError.
3901
3902The list is in arbitrary order. It does not include the special
3903entries '.' and '..' even if they are present in the directory.
3904
3905
3906[clinic start generated code]*/
3907
Larry Hastings2f936352014-08-05 14:04:04 +10003908static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003909os_listdir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +00003910/*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003911{
Steve Dower60419a72019-06-24 08:42:54 -07003912 if (PySys_Audit("os.listdir", "O",
3913 path->object ? path->object : Py_None) < 0) {
3914 return NULL;
3915 }
Larry Hastings2f936352014-08-05 14:04:04 +10003916#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
3917 return _listdir_windows_no_opendir(path, NULL);
3918#else
3919 return _posix_listdir(path, NULL);
3920#endif
3921}
3922
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00003923#ifdef MS_WINDOWS
Mark Hammondef8b6542001-05-13 08:04:26 +00003924/* A helper function for abspath on win32 */
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003925/*[clinic input]
3926os._getfullpathname
Victor Stinnereb5657a2011-09-30 01:44:27 +02003927
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003928 path: path_t
3929 /
3930
3931[clinic start generated code]*/
3932
3933static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003934os__getfullpathname_impl(PyObject *module, path_t *path)
3935/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003936{
Victor Stinner3939c322019-06-25 15:02:43 +02003937 wchar_t *abspath;
Victor Stinnereb5657a2011-09-30 01:44:27 +02003938
Victor Stinner3939c322019-06-25 15:02:43 +02003939 /* _Py_abspath() is implemented with GetFullPathNameW() on Windows */
3940 if (_Py_abspath(path->wide, &abspath) < 0) {
3941 return win32_error_object("GetFullPathNameW", path->object);
Victor Stinner8c62be82010-05-06 00:08:46 +00003942 }
Victor Stinner3939c322019-06-25 15:02:43 +02003943 if (abspath == NULL) {
3944 return PyErr_NoMemory();
3945 }
3946
3947 PyObject *str = PyUnicode_FromWideChar(abspath, wcslen(abspath));
3948 PyMem_RawFree(abspath);
3949 if (str == NULL) {
3950 return NULL;
3951 }
3952 if (path->narrow) {
3953 Py_SETREF(str, PyUnicode_EncodeFSDefault(str));
3954 }
3955 return str;
Larry Hastings2f936352014-08-05 14:04:04 +10003956}
Brian Curtind40e6f72010-07-08 21:39:08 +00003957
Brian Curtind25aef52011-06-13 15:16:04 -05003958
Larry Hastings2f936352014-08-05 14:04:04 +10003959/*[clinic input]
3960os._getfinalpathname
Brian Curtinf5e76d02010-11-24 13:14:05 +00003961
Steve Dower23ad6d02018-02-22 10:39:10 -08003962 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10003963 /
3964
3965A helper function for samepath on windows.
3966[clinic start generated code]*/
3967
Larry Hastings2f936352014-08-05 14:04:04 +10003968static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08003969os__getfinalpathname_impl(PyObject *module, path_t *path)
3970/*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
Brian Curtind40e6f72010-07-08 21:39:08 +00003971{
3972 HANDLE hFile;
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003973 wchar_t buf[MAXPATHLEN], *target_path = buf;
3974 int buf_size = Py_ARRAY_LENGTH(buf);
Brian Curtind40e6f72010-07-08 21:39:08 +00003975 int result_length;
Larry Hastings2f936352014-08-05 14:04:04 +10003976 PyObject *result;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003977
Steve Dower23ad6d02018-02-22 10:39:10 -08003978 Py_BEGIN_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00003979 hFile = CreateFileW(
Steve Dower23ad6d02018-02-22 10:39:10 -08003980 path->wide,
Brian Curtind40e6f72010-07-08 21:39:08 +00003981 0, /* desired access */
3982 0, /* share mode */
3983 NULL, /* security attributes */
3984 OPEN_EXISTING,
3985 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
3986 FILE_FLAG_BACKUP_SEMANTICS,
3987 NULL);
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003988 Py_END_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003989
Steve Dower23ad6d02018-02-22 10:39:10 -08003990 if (hFile == INVALID_HANDLE_VALUE) {
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003991 return win32_error_object("CreateFileW", path->object);
Steve Dower23ad6d02018-02-22 10:39:10 -08003992 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003993
3994 /* We have a good handle to the target, use it to determine the
3995 target path name. */
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003996 while (1) {
3997 Py_BEGIN_ALLOW_THREADS
3998 result_length = GetFinalPathNameByHandleW(hFile, target_path,
3999 buf_size, VOLUME_NAME_DOS);
4000 Py_END_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00004001
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004002 if (!result_length) {
4003 result = win32_error_object("GetFinalPathNameByHandleW",
4004 path->object);
4005 goto cleanup;
4006 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004007
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004008 if (result_length < buf_size) {
4009 break;
4010 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004011
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004012 wchar_t *tmp;
4013 tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
4014 result_length * sizeof(*tmp));
4015 if (!tmp) {
4016 result = PyErr_NoMemory();
4017 goto cleanup;
4018 }
4019
4020 buf_size = result_length;
4021 target_path = tmp;
Steve Dower23ad6d02018-02-22 10:39:10 -08004022 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004023
Victor Stinner9d3b93b2011-11-22 02:27:30 +01004024 result = PyUnicode_FromWideChar(target_path, result_length);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004025 if (result && path->narrow) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004026 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004027 }
Steve Dower23ad6d02018-02-22 10:39:10 -08004028
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004029cleanup:
4030 if (target_path != buf) {
4031 PyMem_Free(target_path);
4032 }
4033 CloseHandle(hFile);
4034 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10004035}
Brian Curtin62857742010-09-06 17:07:27 +00004036
Tim Golden6b528062013-08-01 12:44:00 +01004037
Larry Hastings2f936352014-08-05 14:04:04 +10004038/*[clinic input]
4039os._getvolumepathname
4040
Steve Dower23ad6d02018-02-22 10:39:10 -08004041 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10004042
4043A helper function for ismount on Win32.
4044[clinic start generated code]*/
4045
Larry Hastings2f936352014-08-05 14:04:04 +10004046static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08004047os__getvolumepathname_impl(PyObject *module, path_t *path)
4048/*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004049{
4050 PyObject *result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004051 wchar_t *mountpath=NULL;
Victor Stinner6edddfa2013-11-24 19:22:57 +01004052 size_t buflen;
Tim Golden6b528062013-08-01 12:44:00 +01004053 BOOL ret;
4054
Tim Golden6b528062013-08-01 12:44:00 +01004055 /* Volume path should be shorter than entire path */
Steve Dower23ad6d02018-02-22 10:39:10 -08004056 buflen = Py_MAX(path->length, MAX_PATH);
Victor Stinner6edddfa2013-11-24 19:22:57 +01004057
Victor Stinner850a18e2017-10-24 16:53:32 -07004058 if (buflen > PY_DWORD_MAX) {
Victor Stinner6edddfa2013-11-24 19:22:57 +01004059 PyErr_SetString(PyExc_OverflowError, "path too long");
4060 return NULL;
4061 }
4062
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004063 mountpath = PyMem_New(wchar_t, buflen);
Tim Golden6b528062013-08-01 12:44:00 +01004064 if (mountpath == NULL)
4065 return PyErr_NoMemory();
4066
4067 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -08004068 ret = GetVolumePathNameW(path->wide, mountpath,
Victor Stinner6edddfa2013-11-24 19:22:57 +01004069 Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
Tim Golden6b528062013-08-01 12:44:00 +01004070 Py_END_ALLOW_THREADS
4071
4072 if (!ret) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004073 result = win32_error_object("_getvolumepathname", path->object);
Tim Golden6b528062013-08-01 12:44:00 +01004074 goto exit;
4075 }
4076 result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
Steve Dower23ad6d02018-02-22 10:39:10 -08004077 if (path->narrow)
4078 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Tim Golden6b528062013-08-01 12:44:00 +01004079
4080exit:
4081 PyMem_Free(mountpath);
4082 return result;
4083}
Tim Golden6b528062013-08-01 12:44:00 +01004084
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004085#endif /* MS_WINDOWS */
Mark Hammondef8b6542001-05-13 08:04:26 +00004086
Larry Hastings2f936352014-08-05 14:04:04 +10004087
4088/*[clinic input]
4089os.mkdir
4090
4091 path : path_t
4092
4093 mode: int = 0o777
4094
4095 *
4096
4097 dir_fd : dir_fd(requires='mkdirat') = None
4098
4099# "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
4100
4101Create a directory.
4102
4103If dir_fd is not None, it should be a file descriptor open to a directory,
4104 and path should be relative; path will then be relative to that directory.
4105dir_fd may not be implemented on your platform.
4106 If it is unavailable, using it will raise a NotImplementedError.
4107
4108The mode argument is ignored on Windows.
4109[clinic start generated code]*/
4110
Larry Hastings2f936352014-08-05 14:04:04 +10004111static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004112os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
4113/*[clinic end generated code: output=a70446903abe821f input=e965f68377e9b1ce]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004114{
4115 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004116
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004117#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004118 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004119 result = CreateDirectoryW(path->wide, NULL);
Victor Stinner8c62be82010-05-06 00:08:46 +00004120 Py_END_ALLOW_THREADS
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004121
Larry Hastings2f936352014-08-05 14:04:04 +10004122 if (!result)
4123 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004124#else
Victor Stinner8c62be82010-05-06 00:08:46 +00004125 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004126#if HAVE_MKDIRAT
4127 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004128 result = mkdirat(dir_fd, path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004129 else
4130#endif
Erik Bray03eb11f2017-10-27 14:27:06 +02004131#if defined(__WATCOMC__) && !defined(__QNX__)
Larry Hastings2f936352014-08-05 14:04:04 +10004132 result = mkdir(path->narrow);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004133#else
Larry Hastings2f936352014-08-05 14:04:04 +10004134 result = mkdir(path->narrow, mode);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004135#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004136 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004137 if (result < 0)
4138 return path_error(path);
Steve Dowercc16be82016-09-08 10:35:16 -07004139#endif /* MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10004140 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004141}
4142
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004143
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004144/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
4145#if defined(HAVE_SYS_RESOURCE_H)
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004146#include <sys/resource.h>
4147#endif
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004148
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004149
4150#ifdef HAVE_NICE
Larry Hastings2f936352014-08-05 14:04:04 +10004151/*[clinic input]
4152os.nice
4153
4154 increment: int
4155 /
4156
4157Add increment to the priority of process and return the new priority.
4158[clinic start generated code]*/
4159
Larry Hastings2f936352014-08-05 14:04:04 +10004160static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004161os_nice_impl(PyObject *module, int increment)
4162/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004163{
4164 int value;
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004165
Victor Stinner8c62be82010-05-06 00:08:46 +00004166 /* There are two flavours of 'nice': one that returns the new
4167 priority (as required by almost all standards out there) and the
Benjamin Peterson288d1da2017-09-28 22:44:27 -07004168 Linux/FreeBSD one, which returns '0' on success and advices
Victor Stinner8c62be82010-05-06 00:08:46 +00004169 the use of getpriority() to get the new priority.
Tim Peters5aa91602002-01-30 05:46:57 +00004170
Victor Stinner8c62be82010-05-06 00:08:46 +00004171 If we are of the nice family that returns the new priority, we
4172 need to clear errno before the call, and check if errno is filled
4173 before calling posix_error() on a returnvalue of -1, because the
4174 -1 may be the actual new priority! */
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004175
Victor Stinner8c62be82010-05-06 00:08:46 +00004176 errno = 0;
4177 value = nice(increment);
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004178#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
Victor Stinner8c62be82010-05-06 00:08:46 +00004179 if (value == 0)
4180 value = getpriority(PRIO_PROCESS, 0);
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004181#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004182 if (value == -1 && errno != 0)
4183 /* either nice() or getpriority() returned an error */
4184 return posix_error();
4185 return PyLong_FromLong((long) value);
Guido van Rossum775f4da1993-01-09 17:18:52 +00004186}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004187#endif /* HAVE_NICE */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004188
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004189
4190#ifdef HAVE_GETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004191/*[clinic input]
4192os.getpriority
4193
4194 which: int
4195 who: int
4196
4197Return program scheduling priority.
4198[clinic start generated code]*/
4199
Larry Hastings2f936352014-08-05 14:04:04 +10004200static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004201os_getpriority_impl(PyObject *module, int which, int who)
4202/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004203{
4204 int retval;
4205
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004206 errno = 0;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004207 retval = getpriority(which, who);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004208 if (errno != 0)
4209 return posix_error();
4210 return PyLong_FromLong((long)retval);
4211}
4212#endif /* HAVE_GETPRIORITY */
4213
4214
4215#ifdef HAVE_SETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004216/*[clinic input]
4217os.setpriority
4218
4219 which: int
4220 who: int
4221 priority: int
4222
4223Set program scheduling priority.
4224[clinic start generated code]*/
4225
Larry Hastings2f936352014-08-05 14:04:04 +10004226static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004227os_setpriority_impl(PyObject *module, int which, int who, int priority)
4228/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004229{
4230 int retval;
4231
4232 retval = setpriority(which, who, priority);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004233 if (retval == -1)
4234 return posix_error();
4235 Py_RETURN_NONE;
4236}
4237#endif /* HAVE_SETPRIORITY */
4238
4239
Barry Warsaw53699e91996-12-10 23:23:01 +00004240static PyObject *
Larry Hastings2f936352014-08-05 14:04:04 +10004241internal_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 +00004242{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004243 const char *function_name = is_replace ? "replace" : "rename";
Larry Hastings9cf065c2012-06-22 16:30:09 -07004244 int dir_fd_specified;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004245
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004246#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004247 BOOL result;
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004248 int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004249#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004250 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004251#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004252
Larry Hastings9cf065c2012-06-22 16:30:09 -07004253 dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
4254 (dst_dir_fd != DEFAULT_DIR_FD);
4255#ifndef HAVE_RENAMEAT
4256 if (dir_fd_specified) {
4257 argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10004258 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004259 }
4260#endif
4261
Larry Hastings9cf065c2012-06-22 16:30:09 -07004262#ifdef MS_WINDOWS
4263 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004264 result = MoveFileExW(src->wide, dst->wide, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004265 Py_END_ALLOW_THREADS
4266
Larry Hastings2f936352014-08-05 14:04:04 +10004267 if (!result)
4268 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004269
4270#else
Steve Dowercc16be82016-09-08 10:35:16 -07004271 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
4272 PyErr_Format(PyExc_ValueError,
4273 "%s: src and dst must be the same type", function_name);
4274 return NULL;
4275 }
4276
Larry Hastings9cf065c2012-06-22 16:30:09 -07004277 Py_BEGIN_ALLOW_THREADS
4278#ifdef HAVE_RENAMEAT
4279 if (dir_fd_specified)
Larry Hastings2f936352014-08-05 14:04:04 +10004280 result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004281 else
4282#endif
Steve Dowercc16be82016-09-08 10:35:16 -07004283 result = rename(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004284 Py_END_ALLOW_THREADS
4285
Larry Hastings2f936352014-08-05 14:04:04 +10004286 if (result)
4287 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004288#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004289 Py_RETURN_NONE;
4290}
Larry Hastings9cf065c2012-06-22 16:30:09 -07004291
Larry Hastings2f936352014-08-05 14:04:04 +10004292
4293/*[clinic input]
4294os.rename
4295
4296 src : path_t
4297 dst : path_t
4298 *
4299 src_dir_fd : dir_fd = None
4300 dst_dir_fd : dir_fd = None
4301
4302Rename a file or directory.
4303
4304If either src_dir_fd or dst_dir_fd is not None, it should be a file
4305 descriptor open to a directory, and the respective path string (src or dst)
4306 should be relative; the path will then be relative to that directory.
4307src_dir_fd and dst_dir_fd, may not be implemented on your platform.
4308 If they are unavailable, using them will raise a NotImplementedError.
4309[clinic start generated code]*/
4310
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004311static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004312os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04004313 int dst_dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004314/*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004315{
Larry Hastings2f936352014-08-05 14:04:04 +10004316 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004317}
4318
Larry Hastings2f936352014-08-05 14:04:04 +10004319
4320/*[clinic input]
4321os.replace = os.rename
4322
4323Rename a file or directory, overwriting the destination.
4324
4325If either src_dir_fd or dst_dir_fd is not None, it should be a file
4326 descriptor open to a directory, and the respective path string (src or dst)
4327 should be relative; the path will then be relative to that directory.
4328src_dir_fd and dst_dir_fd, may not be implemented on your platform.
Anthony Sottile73d60022019-02-12 23:15:54 -05004329 If they are unavailable, using them will raise a NotImplementedError.
Larry Hastings2f936352014-08-05 14:04:04 +10004330[clinic start generated code]*/
4331
Larry Hastings2f936352014-08-05 14:04:04 +10004332static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004333os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
4334 int dst_dir_fd)
Anthony Sottile73d60022019-02-12 23:15:54 -05004335/*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004336{
4337 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
4338}
4339
4340
4341/*[clinic input]
4342os.rmdir
4343
4344 path: path_t
4345 *
4346 dir_fd: dir_fd(requires='unlinkat') = None
4347
4348Remove a directory.
4349
4350If dir_fd is not None, it should be a file descriptor open to a directory,
4351 and path should be relative; path will then be relative to that directory.
4352dir_fd may not be implemented on your platform.
4353 If it is unavailable, using it will raise a NotImplementedError.
4354[clinic start generated code]*/
4355
Larry Hastings2f936352014-08-05 14:04:04 +10004356static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004357os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
4358/*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004359{
4360 int result;
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004361
4362 Py_BEGIN_ALLOW_THREADS
4363#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004364 /* Windows, success=1, UNIX, success=0 */
4365 result = !RemoveDirectoryW(path->wide);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004366#else
4367#ifdef HAVE_UNLINKAT
4368 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004369 result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004370 else
4371#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004372 result = rmdir(path->narrow);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004373#endif
4374 Py_END_ALLOW_THREADS
4375
Larry Hastings2f936352014-08-05 14:04:04 +10004376 if (result)
4377 return path_error(path);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004378
Larry Hastings2f936352014-08-05 14:04:04 +10004379 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004380}
4381
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004382
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004383#ifdef HAVE_SYSTEM
Larry Hastings2f936352014-08-05 14:04:04 +10004384#ifdef MS_WINDOWS
4385/*[clinic input]
4386os.system -> long
4387
4388 command: Py_UNICODE
4389
4390Execute the command in a subshell.
4391[clinic start generated code]*/
4392
Larry Hastings2f936352014-08-05 14:04:04 +10004393static long
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02004394os_system_impl(PyObject *module, const Py_UNICODE *command)
4395/*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004396{
4397 long result;
Steve Dowerb82e17e2019-05-23 08:45:22 -07004398
Steve Dowerfbe3c762019-10-18 00:52:15 -07004399 if (PySys_Audit("os.system", "(u)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004400 return -1;
4401 }
4402
Victor Stinner8c62be82010-05-06 00:08:46 +00004403 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08004404 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10004405 result = _wsystem(command);
Steve Dowerc3630612016-11-19 18:41:16 -08004406 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00004407 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004408 return result;
4409}
4410#else /* MS_WINDOWS */
4411/*[clinic input]
4412os.system -> long
4413
4414 command: FSConverter
4415
4416Execute the command in a subshell.
4417[clinic start generated code]*/
4418
Larry Hastings2f936352014-08-05 14:04:04 +10004419static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004420os_system_impl(PyObject *module, PyObject *command)
4421/*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004422{
4423 long result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004424 const char *bytes = PyBytes_AsString(command);
Steve Dowerb82e17e2019-05-23 08:45:22 -07004425
Steve Dowerfbe3c762019-10-18 00:52:15 -07004426 if (PySys_Audit("os.system", "(O)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004427 return -1;
4428 }
4429
Larry Hastings2f936352014-08-05 14:04:04 +10004430 Py_BEGIN_ALLOW_THREADS
4431 result = system(bytes);
4432 Py_END_ALLOW_THREADS
4433 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004434}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004435#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004436#endif /* HAVE_SYSTEM */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004437
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004438
Larry Hastings2f936352014-08-05 14:04:04 +10004439/*[clinic input]
4440os.umask
4441
4442 mask: int
4443 /
4444
4445Set the current numeric umask and return the previous umask.
4446[clinic start generated code]*/
4447
Larry Hastings2f936352014-08-05 14:04:04 +10004448static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004449os_umask_impl(PyObject *module, int mask)
4450/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004451{
4452 int i = (int)umask(mask);
Victor Stinner8c62be82010-05-06 00:08:46 +00004453 if (i < 0)
4454 return posix_error();
4455 return PyLong_FromLong((long)i);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004456}
4457
Brian Curtind40e6f72010-07-08 21:39:08 +00004458#ifdef MS_WINDOWS
4459
4460/* override the default DeleteFileW behavior so that directory
4461symlinks can be removed with this function, the same as with
4462Unix symlinks */
4463BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
4464{
4465 WIN32_FILE_ATTRIBUTE_DATA info;
4466 WIN32_FIND_DATAW find_data;
4467 HANDLE find_data_handle;
4468 int is_directory = 0;
4469 int is_link = 0;
4470
4471 if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
4472 is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004473
Brian Curtind40e6f72010-07-08 21:39:08 +00004474 /* Get WIN32_FIND_DATA structure for the path to determine if
4475 it is a symlink */
4476 if(is_directory &&
4477 info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
4478 find_data_handle = FindFirstFileW(lpFileName, &find_data);
4479
4480 if(find_data_handle != INVALID_HANDLE_VALUE) {
Tim Golden0321cf22014-05-05 19:46:17 +01004481 /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
4482 IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
4483 is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
4484 find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
Brian Curtind40e6f72010-07-08 21:39:08 +00004485 FindClose(find_data_handle);
4486 }
4487 }
4488 }
4489
4490 if (is_directory && is_link)
4491 return RemoveDirectoryW(lpFileName);
4492
4493 return DeleteFileW(lpFileName);
4494}
4495#endif /* MS_WINDOWS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004496
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004497
Larry Hastings2f936352014-08-05 14:04:04 +10004498/*[clinic input]
4499os.unlink
4500
4501 path: path_t
4502 *
4503 dir_fd: dir_fd(requires='unlinkat')=None
4504
4505Remove a file (same as remove()).
4506
4507If dir_fd is not None, it should be a file descriptor open to a directory,
4508 and path should be relative; path will then be relative to that directory.
4509dir_fd may not be implemented on your platform.
4510 If it is unavailable, using it will raise a NotImplementedError.
4511
4512[clinic start generated code]*/
4513
Larry Hastings2f936352014-08-05 14:04:04 +10004514static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004515os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
4516/*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004517{
4518 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004519
4520 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04004521 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004522#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004523 /* Windows, success=1, UNIX, success=0 */
4524 result = !Py_DeleteFileW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004525#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004526#ifdef HAVE_UNLINKAT
4527 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004528 result = unlinkat(dir_fd, path->narrow, 0);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004529 else
4530#endif /* HAVE_UNLINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10004531 result = unlink(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004532#endif
Steve Dower8fc89802015-04-12 00:26:27 -04004533 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004534 Py_END_ALLOW_THREADS
4535
Larry Hastings2f936352014-08-05 14:04:04 +10004536 if (result)
4537 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004538
Larry Hastings2f936352014-08-05 14:04:04 +10004539 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004540}
4541
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004542
Larry Hastings2f936352014-08-05 14:04:04 +10004543/*[clinic input]
4544os.remove = os.unlink
4545
4546Remove a file (same as unlink()).
4547
4548If dir_fd is not None, it should be a file descriptor open to a directory,
4549 and path should be relative; path will then be relative to that directory.
4550dir_fd may not be implemented on your platform.
4551 If it is unavailable, using it will raise a NotImplementedError.
4552[clinic start generated code]*/
4553
Larry Hastings2f936352014-08-05 14:04:04 +10004554static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004555os_remove_impl(PyObject *module, path_t *path, int dir_fd)
4556/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004557{
4558 return os_unlink_impl(module, path, dir_fd);
4559}
4560
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004561
Larry Hastings605a62d2012-06-24 04:33:36 -07004562static PyStructSequence_Field uname_result_fields[] = {
4563 {"sysname", "operating system name"},
4564 {"nodename", "name of machine on network (implementation-defined)"},
4565 {"release", "operating system release"},
4566 {"version", "operating system version"},
4567 {"machine", "hardware identifier"},
4568 {NULL}
4569};
4570
4571PyDoc_STRVAR(uname_result__doc__,
4572"uname_result: Result from os.uname().\n\n\
4573This object may be accessed either as a tuple of\n\
4574 (sysname, nodename, release, version, machine),\n\
4575or via the attributes sysname, nodename, release, version, and machine.\n\
4576\n\
4577See os.uname for more information.");
4578
4579static PyStructSequence_Desc uname_result_desc = {
Eddie Elizondob3966632019-11-05 07:16:14 -08004580 MODNAME ".uname_result", /* name */
Larry Hastings605a62d2012-06-24 04:33:36 -07004581 uname_result__doc__, /* doc */
4582 uname_result_fields,
4583 5
4584};
4585
Larry Hastings605a62d2012-06-24 04:33:36 -07004586#ifdef HAVE_UNAME
Larry Hastings2f936352014-08-05 14:04:04 +10004587/*[clinic input]
4588os.uname
4589
4590Return an object identifying the current operating system.
4591
4592The object behaves like a named tuple with the following fields:
4593 (sysname, nodename, release, version, machine)
4594
4595[clinic start generated code]*/
4596
Larry Hastings2f936352014-08-05 14:04:04 +10004597static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004598os_uname_impl(PyObject *module)
4599/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004600{
Victor Stinner8c62be82010-05-06 00:08:46 +00004601 struct utsname u;
4602 int res;
Larry Hastings605a62d2012-06-24 04:33:36 -07004603 PyObject *value;
Neal Norwitze241ce82003-02-17 18:17:05 +00004604
Victor Stinner8c62be82010-05-06 00:08:46 +00004605 Py_BEGIN_ALLOW_THREADS
4606 res = uname(&u);
4607 Py_END_ALLOW_THREADS
4608 if (res < 0)
4609 return posix_error();
Larry Hastings605a62d2012-06-24 04:33:36 -07004610
Eddie Elizondob3966632019-11-05 07:16:14 -08004611 PyObject *UnameResultType = _posixstate(module)->UnameResultType;
4612 value = PyStructSequence_New((PyTypeObject *)UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07004613 if (value == NULL)
4614 return NULL;
4615
4616#define SET(i, field) \
4617 { \
Victor Stinnera534fc42013-06-03 22:07:27 +02004618 PyObject *o = PyUnicode_DecodeFSDefault(field); \
Larry Hastings605a62d2012-06-24 04:33:36 -07004619 if (!o) { \
4620 Py_DECREF(value); \
4621 return NULL; \
4622 } \
4623 PyStructSequence_SET_ITEM(value, i, o); \
4624 } \
4625
4626 SET(0, u.sysname);
4627 SET(1, u.nodename);
4628 SET(2, u.release);
4629 SET(3, u.version);
4630 SET(4, u.machine);
4631
4632#undef SET
4633
4634 return value;
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004635}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004636#endif /* HAVE_UNAME */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004637
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004638
Larry Hastings9cf065c2012-06-22 16:30:09 -07004639
4640typedef struct {
4641 int now;
4642 time_t atime_s;
4643 long atime_ns;
4644 time_t mtime_s;
4645 long mtime_ns;
4646} utime_t;
4647
4648/*
Victor Stinner484df002014-10-09 13:52:31 +02004649 * these macros assume that "ut" is a pointer to a utime_t
Larry Hastings9cf065c2012-06-22 16:30:09 -07004650 * they also intentionally leak the declaration of a pointer named "time"
4651 */
4652#define UTIME_TO_TIMESPEC \
4653 struct timespec ts[2]; \
4654 struct timespec *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004655 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004656 time = NULL; \
4657 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004658 ts[0].tv_sec = ut->atime_s; \
4659 ts[0].tv_nsec = ut->atime_ns; \
4660 ts[1].tv_sec = ut->mtime_s; \
4661 ts[1].tv_nsec = ut->mtime_ns; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004662 time = ts; \
4663 } \
4664
4665#define UTIME_TO_TIMEVAL \
4666 struct timeval tv[2]; \
4667 struct timeval *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004668 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004669 time = NULL; \
4670 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004671 tv[0].tv_sec = ut->atime_s; \
4672 tv[0].tv_usec = ut->atime_ns / 1000; \
4673 tv[1].tv_sec = ut->mtime_s; \
4674 tv[1].tv_usec = ut->mtime_ns / 1000; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004675 time = tv; \
4676 } \
4677
4678#define UTIME_TO_UTIMBUF \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004679 struct utimbuf u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004680 struct utimbuf *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004681 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004682 time = NULL; \
4683 else { \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004684 u.actime = ut->atime_s; \
4685 u.modtime = ut->mtime_s; \
4686 time = &u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004687 }
4688
4689#define UTIME_TO_TIME_T \
4690 time_t timet[2]; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004691 time_t *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004692 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004693 time = NULL; \
4694 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004695 timet[0] = ut->atime_s; \
4696 timet[1] = ut->mtime_s; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004697 time = timet; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004698 } \
4699
4700
Victor Stinner528a9ab2015-09-03 21:30:26 +02004701#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004702
4703static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004704utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004705{
4706#ifdef HAVE_UTIMENSAT
4707 int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
4708 UTIME_TO_TIMESPEC;
4709 return utimensat(dir_fd, path, time, flags);
4710#elif defined(HAVE_FUTIMESAT)
4711 UTIME_TO_TIMEVAL;
4712 /*
4713 * follow_symlinks will never be false here;
4714 * we only allow !follow_symlinks and dir_fd together
4715 * if we have utimensat()
4716 */
4717 assert(follow_symlinks);
4718 return futimesat(dir_fd, path, time);
4719#endif
4720}
4721
Larry Hastings2f936352014-08-05 14:04:04 +10004722 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
4723#else
4724 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings9cf065c2012-06-22 16:30:09 -07004725#endif
4726
Victor Stinner528a9ab2015-09-03 21:30:26 +02004727#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004728
4729static int
Victor Stinner484df002014-10-09 13:52:31 +02004730utime_fd(utime_t *ut, int fd)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004731{
4732#ifdef HAVE_FUTIMENS
4733 UTIME_TO_TIMESPEC;
4734 return futimens(fd, time);
4735#else
4736 UTIME_TO_TIMEVAL;
4737 return futimes(fd, time);
4738#endif
4739}
4740
Larry Hastings2f936352014-08-05 14:04:04 +10004741 #define PATH_UTIME_HAVE_FD 1
4742#else
4743 #define PATH_UTIME_HAVE_FD 0
Larry Hastings9cf065c2012-06-22 16:30:09 -07004744#endif
4745
Victor Stinner5ebae872015-09-22 01:29:33 +02004746#if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
4747# define UTIME_HAVE_NOFOLLOW_SYMLINKS
4748#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004749
Victor Stinner4552ced2015-09-21 22:37:15 +02004750#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004751
4752static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004753utime_nofollow_symlinks(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004754{
4755#ifdef HAVE_UTIMENSAT
4756 UTIME_TO_TIMESPEC;
4757 return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
4758#else
4759 UTIME_TO_TIMEVAL;
4760 return lutimes(path, time);
4761#endif
4762}
4763
4764#endif
4765
4766#ifndef MS_WINDOWS
4767
4768static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004769utime_default(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004770{
4771#ifdef HAVE_UTIMENSAT
4772 UTIME_TO_TIMESPEC;
4773 return utimensat(DEFAULT_DIR_FD, path, time, 0);
4774#elif defined(HAVE_UTIMES)
4775 UTIME_TO_TIMEVAL;
4776 return utimes(path, time);
4777#elif defined(HAVE_UTIME_H)
4778 UTIME_TO_UTIMBUF;
4779 return utime(path, time);
4780#else
4781 UTIME_TO_TIME_T;
4782 return utime(path, time);
4783#endif
4784}
4785
4786#endif
4787
Larry Hastings76ad59b2012-05-03 00:30:07 -07004788static int
4789split_py_long_to_s_and_ns(PyObject *py_long, time_t *s, long *ns)
4790{
4791 int result = 0;
Benjamin Petersonfbd85a02012-05-04 11:06:09 -04004792 PyObject *divmod;
Eddie Elizondob3966632019-11-05 07:16:14 -08004793 divmod = PyNumber_Divmod(py_long, _posixstate_global->billion);
Larry Hastings76ad59b2012-05-03 00:30:07 -07004794 if (!divmod)
4795 goto exit;
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004796 if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
4797 PyErr_Format(PyExc_TypeError,
4798 "%.200s.__divmod__() must return a 2-tuple, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -08004799 _PyType_Name(Py_TYPE(py_long)), _PyType_Name(Py_TYPE(divmod)));
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004800 goto exit;
4801 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004802 *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
4803 if ((*s == -1) && PyErr_Occurred())
4804 goto exit;
4805 *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
Benjamin Peterson35a8f0d2012-05-04 01:10:59 -04004806 if ((*ns == -1) && PyErr_Occurred())
Larry Hastings76ad59b2012-05-03 00:30:07 -07004807 goto exit;
4808
4809 result = 1;
4810exit:
4811 Py_XDECREF(divmod);
4812 return result;
4813}
4814
Larry Hastings2f936352014-08-05 14:04:04 +10004815
4816/*[clinic input]
4817os.utime
4818
4819 path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004820 times: object = None
Larry Hastings2f936352014-08-05 14:04:04 +10004821 *
4822 ns: object = NULL
4823 dir_fd: dir_fd(requires='futimensat') = None
4824 follow_symlinks: bool=True
4825
Martin Panter0ff89092015-09-09 01:56:53 +00004826# "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
Larry Hastings2f936352014-08-05 14:04:04 +10004827
4828Set the access and modified time of path.
4829
4830path may always be specified as a string.
4831On some platforms, path may also be specified as an open file descriptor.
4832 If this functionality is unavailable, using it raises an exception.
4833
4834If times is not None, it must be a tuple (atime, mtime);
4835 atime and mtime should be expressed as float seconds since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004836If ns is specified, it must be a tuple (atime_ns, mtime_ns);
Larry Hastings2f936352014-08-05 14:04:04 +10004837 atime_ns and mtime_ns should be expressed as integer nanoseconds
4838 since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004839If times is None and ns is unspecified, utime uses the current time.
Larry Hastings2f936352014-08-05 14:04:04 +10004840Specifying tuples for both times and ns is an error.
4841
4842If dir_fd is not None, it should be a file descriptor open to a directory,
4843 and path should be relative; path will then be relative to that directory.
4844If follow_symlinks is False, and the last element of the path is a symbolic
4845 link, utime will modify the symbolic link itself instead of the file the
4846 link points to.
4847It is an error to use dir_fd or follow_symlinks when specifying path
4848 as an open file descriptor.
4849dir_fd and follow_symlinks may not be available on your platform.
4850 If they are unavailable, using them will raise a NotImplementedError.
4851
4852[clinic start generated code]*/
4853
Larry Hastings2f936352014-08-05 14:04:04 +10004854static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004855os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
4856 int dir_fd, int follow_symlinks)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004857/*[clinic end generated code: output=cfcac69d027b82cf input=2fbd62a2f228f8f4]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004858{
Larry Hastings9cf065c2012-06-22 16:30:09 -07004859#ifdef MS_WINDOWS
4860 HANDLE hFile;
4861 FILETIME atime, mtime;
4862#else
4863 int result;
4864#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004865
Larry Hastings2f936352014-08-05 14:04:04 +10004866 utime_t utime;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004867
Christian Heimesb3c87242013-08-01 00:08:16 +02004868 memset(&utime, 0, sizeof(utime_t));
Larry Hastings76ad59b2012-05-03 00:30:07 -07004869
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004870 if (times != Py_None && ns) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004871 PyErr_SetString(PyExc_ValueError,
4872 "utime: you may specify either 'times'"
4873 " or 'ns' but not both");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004874 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004875 }
4876
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004877 if (times != Py_None) {
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004878 time_t a_sec, m_sec;
4879 long a_nsec, m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004880 if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004881 PyErr_SetString(PyExc_TypeError,
4882 "utime: 'times' must be either"
4883 " a tuple of two ints or None");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004884 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004885 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004886 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004887 if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004888 &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004889 _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004890 &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004891 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004892 }
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004893 utime.atime_s = a_sec;
4894 utime.atime_ns = a_nsec;
4895 utime.mtime_s = m_sec;
4896 utime.mtime_ns = m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004897 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004898 else if (ns) {
Larry Hastings76ad59b2012-05-03 00:30:07 -07004899 if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004900 PyErr_SetString(PyExc_TypeError,
4901 "utime: 'ns' must be a tuple of two ints");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004902 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004903 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004904 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004905 if (!split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 0),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004906 &utime.atime_s, &utime.atime_ns) ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004907 !split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 1),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004908 &utime.mtime_s, &utime.mtime_ns)) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004909 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004910 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004911 }
4912 else {
4913 /* times and ns are both None/unspecified. use "now". */
4914 utime.now = 1;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004915 }
4916
Victor Stinner4552ced2015-09-21 22:37:15 +02004917#if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004918 if (follow_symlinks_specified("utime", follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004919 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004920#endif
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004921
Larry Hastings2f936352014-08-05 14:04:04 +10004922 if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
4923 dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
4924 fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004925 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004926
Larry Hastings9cf065c2012-06-22 16:30:09 -07004927#if !defined(HAVE_UTIMENSAT)
4928 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
Georg Brandl969288e2012-06-26 09:25:44 +02004929 PyErr_SetString(PyExc_ValueError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07004930 "utime: cannot use dir_fd and follow_symlinks "
4931 "together on this platform");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004932 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004933 }
4934#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004935
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004936#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004937 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004938 hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
4939 NULL, OPEN_EXISTING,
4940 FILE_FLAG_BACKUP_SEMANTICS, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004941 Py_END_ALLOW_THREADS
4942 if (hFile == INVALID_HANDLE_VALUE) {
Larry Hastings2f936352014-08-05 14:04:04 +10004943 path_error(path);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004944 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004945 }
4946
Larry Hastings9cf065c2012-06-22 16:30:09 -07004947 if (utime.now) {
Antoine Pitrou91a7af32013-11-23 15:23:26 +01004948 GetSystemTimeAsFileTime(&mtime);
4949 atime = mtime;
Victor Stinner8c62be82010-05-06 00:08:46 +00004950 }
Victor Stinner8c62be82010-05-06 00:08:46 +00004951 else {
Steve Dowerbf1f3762015-02-21 15:26:02 -08004952 _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
4953 _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
Victor Stinner8c62be82010-05-06 00:08:46 +00004954 }
4955 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
4956 /* Avoid putting the file name into the error here,
4957 as that may confuse the user into believing that
4958 something is wrong with the file, when it also
4959 could be the time stamp that gives a problem. */
Victor Stinnerb024e842012-10-31 22:24:06 +01004960 PyErr_SetFromWindowsErr(0);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004961 CloseHandle(hFile);
4962 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004963 }
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004964 CloseHandle(hFile);
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004965#else /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07004966 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004967
Victor Stinner4552ced2015-09-21 22:37:15 +02004968#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004969 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10004970 result = utime_nofollow_symlinks(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004971 else
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004972#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004973
Victor Stinner528a9ab2015-09-03 21:30:26 +02004974#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004975 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10004976 result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004977 else
4978#endif
4979
Victor Stinner528a9ab2015-09-03 21:30:26 +02004980#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings2f936352014-08-05 14:04:04 +10004981 if (path->fd != -1)
4982 result = utime_fd(&utime, path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004983 else
4984#endif
4985
Larry Hastings2f936352014-08-05 14:04:04 +10004986 result = utime_default(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004987
4988 Py_END_ALLOW_THREADS
4989
4990 if (result < 0) {
4991 /* see previous comment about not putting filename in error here */
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004992 posix_error();
4993 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004994 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004995
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004996#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07004997
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004998 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004999}
5000
Guido van Rossum3b066191991-06-04 19:40:25 +00005001/* Process operations */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005002
Larry Hastings2f936352014-08-05 14:04:04 +10005003
5004/*[clinic input]
5005os._exit
5006
5007 status: int
5008
5009Exit to the system with specified status, without normal exit processing.
5010[clinic start generated code]*/
5011
Larry Hastings2f936352014-08-05 14:04:04 +10005012static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005013os__exit_impl(PyObject *module, int status)
5014/*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005015{
5016 _exit(status);
Victor Stinner8c62be82010-05-06 00:08:46 +00005017 return NULL; /* Make gcc -Wall happy */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005018}
5019
Steve Dowercc16be82016-09-08 10:35:16 -07005020#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5021#define EXECV_CHAR wchar_t
5022#else
5023#define EXECV_CHAR char
5024#endif
5025
pxinwrf2d7ac72019-05-21 18:46:37 +08005026#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005027static void
Steve Dowercc16be82016-09-08 10:35:16 -07005028free_string_array(EXECV_CHAR **array, Py_ssize_t count)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005029{
Victor Stinner8c62be82010-05-06 00:08:46 +00005030 Py_ssize_t i;
5031 for (i = 0; i < count; i++)
5032 PyMem_Free(array[i]);
5033 PyMem_DEL(array);
Martin v. Löwis114619e2002-10-07 06:44:21 +00005034}
Martin v. Löwis011e8422009-05-05 04:43:17 +00005035
Berker Peksag81816462016-09-15 20:19:47 +03005036static int
5037fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
Martin v. Löwis011e8422009-05-05 04:43:17 +00005038{
Victor Stinner8c62be82010-05-06 00:08:46 +00005039 Py_ssize_t size;
Berker Peksag81816462016-09-15 20:19:47 +03005040 PyObject *ub;
5041 int result = 0;
Steve Dowercc16be82016-09-08 10:35:16 -07005042#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
Berker Peksag81816462016-09-15 20:19:47 +03005043 if (!PyUnicode_FSDecoder(o, &ub))
Steve Dowercc16be82016-09-08 10:35:16 -07005044 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005045 *out = PyUnicode_AsWideCharString(ub, &size);
5046 if (*out)
5047 result = 1;
Steve Dowercc16be82016-09-08 10:35:16 -07005048#else
Berker Peksag81816462016-09-15 20:19:47 +03005049 if (!PyUnicode_FSConverter(o, &ub))
Victor Stinner8c62be82010-05-06 00:08:46 +00005050 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005051 size = PyBytes_GET_SIZE(ub);
5052 *out = PyMem_Malloc(size + 1);
5053 if (*out) {
5054 memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
5055 result = 1;
5056 } else
Victor Stinner50abf222013-11-07 23:56:10 +01005057 PyErr_NoMemory();
Steve Dowercc16be82016-09-08 10:35:16 -07005058#endif
Berker Peksag81816462016-09-15 20:19:47 +03005059 Py_DECREF(ub);
5060 return result;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005061}
Martin v. Löwis114619e2002-10-07 06:44:21 +00005062#endif
5063
pxinwrf2d7ac72019-05-21 18:46:37 +08005064#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
Steve Dowercc16be82016-09-08 10:35:16 -07005065static EXECV_CHAR**
Victor Stinner13bb71c2010-04-23 21:41:56 +00005066parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
5067{
Victor Stinner8c62be82010-05-06 00:08:46 +00005068 Py_ssize_t i, pos, envc;
5069 PyObject *keys=NULL, *vals=NULL;
Berker Peksag81816462016-09-15 20:19:47 +03005070 PyObject *key, *val, *key2, *val2, *keyval;
Steve Dowercc16be82016-09-08 10:35:16 -07005071 EXECV_CHAR **envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005072
Victor Stinner8c62be82010-05-06 00:08:46 +00005073 i = PyMapping_Size(env);
5074 if (i < 0)
5075 return NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07005076 envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005077 if (envlist == NULL) {
5078 PyErr_NoMemory();
5079 return NULL;
5080 }
5081 envc = 0;
5082 keys = PyMapping_Keys(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005083 if (!keys)
5084 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00005085 vals = PyMapping_Values(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005086 if (!vals)
Victor Stinner8c62be82010-05-06 00:08:46 +00005087 goto error;
5088 if (!PyList_Check(keys) || !PyList_Check(vals)) {
5089 PyErr_Format(PyExc_TypeError,
5090 "env.keys() or env.values() is not a list");
5091 goto error;
5092 }
Victor Stinner13bb71c2010-04-23 21:41:56 +00005093
Victor Stinner8c62be82010-05-06 00:08:46 +00005094 for (pos = 0; pos < i; pos++) {
5095 key = PyList_GetItem(keys, pos);
5096 val = PyList_GetItem(vals, pos);
5097 if (!key || !val)
5098 goto error;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005099
Berker Peksag81816462016-09-15 20:19:47 +03005100#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5101 if (!PyUnicode_FSDecoder(key, &key2))
5102 goto error;
5103 if (!PyUnicode_FSDecoder(val, &val2)) {
5104 Py_DECREF(key2);
5105 goto error;
5106 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005107 /* Search from index 1 because on Windows starting '=' is allowed for
5108 defining hidden environment variables. */
5109 if (PyUnicode_GET_LENGTH(key2) == 0 ||
5110 PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
5111 {
5112 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005113 Py_DECREF(key2);
5114 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005115 goto error;
5116 }
Berker Peksag81816462016-09-15 20:19:47 +03005117 keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
5118#else
5119 if (!PyUnicode_FSConverter(key, &key2))
5120 goto error;
5121 if (!PyUnicode_FSConverter(val, &val2)) {
5122 Py_DECREF(key2);
5123 goto error;
5124 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005125 if (PyBytes_GET_SIZE(key2) == 0 ||
5126 strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
5127 {
5128 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005129 Py_DECREF(key2);
5130 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005131 goto error;
5132 }
Berker Peksag81816462016-09-15 20:19:47 +03005133 keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
5134 PyBytes_AS_STRING(val2));
5135#endif
5136 Py_DECREF(key2);
5137 Py_DECREF(val2);
Steve Dowercc16be82016-09-08 10:35:16 -07005138 if (!keyval)
Victor Stinner8c62be82010-05-06 00:08:46 +00005139 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -07005140
5141 if (!fsconvert_strdup(keyval, &envlist[envc++])) {
5142 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005143 goto error;
5144 }
Berker Peksag81816462016-09-15 20:19:47 +03005145
Steve Dowercc16be82016-09-08 10:35:16 -07005146 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005147 }
5148 Py_DECREF(vals);
5149 Py_DECREF(keys);
Victor Stinner13bb71c2010-04-23 21:41:56 +00005150
Victor Stinner8c62be82010-05-06 00:08:46 +00005151 envlist[envc] = 0;
5152 *envc_ptr = envc;
5153 return envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005154
5155error:
Victor Stinner8c62be82010-05-06 00:08:46 +00005156 Py_XDECREF(keys);
5157 Py_XDECREF(vals);
Steve Dowercc16be82016-09-08 10:35:16 -07005158 free_string_array(envlist, envc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005159 return NULL;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005160}
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005161
Steve Dowercc16be82016-09-08 10:35:16 -07005162static EXECV_CHAR**
Ross Lagerwall7807c352011-03-17 20:20:30 +02005163parse_arglist(PyObject* argv, Py_ssize_t *argc)
5164{
5165 int i;
Steve Dowercc16be82016-09-08 10:35:16 -07005166 EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005167 if (argvlist == NULL) {
5168 PyErr_NoMemory();
5169 return NULL;
5170 }
5171 for (i = 0; i < *argc; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005172 PyObject* item = PySequence_ITEM(argv, i);
5173 if (item == NULL)
5174 goto fail;
5175 if (!fsconvert_strdup(item, &argvlist[i])) {
5176 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005177 goto fail;
5178 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005179 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005180 }
5181 argvlist[*argc] = NULL;
5182 return argvlist;
5183fail:
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005184 *argc = i;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005185 free_string_array(argvlist, *argc);
5186 return NULL;
5187}
Steve Dowercc16be82016-09-08 10:35:16 -07005188
Ross Lagerwall7807c352011-03-17 20:20:30 +02005189#endif
5190
Larry Hastings2f936352014-08-05 14:04:04 +10005191
Ross Lagerwall7807c352011-03-17 20:20:30 +02005192#ifdef HAVE_EXECV
Larry Hastings2f936352014-08-05 14:04:04 +10005193/*[clinic input]
5194os.execv
5195
Steve Dowercc16be82016-09-08 10:35:16 -07005196 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005197 Path of executable file.
5198 argv: object
5199 Tuple or list of strings.
5200 /
5201
5202Execute an executable path with arguments, replacing current process.
5203[clinic start generated code]*/
5204
Larry Hastings2f936352014-08-05 14:04:04 +10005205static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005206os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
5207/*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005208{
Steve Dowercc16be82016-09-08 10:35:16 -07005209 EXECV_CHAR **argvlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005210 Py_ssize_t argc;
5211
5212 /* execv has two arguments: (path, argv), where
5213 argv is a list or tuple of strings. */
5214
Ross Lagerwall7807c352011-03-17 20:20:30 +02005215 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
5216 PyErr_SetString(PyExc_TypeError,
5217 "execv() arg 2 must be a tuple or list");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005218 return NULL;
5219 }
5220 argc = PySequence_Size(argv);
5221 if (argc < 1) {
5222 PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005223 return NULL;
5224 }
5225
5226 argvlist = parse_arglist(argv, &argc);
5227 if (argvlist == NULL) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02005228 return NULL;
5229 }
Steve Dowerbce26262016-11-19 19:17:26 -08005230 if (!argvlist[0][0]) {
5231 PyErr_SetString(PyExc_ValueError,
5232 "execv() arg 2 first element cannot be empty");
5233 free_string_array(argvlist, argc);
5234 return NULL;
5235 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005236
Saiyang Gou95f60012020-02-04 16:15:00 -08005237 if (PySys_Audit("os.exec", "OOO", path->object ? path->object : Py_None,
5238 argv, Py_None) < 0) {
5239 free_string_array(argvlist, argc);
5240 return NULL;
5241 }
5242
Steve Dowerbce26262016-11-19 19:17:26 -08005243 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005244#ifdef HAVE_WEXECV
5245 _wexecv(path->wide, argvlist);
5246#else
5247 execv(path->narrow, argvlist);
5248#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005249 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005250
5251 /* If we get here it's definitely an error */
5252
5253 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005254 return posix_error();
5255}
5256
Larry Hastings2f936352014-08-05 14:04:04 +10005257
5258/*[clinic input]
5259os.execve
5260
5261 path: path_t(allow_fd='PATH_HAVE_FEXECVE')
5262 Path of executable file.
5263 argv: object
5264 Tuple or list of strings.
5265 env: object
5266 Dictionary of strings mapping to strings.
5267
5268Execute an executable path with arguments, replacing current process.
5269[clinic start generated code]*/
5270
Larry Hastings2f936352014-08-05 14:04:04 +10005271static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005272os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
5273/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005274{
Steve Dowercc16be82016-09-08 10:35:16 -07005275 EXECV_CHAR **argvlist = NULL;
5276 EXECV_CHAR **envlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005277 Py_ssize_t argc, envc;
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005278
Victor Stinner8c62be82010-05-06 00:08:46 +00005279 /* execve has three arguments: (path, argv, env), where
5280 argv is a list or tuple of strings and env is a dictionary
5281 like posix.environ. */
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005282
Ross Lagerwall7807c352011-03-17 20:20:30 +02005283 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005284 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005285 "execve: argv must be a tuple or list");
Saiyang Gou95f60012020-02-04 16:15:00 -08005286 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005287 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005288 argc = PySequence_Size(argv);
Steve Dowerbce26262016-11-19 19:17:26 -08005289 if (argc < 1) {
5290 PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
5291 return NULL;
5292 }
5293
Victor Stinner8c62be82010-05-06 00:08:46 +00005294 if (!PyMapping_Check(env)) {
5295 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005296 "execve: environment must be a mapping object");
Saiyang Gou95f60012020-02-04 16:15:00 -08005297 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005298 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005299
Ross Lagerwall7807c352011-03-17 20:20:30 +02005300 argvlist = parse_arglist(argv, &argc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005301 if (argvlist == NULL) {
Saiyang Gou95f60012020-02-04 16:15:00 -08005302 goto fail_0;
Victor Stinner8c62be82010-05-06 00:08:46 +00005303 }
Steve Dowerbce26262016-11-19 19:17:26 -08005304 if (!argvlist[0][0]) {
5305 PyErr_SetString(PyExc_ValueError,
5306 "execve: argv first element cannot be empty");
Saiyang Gou95f60012020-02-04 16:15:00 -08005307 goto fail_0;
Steve Dowerbce26262016-11-19 19:17:26 -08005308 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005309
Victor Stinner8c62be82010-05-06 00:08:46 +00005310 envlist = parse_envlist(env, &envc);
5311 if (envlist == NULL)
Saiyang Gou95f60012020-02-04 16:15:00 -08005312 goto fail_0;
5313
5314 if (PySys_Audit("os.exec", "OOO", path->object ? path->object : Py_None,
5315 argv, env) < 0) {
5316 goto fail_1;
5317 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005318
Steve Dowerbce26262016-11-19 19:17:26 -08005319 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07005320#ifdef HAVE_FEXECVE
Larry Hastings2f936352014-08-05 14:04:04 +10005321 if (path->fd > -1)
5322 fexecve(path->fd, argvlist, envlist);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005323 else
5324#endif
Steve Dowercc16be82016-09-08 10:35:16 -07005325#ifdef HAVE_WEXECV
5326 _wexecve(path->wide, argvlist, envlist);
5327#else
Larry Hastings2f936352014-08-05 14:04:04 +10005328 execve(path->narrow, argvlist, envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07005329#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005330 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005331
5332 /* If we get here it's definitely an error */
5333
Alexey Izbyshev83460312018-10-20 03:28:22 +03005334 posix_path_error(path);
Saiyang Gou95f60012020-02-04 16:15:00 -08005335 fail_1:
Steve Dowercc16be82016-09-08 10:35:16 -07005336 free_string_array(envlist, envc);
Saiyang Gou95f60012020-02-04 16:15:00 -08005337 fail_0:
Larry Hastings9cf065c2012-06-22 16:30:09 -07005338 if (argvlist)
5339 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005340 return NULL;
5341}
Steve Dowercc16be82016-09-08 10:35:16 -07005342
Larry Hastings9cf065c2012-06-22 16:30:09 -07005343#endif /* HAVE_EXECV */
5344
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005345#ifdef HAVE_POSIX_SPAWN
5346
5347enum posix_spawn_file_actions_identifier {
5348 POSIX_SPAWN_OPEN,
5349 POSIX_SPAWN_CLOSE,
5350 POSIX_SPAWN_DUP2
5351};
5352
William Orr81574b82018-10-01 22:19:56 -07005353#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005354static int
Pablo Galindo254a4662018-09-07 16:44:24 +01005355convert_sched_param(PyObject *param, struct sched_param *res);
William Orr81574b82018-10-01 22:19:56 -07005356#endif
Pablo Galindo254a4662018-09-07 16:44:24 +01005357
5358static int
Victor Stinner325e4ba2019-02-01 15:47:24 +01005359parse_posix_spawn_flags(const char *func_name, PyObject *setpgroup,
5360 int resetids, int setsid, PyObject *setsigmask,
Pablo Galindo254a4662018-09-07 16:44:24 +01005361 PyObject *setsigdef, PyObject *scheduler,
5362 posix_spawnattr_t *attrp)
5363{
5364 long all_flags = 0;
5365
5366 errno = posix_spawnattr_init(attrp);
5367 if (errno) {
5368 posix_error();
5369 return -1;
5370 }
5371
5372 if (setpgroup) {
5373 pid_t pgid = PyLong_AsPid(setpgroup);
5374 if (pgid == (pid_t)-1 && PyErr_Occurred()) {
5375 goto fail;
5376 }
5377 errno = posix_spawnattr_setpgroup(attrp, pgid);
5378 if (errno) {
5379 posix_error();
5380 goto fail;
5381 }
5382 all_flags |= POSIX_SPAWN_SETPGROUP;
5383 }
5384
5385 if (resetids) {
5386 all_flags |= POSIX_SPAWN_RESETIDS;
5387 }
5388
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005389 if (setsid) {
5390#ifdef POSIX_SPAWN_SETSID
5391 all_flags |= POSIX_SPAWN_SETSID;
5392#elif defined(POSIX_SPAWN_SETSID_NP)
5393 all_flags |= POSIX_SPAWN_SETSID_NP;
5394#else
5395 argument_unavailable_error(func_name, "setsid");
5396 return -1;
5397#endif
5398 }
5399
Pablo Galindo254a4662018-09-07 16:44:24 +01005400 if (setsigmask) {
5401 sigset_t set;
5402 if (!_Py_Sigset_Converter(setsigmask, &set)) {
5403 goto fail;
5404 }
5405 errno = posix_spawnattr_setsigmask(attrp, &set);
5406 if (errno) {
5407 posix_error();
5408 goto fail;
5409 }
5410 all_flags |= POSIX_SPAWN_SETSIGMASK;
5411 }
5412
5413 if (setsigdef) {
5414 sigset_t set;
5415 if (!_Py_Sigset_Converter(setsigdef, &set)) {
5416 goto fail;
5417 }
5418 errno = posix_spawnattr_setsigdefault(attrp, &set);
5419 if (errno) {
5420 posix_error();
5421 goto fail;
5422 }
5423 all_flags |= POSIX_SPAWN_SETSIGDEF;
5424 }
5425
5426 if (scheduler) {
5427#ifdef POSIX_SPAWN_SETSCHEDULER
5428 PyObject *py_schedpolicy;
5429 struct sched_param schedparam;
5430
5431 if (!PyArg_ParseTuple(scheduler, "OO&"
5432 ";A scheduler tuple must have two elements",
5433 &py_schedpolicy, convert_sched_param, &schedparam)) {
5434 goto fail;
5435 }
5436 if (py_schedpolicy != Py_None) {
5437 int schedpolicy = _PyLong_AsInt(py_schedpolicy);
5438
5439 if (schedpolicy == -1 && PyErr_Occurred()) {
5440 goto fail;
5441 }
5442 errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
5443 if (errno) {
5444 posix_error();
5445 goto fail;
5446 }
5447 all_flags |= POSIX_SPAWN_SETSCHEDULER;
5448 }
5449 errno = posix_spawnattr_setschedparam(attrp, &schedparam);
5450 if (errno) {
5451 posix_error();
5452 goto fail;
5453 }
5454 all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
5455#else
5456 PyErr_SetString(PyExc_NotImplementedError,
5457 "The scheduler option is not supported in this system.");
5458 goto fail;
5459#endif
5460 }
5461
5462 errno = posix_spawnattr_setflags(attrp, all_flags);
5463 if (errno) {
5464 posix_error();
5465 goto fail;
5466 }
5467
5468 return 0;
5469
5470fail:
5471 (void)posix_spawnattr_destroy(attrp);
5472 return -1;
5473}
5474
5475static int
Serhiy Storchakaef347532018-05-01 16:45:04 +03005476parse_file_actions(PyObject *file_actions,
Pablo Galindocb970732018-06-19 09:19:50 +01005477 posix_spawn_file_actions_t *file_actionsp,
5478 PyObject *temp_buffer)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005479{
5480 PyObject *seq;
5481 PyObject *file_action = NULL;
5482 PyObject *tag_obj;
5483
5484 seq = PySequence_Fast(file_actions,
5485 "file_actions must be a sequence or None");
5486 if (seq == NULL) {
5487 return -1;
5488 }
5489
5490 errno = posix_spawn_file_actions_init(file_actionsp);
5491 if (errno) {
5492 posix_error();
5493 Py_DECREF(seq);
5494 return -1;
5495 }
5496
Zackery Spytzd52a83a2019-06-26 14:54:20 -06005497 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
Serhiy Storchakaef347532018-05-01 16:45:04 +03005498 file_action = PySequence_Fast_GET_ITEM(seq, i);
5499 Py_INCREF(file_action);
5500 if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
5501 PyErr_SetString(PyExc_TypeError,
5502 "Each file_actions element must be a non-empty tuple");
5503 goto fail;
5504 }
5505 long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
5506 if (tag == -1 && PyErr_Occurred()) {
5507 goto fail;
5508 }
5509
5510 /* Populate the file_actions object */
5511 switch (tag) {
5512 case POSIX_SPAWN_OPEN: {
5513 int fd, oflag;
5514 PyObject *path;
5515 unsigned long mode;
5516 if (!PyArg_ParseTuple(file_action, "OiO&ik"
5517 ";A open file_action tuple must have 5 elements",
5518 &tag_obj, &fd, PyUnicode_FSConverter, &path,
5519 &oflag, &mode))
5520 {
5521 goto fail;
5522 }
Pablo Galindocb970732018-06-19 09:19:50 +01005523 if (PyList_Append(temp_buffer, path)) {
5524 Py_DECREF(path);
5525 goto fail;
5526 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005527 errno = posix_spawn_file_actions_addopen(file_actionsp,
5528 fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
Pablo Galindocb970732018-06-19 09:19:50 +01005529 Py_DECREF(path);
Serhiy Storchakaef347532018-05-01 16:45:04 +03005530 if (errno) {
5531 posix_error();
5532 goto fail;
5533 }
5534 break;
5535 }
5536 case POSIX_SPAWN_CLOSE: {
5537 int fd;
5538 if (!PyArg_ParseTuple(file_action, "Oi"
5539 ";A close file_action tuple must have 2 elements",
5540 &tag_obj, &fd))
5541 {
5542 goto fail;
5543 }
5544 errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
5545 if (errno) {
5546 posix_error();
5547 goto fail;
5548 }
5549 break;
5550 }
5551 case POSIX_SPAWN_DUP2: {
5552 int fd1, fd2;
5553 if (!PyArg_ParseTuple(file_action, "Oii"
5554 ";A dup2 file_action tuple must have 3 elements",
5555 &tag_obj, &fd1, &fd2))
5556 {
5557 goto fail;
5558 }
5559 errno = posix_spawn_file_actions_adddup2(file_actionsp,
5560 fd1, fd2);
5561 if (errno) {
5562 posix_error();
5563 goto fail;
5564 }
5565 break;
5566 }
5567 default: {
5568 PyErr_SetString(PyExc_TypeError,
5569 "Unknown file_actions identifier");
5570 goto fail;
5571 }
5572 }
5573 Py_DECREF(file_action);
5574 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005575
Serhiy Storchakaef347532018-05-01 16:45:04 +03005576 Py_DECREF(seq);
5577 return 0;
5578
5579fail:
5580 Py_DECREF(seq);
5581 Py_DECREF(file_action);
5582 (void)posix_spawn_file_actions_destroy(file_actionsp);
5583 return -1;
5584}
5585
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005586
5587static PyObject *
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005588py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
5589 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005590 PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005591 PyObject *setsigdef, PyObject *scheduler)
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005592{
Victor Stinner325e4ba2019-02-01 15:47:24 +01005593 const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005594 EXECV_CHAR **argvlist = NULL;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005595 EXECV_CHAR **envlist = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005596 posix_spawn_file_actions_t file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005597 posix_spawn_file_actions_t *file_actionsp = NULL;
Pablo Galindo254a4662018-09-07 16:44:24 +01005598 posix_spawnattr_t attr;
5599 posix_spawnattr_t *attrp = NULL;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005600 Py_ssize_t argc, envc;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005601 PyObject *result = NULL;
Pablo Galindocb970732018-06-19 09:19:50 +01005602 PyObject *temp_buffer = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005603 pid_t pid;
5604 int err_code;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005605
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005606 /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
Serhiy Storchakaef347532018-05-01 16:45:04 +03005607 argv is a list or tuple of strings and env is a dictionary
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005608 like posix.environ. */
5609
Serhiy Storchakaef347532018-05-01 16:45:04 +03005610 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005611 PyErr_Format(PyExc_TypeError,
5612 "%s: argv must be a tuple or list", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005613 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005614 }
5615 argc = PySequence_Size(argv);
5616 if (argc < 1) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005617 PyErr_Format(PyExc_ValueError,
5618 "%s: argv must not be empty", func_name);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005619 return NULL;
5620 }
5621
5622 if (!PyMapping_Check(env)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005623 PyErr_Format(PyExc_TypeError,
5624 "%s: environment must be a mapping object", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005625 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005626 }
5627
5628 argvlist = parse_arglist(argv, &argc);
5629 if (argvlist == NULL) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005630 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005631 }
5632 if (!argvlist[0][0]) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005633 PyErr_Format(PyExc_ValueError,
5634 "%s: argv first element cannot be empty", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005635 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005636 }
5637
5638 envlist = parse_envlist(env, &envc);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005639 if (envlist == NULL) {
5640 goto exit;
5641 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005642
Anthony Shaw948ed8c2019-05-10 12:00:06 +10005643 if (file_actions != NULL && file_actions != Py_None) {
Pablo Galindocb970732018-06-19 09:19:50 +01005644 /* There is a bug in old versions of glibc that makes some of the
5645 * helper functions for manipulating file actions not copy the provided
5646 * buffers. The problem is that posix_spawn_file_actions_addopen does not
5647 * copy the value of path for some old versions of glibc (<2.20).
5648 * The use of temp_buffer here is a workaround that keeps the
5649 * python objects that own the buffers alive until posix_spawn gets called.
5650 * Check https://bugs.python.org/issue33630 and
5651 * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
5652 temp_buffer = PyList_New(0);
5653 if (!temp_buffer) {
5654 goto exit;
5655 }
5656 if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005657 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005658 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005659 file_actionsp = &file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005660 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005661
Victor Stinner325e4ba2019-02-01 15:47:24 +01005662 if (parse_posix_spawn_flags(func_name, setpgroup, resetids, setsid,
5663 setsigmask, setsigdef, scheduler, &attr)) {
Pablo Galindo254a4662018-09-07 16:44:24 +01005664 goto exit;
5665 }
5666 attrp = &attr;
5667
Saiyang Gou95f60012020-02-04 16:15:00 -08005668 if (PySys_Audit("os.posix_spawn", "OOO",
5669 path->object ? path->object : Py_None, argv, env) < 0) {
5670 goto exit;
5671 }
5672
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005673 _Py_BEGIN_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005674#ifdef HAVE_POSIX_SPAWNP
5675 if (use_posix_spawnp) {
5676 err_code = posix_spawnp(&pid, path->narrow,
5677 file_actionsp, attrp, argvlist, envlist);
5678 }
5679 else
5680#endif /* HAVE_POSIX_SPAWNP */
5681 {
5682 err_code = posix_spawn(&pid, path->narrow,
5683 file_actionsp, attrp, argvlist, envlist);
5684 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005685 _Py_END_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005686
Serhiy Storchakaef347532018-05-01 16:45:04 +03005687 if (err_code) {
5688 errno = err_code;
5689 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005690 goto exit;
5691 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08005692#ifdef _Py_MEMORY_SANITIZER
5693 __msan_unpoison(&pid, sizeof(pid));
5694#endif
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005695 result = PyLong_FromPid(pid);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005696
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005697exit:
Serhiy Storchakaef347532018-05-01 16:45:04 +03005698 if (file_actionsp) {
5699 (void)posix_spawn_file_actions_destroy(file_actionsp);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005700 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005701 if (attrp) {
5702 (void)posix_spawnattr_destroy(attrp);
5703 }
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005704 if (envlist) {
5705 free_string_array(envlist, envc);
5706 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005707 if (argvlist) {
5708 free_string_array(argvlist, argc);
5709 }
Pablo Galindocb970732018-06-19 09:19:50 +01005710 Py_XDECREF(temp_buffer);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005711 return result;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005712}
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005713
5714
5715/*[clinic input]
5716
5717os.posix_spawn
5718 path: path_t
5719 Path of executable file.
5720 argv: object
5721 Tuple or list of strings.
5722 env: object
5723 Dictionary of strings mapping to strings.
5724 /
5725 *
5726 file_actions: object(c_default='NULL') = ()
5727 A sequence of file action tuples.
5728 setpgroup: object = NULL
5729 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5730 resetids: bool(accept={int}) = False
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005731 If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
5732 setsid: bool(accept={int}) = False
5733 If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005734 setsigmask: object(c_default='NULL') = ()
5735 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5736 setsigdef: object(c_default='NULL') = ()
5737 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5738 scheduler: object = NULL
5739 A tuple with the scheduler policy (optional) and parameters.
5740
5741Execute the program specified by path in a new process.
5742[clinic start generated code]*/
5743
5744static PyObject *
5745os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
5746 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005747 PyObject *setpgroup, int resetids, int setsid,
5748 PyObject *setsigmask, PyObject *setsigdef,
5749 PyObject *scheduler)
5750/*[clinic end generated code: output=14a1098c566bc675 input=8c6305619a00ad04]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005751{
5752 return py_posix_spawn(0, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005753 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005754 scheduler);
5755}
5756 #endif /* HAVE_POSIX_SPAWN */
5757
5758
5759
5760#ifdef HAVE_POSIX_SPAWNP
5761/*[clinic input]
5762
5763os.posix_spawnp
5764 path: path_t
5765 Path of executable file.
5766 argv: object
5767 Tuple or list of strings.
5768 env: object
5769 Dictionary of strings mapping to strings.
5770 /
5771 *
5772 file_actions: object(c_default='NULL') = ()
5773 A sequence of file action tuples.
5774 setpgroup: object = NULL
5775 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5776 resetids: bool(accept={int}) = False
5777 If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005778 setsid: bool(accept={int}) = False
5779 If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005780 setsigmask: object(c_default='NULL') = ()
5781 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5782 setsigdef: object(c_default='NULL') = ()
5783 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5784 scheduler: object = NULL
5785 A tuple with the scheduler policy (optional) and parameters.
5786
5787Execute the program specified by path in a new process.
5788[clinic start generated code]*/
5789
5790static PyObject *
5791os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
5792 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005793 PyObject *setpgroup, int resetids, int setsid,
5794 PyObject *setsigmask, PyObject *setsigdef,
5795 PyObject *scheduler)
5796/*[clinic end generated code: output=7b9aaefe3031238d input=c1911043a22028da]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005797{
5798 return py_posix_spawn(1, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005799 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005800 scheduler);
5801}
5802#endif /* HAVE_POSIX_SPAWNP */
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005803
pxinwrf2d7ac72019-05-21 18:46:37 +08005804#ifdef HAVE_RTPSPAWN
5805static intptr_t
5806_rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
5807 const char *envp[])
5808{
5809 RTP_ID rtpid;
5810 int status;
5811 pid_t res;
5812 int async_err = 0;
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005813
pxinwrf2d7ac72019-05-21 18:46:37 +08005814 /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
5815 uStackSize=0 cannot be used, the default stack size is too small for
5816 Python. */
5817 if (envp) {
5818 rtpid = rtpSpawn(rtpFileName, argv, envp,
5819 100, 0x1000000, 0, VX_FP_TASK);
5820 }
5821 else {
5822 rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
5823 100, 0x1000000, 0, VX_FP_TASK);
5824 }
5825 if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
5826 do {
5827 res = waitpid((pid_t)rtpid, &status, 0);
5828 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
5829
5830 if (res < 0)
5831 return RTP_ID_ERROR;
5832 return ((intptr_t)status);
5833 }
5834 return ((intptr_t)rtpid);
5835}
5836#endif
5837
5838#if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
Larry Hastings2f936352014-08-05 14:04:04 +10005839/*[clinic input]
5840os.spawnv
5841
5842 mode: int
5843 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005844 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005845 Path of executable file.
5846 argv: object
5847 Tuple or list of strings.
5848 /
5849
5850Execute the program specified by path in a new process.
5851[clinic start generated code]*/
5852
Larry Hastings2f936352014-08-05 14:04:04 +10005853static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005854os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
5855/*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005856{
Steve Dowercc16be82016-09-08 10:35:16 -07005857 EXECV_CHAR **argvlist;
Larry Hastings2f936352014-08-05 14:04:04 +10005858 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00005859 Py_ssize_t argc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005860 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005861 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Guido van Rossuma1065681999-01-25 23:20:23 +00005862
Victor Stinner8c62be82010-05-06 00:08:46 +00005863 /* spawnv has three arguments: (mode, path, argv), where
5864 argv is a list or tuple of strings. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005865
Victor Stinner8c62be82010-05-06 00:08:46 +00005866 if (PyList_Check(argv)) {
5867 argc = PyList_Size(argv);
5868 getitem = PyList_GetItem;
5869 }
5870 else if (PyTuple_Check(argv)) {
5871 argc = PyTuple_Size(argv);
5872 getitem = PyTuple_GetItem;
5873 }
5874 else {
5875 PyErr_SetString(PyExc_TypeError,
5876 "spawnv() arg 2 must be a tuple or list");
Victor Stinner8c62be82010-05-06 00:08:46 +00005877 return NULL;
5878 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005879 if (argc == 0) {
5880 PyErr_SetString(PyExc_ValueError,
5881 "spawnv() arg 2 cannot be empty");
5882 return NULL;
5883 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005884
Steve Dowercc16be82016-09-08 10:35:16 -07005885 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005886 if (argvlist == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005887 return PyErr_NoMemory();
5888 }
5889 for (i = 0; i < argc; i++) {
5890 if (!fsconvert_strdup((*getitem)(argv, i),
5891 &argvlist[i])) {
5892 free_string_array(argvlist, i);
5893 PyErr_SetString(
5894 PyExc_TypeError,
5895 "spawnv() arg 2 must contain only strings");
Victor Stinner8c62be82010-05-06 00:08:46 +00005896 return NULL;
5897 }
Steve Dower93ff8722016-11-19 19:03:54 -08005898 if (i == 0 && !argvlist[0][0]) {
Victor Stinner8acb4cf2017-06-15 15:30:40 +02005899 free_string_array(argvlist, i + 1);
Steve Dower93ff8722016-11-19 19:03:54 -08005900 PyErr_SetString(
5901 PyExc_ValueError,
5902 "spawnv() arg 2 first element cannot be empty");
5903 return NULL;
5904 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005905 }
5906 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005907
pxinwrf2d7ac72019-05-21 18:46:37 +08005908#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00005909 if (mode == _OLD_P_OVERLAY)
5910 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08005911#endif
Tim Peters5aa91602002-01-30 05:46:57 +00005912
Saiyang Gou95f60012020-02-04 16:15:00 -08005913 if (PySys_Audit("os.spawn", "iOOO", mode,
5914 path->object ? path->object : Py_None, argv,
5915 Py_None) < 0) {
5916 free_string_array(argvlist, argc);
5917 return NULL;
5918 }
5919
Victor Stinner8c62be82010-05-06 00:08:46 +00005920 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07005921 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005922#ifdef HAVE_WSPAWNV
5923 spawnval = _wspawnv(mode, path->wide, argvlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08005924#elif defined(HAVE_RTPSPAWN)
5925 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
Steve Dowercc16be82016-09-08 10:35:16 -07005926#else
5927 spawnval = _spawnv(mode, path->narrow, argvlist);
5928#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07005929 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00005930 Py_END_ALLOW_THREADS
Tim Peters5aa91602002-01-30 05:46:57 +00005931
Victor Stinner8c62be82010-05-06 00:08:46 +00005932 free_string_array(argvlist, argc);
Guido van Rossuma1065681999-01-25 23:20:23 +00005933
Victor Stinner8c62be82010-05-06 00:08:46 +00005934 if (spawnval == -1)
5935 return posix_error();
5936 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01005937 return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00005938}
5939
Larry Hastings2f936352014-08-05 14:04:04 +10005940/*[clinic input]
5941os.spawnve
5942
5943 mode: int
5944 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005945 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005946 Path of executable file.
5947 argv: object
5948 Tuple or list of strings.
5949 env: object
5950 Dictionary of strings mapping to strings.
5951 /
5952
5953Execute the program specified by path in a new process.
5954[clinic start generated code]*/
5955
Larry Hastings2f936352014-08-05 14:04:04 +10005956static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005957os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005958 PyObject *env)
Steve Dowercc16be82016-09-08 10:35:16 -07005959/*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005960{
Steve Dowercc16be82016-09-08 10:35:16 -07005961 EXECV_CHAR **argvlist;
5962 EXECV_CHAR **envlist;
Victor Stinner8c62be82010-05-06 00:08:46 +00005963 PyObject *res = NULL;
Antoine Pitrou22e41552010-08-15 18:07:50 +00005964 Py_ssize_t argc, i, envc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005965 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005966 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005967 Py_ssize_t lastarg = 0;
Guido van Rossuma1065681999-01-25 23:20:23 +00005968
Victor Stinner8c62be82010-05-06 00:08:46 +00005969 /* spawnve has four arguments: (mode, path, argv, env), where
5970 argv is a list or tuple of strings and env is a dictionary
5971 like posix.environ. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005972
Victor Stinner8c62be82010-05-06 00:08:46 +00005973 if (PyList_Check(argv)) {
5974 argc = PyList_Size(argv);
5975 getitem = PyList_GetItem;
5976 }
5977 else if (PyTuple_Check(argv)) {
5978 argc = PyTuple_Size(argv);
5979 getitem = PyTuple_GetItem;
5980 }
5981 else {
5982 PyErr_SetString(PyExc_TypeError,
5983 "spawnve() arg 2 must be a tuple or list");
5984 goto fail_0;
5985 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005986 if (argc == 0) {
5987 PyErr_SetString(PyExc_ValueError,
5988 "spawnve() arg 2 cannot be empty");
5989 goto fail_0;
5990 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005991 if (!PyMapping_Check(env)) {
5992 PyErr_SetString(PyExc_TypeError,
5993 "spawnve() arg 3 must be a mapping object");
5994 goto fail_0;
5995 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005996
Steve Dowercc16be82016-09-08 10:35:16 -07005997 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005998 if (argvlist == NULL) {
5999 PyErr_NoMemory();
6000 goto fail_0;
6001 }
6002 for (i = 0; i < argc; i++) {
6003 if (!fsconvert_strdup((*getitem)(argv, i),
6004 &argvlist[i]))
6005 {
6006 lastarg = i;
6007 goto fail_1;
6008 }
Steve Dowerbce26262016-11-19 19:17:26 -08006009 if (i == 0 && !argvlist[0][0]) {
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006010 lastarg = i + 1;
Steve Dowerbce26262016-11-19 19:17:26 -08006011 PyErr_SetString(
6012 PyExc_ValueError,
6013 "spawnv() arg 2 first element cannot be empty");
6014 goto fail_1;
6015 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006016 }
6017 lastarg = argc;
6018 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00006019
Victor Stinner8c62be82010-05-06 00:08:46 +00006020 envlist = parse_envlist(env, &envc);
6021 if (envlist == NULL)
6022 goto fail_1;
Guido van Rossuma1065681999-01-25 23:20:23 +00006023
pxinwrf2d7ac72019-05-21 18:46:37 +08006024#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00006025 if (mode == _OLD_P_OVERLAY)
6026 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08006027#endif
Tim Peters25059d32001-12-07 20:35:43 +00006028
Saiyang Gou95f60012020-02-04 16:15:00 -08006029 if (PySys_Audit("os.spawn", "iOOO", mode,
6030 path->object ? path->object : Py_None, argv, env) < 0) {
6031 goto fail_2;
6032 }
6033
Victor Stinner8c62be82010-05-06 00:08:46 +00006034 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07006035 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07006036#ifdef HAVE_WSPAWNV
6037 spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08006038#elif defined(HAVE_RTPSPAWN)
6039 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
6040 (const char **)envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07006041#else
6042 spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
6043#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07006044 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00006045 Py_END_ALLOW_THREADS
Tim Peters25059d32001-12-07 20:35:43 +00006046
Victor Stinner8c62be82010-05-06 00:08:46 +00006047 if (spawnval == -1)
6048 (void) posix_error();
6049 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01006050 res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00006051
Saiyang Gou95f60012020-02-04 16:15:00 -08006052 fail_2:
Victor Stinner8c62be82010-05-06 00:08:46 +00006053 while (--envc >= 0)
6054 PyMem_DEL(envlist[envc]);
6055 PyMem_DEL(envlist);
Guido van Rossum0847c5c2002-12-13 18:36:22 +00006056 fail_1:
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006057 free_string_array(argvlist, lastarg);
Martin v. Löwis114619e2002-10-07 06:44:21 +00006058 fail_0:
Victor Stinner8c62be82010-05-06 00:08:46 +00006059 return res;
Guido van Rossuma1065681999-01-25 23:20:23 +00006060}
Andrew MacIntyre69e18c92004-04-04 07:11:43 +00006061
Guido van Rossuma1065681999-01-25 23:20:23 +00006062#endif /* HAVE_SPAWNV */
6063
6064
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006065#ifdef HAVE_FORK
Gregory P. Smith163468a2017-05-29 10:03:41 -07006066
6067/* Helper function to validate arguments.
6068 Returns 0 on success. non-zero on failure with a TypeError raised.
6069 If obj is non-NULL it must be callable. */
6070static int
6071check_null_or_callable(PyObject *obj, const char* obj_name)
6072{
6073 if (obj && !PyCallable_Check(obj)) {
6074 PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
Eddie Elizondob3966632019-11-05 07:16:14 -08006075 obj_name, _PyType_Name(Py_TYPE(obj)));
Gregory P. Smith163468a2017-05-29 10:03:41 -07006076 return -1;
6077 }
6078 return 0;
6079}
6080
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006081/*[clinic input]
6082os.register_at_fork
6083
Gregory P. Smith163468a2017-05-29 10:03:41 -07006084 *
6085 before: object=NULL
6086 A callable to be called in the parent before the fork() syscall.
6087 after_in_child: object=NULL
6088 A callable to be called in the child after fork().
6089 after_in_parent: object=NULL
6090 A callable to be called in the parent after fork().
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006091
Gregory P. Smith163468a2017-05-29 10:03:41 -07006092Register callables to be called when forking a new process.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006093
Gregory P. Smith163468a2017-05-29 10:03:41 -07006094'before' callbacks are called in reverse order.
6095'after_in_child' and 'after_in_parent' callbacks are called in order.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006096
6097[clinic start generated code]*/
6098
6099static PyObject *
Gregory P. Smith163468a2017-05-29 10:03:41 -07006100os_register_at_fork_impl(PyObject *module, PyObject *before,
6101 PyObject *after_in_child, PyObject *after_in_parent)
6102/*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006103{
6104 PyInterpreterState *interp;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006105
Gregory P. Smith163468a2017-05-29 10:03:41 -07006106 if (!before && !after_in_child && !after_in_parent) {
6107 PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
6108 return NULL;
6109 }
6110 if (check_null_or_callable(before, "before") ||
6111 check_null_or_callable(after_in_child, "after_in_child") ||
6112 check_null_or_callable(after_in_parent, "after_in_parent")) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006113 return NULL;
6114 }
Victor Stinnercaba55b2018-08-03 15:33:52 +02006115 interp = _PyInterpreterState_Get();
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006116
Gregory P. Smith163468a2017-05-29 10:03:41 -07006117 if (register_at_forker(&interp->before_forkers, before)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006118 return NULL;
6119 }
Gregory P. Smith163468a2017-05-29 10:03:41 -07006120 if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006121 return NULL;
Gregory P. Smith163468a2017-05-29 10:03:41 -07006122 }
6123 if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
6124 return NULL;
6125 }
6126 Py_RETURN_NONE;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006127}
6128#endif /* HAVE_FORK */
6129
6130
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006131#ifdef HAVE_FORK1
Larry Hastings2f936352014-08-05 14:04:04 +10006132/*[clinic input]
6133os.fork1
6134
6135Fork a child process with a single multiplexed (i.e., not bound) thread.
6136
6137Return 0 to child process and PID of child to parent process.
6138[clinic start generated code]*/
6139
Larry Hastings2f936352014-08-05 14:04:04 +10006140static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006141os_fork1_impl(PyObject *module)
6142/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006143{
Victor Stinner8c62be82010-05-06 00:08:46 +00006144 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006145
Eric Snow59032962018-09-14 14:17:20 -07006146 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6147 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6148 return NULL;
6149 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006150 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006151 pid = fork1();
6152 if (pid == 0) {
6153 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006154 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006155 } else {
6156 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006157 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006158 }
6159 if (pid == -1)
6160 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006161 return PyLong_FromPid(pid);
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006162}
Larry Hastings2f936352014-08-05 14:04:04 +10006163#endif /* HAVE_FORK1 */
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006164
6165
Guido van Rossumad0ee831995-03-01 10:34:45 +00006166#ifdef HAVE_FORK
Larry Hastings2f936352014-08-05 14:04:04 +10006167/*[clinic input]
6168os.fork
6169
6170Fork a child process.
6171
6172Return 0 to child process and PID of child to parent process.
6173[clinic start generated code]*/
6174
Larry Hastings2f936352014-08-05 14:04:04 +10006175static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006176os_fork_impl(PyObject *module)
6177/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006178{
Victor Stinner8c62be82010-05-06 00:08:46 +00006179 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006180
Eric Snow59032962018-09-14 14:17:20 -07006181 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6182 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6183 return NULL;
6184 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006185 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006186 pid = fork();
6187 if (pid == 0) {
6188 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006189 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006190 } else {
6191 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006192 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006193 }
6194 if (pid == -1)
6195 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006196 return PyLong_FromPid(pid);
Guido van Rossum85e3b011991-06-03 12:42:10 +00006197}
Larry Hastings2f936352014-08-05 14:04:04 +10006198#endif /* HAVE_FORK */
6199
Guido van Rossum85e3b011991-06-03 12:42:10 +00006200
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006201#ifdef HAVE_SCHED_H
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006202#ifdef HAVE_SCHED_GET_PRIORITY_MAX
Larry Hastings2f936352014-08-05 14:04:04 +10006203/*[clinic input]
6204os.sched_get_priority_max
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006205
Larry Hastings2f936352014-08-05 14:04:04 +10006206 policy: int
6207
6208Get the maximum scheduling priority for policy.
6209[clinic start generated code]*/
6210
Larry Hastings2f936352014-08-05 14:04:04 +10006211static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006212os_sched_get_priority_max_impl(PyObject *module, int policy)
6213/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006214{
6215 int max;
6216
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006217 max = sched_get_priority_max(policy);
6218 if (max < 0)
6219 return posix_error();
6220 return PyLong_FromLong(max);
6221}
6222
Larry Hastings2f936352014-08-05 14:04:04 +10006223
6224/*[clinic input]
6225os.sched_get_priority_min
6226
6227 policy: int
6228
6229Get the minimum scheduling priority for policy.
6230[clinic start generated code]*/
6231
Larry Hastings2f936352014-08-05 14:04:04 +10006232static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006233os_sched_get_priority_min_impl(PyObject *module, int policy)
6234/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006235{
6236 int min = sched_get_priority_min(policy);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006237 if (min < 0)
6238 return posix_error();
6239 return PyLong_FromLong(min);
6240}
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006241#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
6242
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006243
Larry Hastings2f936352014-08-05 14:04:04 +10006244#ifdef HAVE_SCHED_SETSCHEDULER
6245/*[clinic input]
6246os.sched_getscheduler
6247 pid: pid_t
6248 /
6249
Min ho Kimc4cacc82019-07-31 08:16:13 +10006250Get the scheduling policy for the process identified by pid.
Larry Hastings2f936352014-08-05 14:04:04 +10006251
6252Passing 0 for pid returns the scheduling policy for the calling process.
6253[clinic start generated code]*/
6254
Larry Hastings2f936352014-08-05 14:04:04 +10006255static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006256os_sched_getscheduler_impl(PyObject *module, pid_t pid)
Min ho Kimc4cacc82019-07-31 08:16:13 +10006257/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=8d99dac505485ac8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006258{
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006259 int policy;
6260
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006261 policy = sched_getscheduler(pid);
6262 if (policy < 0)
6263 return posix_error();
6264 return PyLong_FromLong(policy);
6265}
Larry Hastings2f936352014-08-05 14:04:04 +10006266#endif /* HAVE_SCHED_SETSCHEDULER */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006267
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006268
William Orr81574b82018-10-01 22:19:56 -07006269#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Larry Hastings2f936352014-08-05 14:04:04 +10006270/*[clinic input]
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006271class os.sched_param "PyObject *" "SchedParamType"
Larry Hastings2f936352014-08-05 14:04:04 +10006272
6273@classmethod
6274os.sched_param.__new__
6275
6276 sched_priority: object
6277 A scheduling parameter.
6278
Eddie Elizondob3966632019-11-05 07:16:14 -08006279Currently has only one field: sched_priority
Larry Hastings2f936352014-08-05 14:04:04 +10006280[clinic start generated code]*/
6281
Larry Hastings2f936352014-08-05 14:04:04 +10006282static PyObject *
6283os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
Eddie Elizondob3966632019-11-05 07:16:14 -08006284/*[clinic end generated code: output=48f4067d60f48c13 input=eb42909a2c0e3e6c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006285{
6286 PyObject *res;
6287
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006288 res = PyStructSequence_New(type);
6289 if (!res)
6290 return NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10006291 Py_INCREF(sched_priority);
6292 PyStructSequence_SET_ITEM(res, 0, sched_priority);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006293 return res;
6294}
6295
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03006296PyDoc_VAR(os_sched_param__doc__);
6297
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006298static PyStructSequence_Field sched_param_fields[] = {
6299 {"sched_priority", "the scheduling priority"},
6300 {0}
6301};
6302
6303static PyStructSequence_Desc sched_param_desc = {
6304 "sched_param", /* name */
Larry Hastings2f936352014-08-05 14:04:04 +10006305 os_sched_param__doc__, /* doc */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006306 sched_param_fields,
6307 1
6308};
6309
6310static int
6311convert_sched_param(PyObject *param, struct sched_param *res)
6312{
6313 long priority;
6314
Eddie Elizondob3966632019-11-05 07:16:14 -08006315 PyObject *SchedParamType = _posixstate_global->SchedParamType;
6316 if (Py_TYPE(param) != (PyTypeObject *)SchedParamType) {
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006317 PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
6318 return 0;
6319 }
6320 priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
6321 if (priority == -1 && PyErr_Occurred())
6322 return 0;
6323 if (priority > INT_MAX || priority < INT_MIN) {
6324 PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
6325 return 0;
6326 }
6327 res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
6328 return 1;
6329}
William Orr81574b82018-10-01 22:19:56 -07006330#endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006331
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006332
6333#ifdef HAVE_SCHED_SETSCHEDULER
Larry Hastings2f936352014-08-05 14:04:04 +10006334/*[clinic input]
6335os.sched_setscheduler
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006336
Larry Hastings2f936352014-08-05 14:04:04 +10006337 pid: pid_t
6338 policy: int
6339 param: sched_param
6340 /
6341
6342Set the scheduling policy for the process identified by pid.
6343
6344If pid is 0, the calling process is changed.
6345param is an instance of sched_param.
6346[clinic start generated code]*/
6347
Larry Hastings2f936352014-08-05 14:04:04 +10006348static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006349os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
Larry Hastings89964c42015-04-14 18:07:59 -04006350 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006351/*[clinic end generated code: output=b0ac0a70d3b1d705 input=c581f9469a5327dd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006352{
Jesus Cea9c822272011-09-10 01:40:52 +02006353 /*
Jesus Cea54b01492011-09-10 01:53:19 +02006354 ** sched_setscheduler() returns 0 in Linux, but the previous
6355 ** scheduling policy under Solaris/Illumos, and others.
6356 ** On error, -1 is returned in all Operating Systems.
Jesus Cea9c822272011-09-10 01:40:52 +02006357 */
Larry Hastings2f936352014-08-05 14:04:04 +10006358 if (sched_setscheduler(pid, policy, param) == -1)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006359 return posix_error();
6360 Py_RETURN_NONE;
6361}
Larry Hastings2f936352014-08-05 14:04:04 +10006362#endif /* HAVE_SCHED_SETSCHEDULER*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006363
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006364
6365#ifdef HAVE_SCHED_SETPARAM
Larry Hastings2f936352014-08-05 14:04:04 +10006366/*[clinic input]
6367os.sched_getparam
6368 pid: pid_t
6369 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006370
Larry Hastings2f936352014-08-05 14:04:04 +10006371Returns scheduling parameters for the process identified by pid.
6372
6373If pid is 0, returns parameters for the calling process.
6374Return value is an instance of sched_param.
6375[clinic start generated code]*/
6376
Larry Hastings2f936352014-08-05 14:04:04 +10006377static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006378os_sched_getparam_impl(PyObject *module, pid_t pid)
6379/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006380{
6381 struct sched_param param;
6382 PyObject *result;
6383 PyObject *priority;
6384
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006385 if (sched_getparam(pid, &param))
6386 return posix_error();
Eddie Elizondob3966632019-11-05 07:16:14 -08006387 PyObject *SchedParamType = _posixstate_global->SchedParamType;
6388 result = PyStructSequence_New((PyTypeObject *)SchedParamType);
Larry Hastings2f936352014-08-05 14:04:04 +10006389 if (!result)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006390 return NULL;
6391 priority = PyLong_FromLong(param.sched_priority);
6392 if (!priority) {
Larry Hastings2f936352014-08-05 14:04:04 +10006393 Py_DECREF(result);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006394 return NULL;
6395 }
Larry Hastings2f936352014-08-05 14:04:04 +10006396 PyStructSequence_SET_ITEM(result, 0, priority);
6397 return result;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006398}
6399
Larry Hastings2f936352014-08-05 14:04:04 +10006400
6401/*[clinic input]
6402os.sched_setparam
6403 pid: pid_t
6404 param: sched_param
6405 /
6406
6407Set scheduling parameters for the process identified by pid.
6408
6409If pid is 0, sets parameters for the calling process.
6410param should be an instance of sched_param.
6411[clinic start generated code]*/
6412
Larry Hastings2f936352014-08-05 14:04:04 +10006413static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006414os_sched_setparam_impl(PyObject *module, pid_t pid,
Larry Hastings89964c42015-04-14 18:07:59 -04006415 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006416/*[clinic end generated code: output=8af013f78a32b591 input=6b8d6dfcecdc21bd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006417{
6418 if (sched_setparam(pid, param))
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006419 return posix_error();
6420 Py_RETURN_NONE;
6421}
Larry Hastings2f936352014-08-05 14:04:04 +10006422#endif /* HAVE_SCHED_SETPARAM */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006423
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006424
6425#ifdef HAVE_SCHED_RR_GET_INTERVAL
Larry Hastings2f936352014-08-05 14:04:04 +10006426/*[clinic input]
6427os.sched_rr_get_interval -> double
6428 pid: pid_t
6429 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006430
Larry Hastings2f936352014-08-05 14:04:04 +10006431Return the round-robin quantum for the process identified by pid, in seconds.
6432
6433Value returned is a float.
6434[clinic start generated code]*/
6435
Larry Hastings2f936352014-08-05 14:04:04 +10006436static double
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006437os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
6438/*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006439{
6440 struct timespec interval;
6441 if (sched_rr_get_interval(pid, &interval)) {
6442 posix_error();
6443 return -1.0;
6444 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006445#ifdef _Py_MEMORY_SANITIZER
6446 __msan_unpoison(&interval, sizeof(interval));
6447#endif
Larry Hastings2f936352014-08-05 14:04:04 +10006448 return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
6449}
6450#endif /* HAVE_SCHED_RR_GET_INTERVAL */
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006451
Larry Hastings2f936352014-08-05 14:04:04 +10006452
6453/*[clinic input]
6454os.sched_yield
6455
6456Voluntarily relinquish the CPU.
6457[clinic start generated code]*/
6458
Larry Hastings2f936352014-08-05 14:04:04 +10006459static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006460os_sched_yield_impl(PyObject *module)
6461/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006462{
6463 if (sched_yield())
6464 return posix_error();
6465 Py_RETURN_NONE;
6466}
6467
Benjamin Peterson2740af82011-08-02 17:41:34 -05006468#ifdef HAVE_SCHED_SETAFFINITY
Antoine Pitrou84869872012-08-04 16:16:35 +02006469/* The minimum number of CPUs allocated in a cpu_set_t */
6470static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006471
Larry Hastings2f936352014-08-05 14:04:04 +10006472/*[clinic input]
6473os.sched_setaffinity
6474 pid: pid_t
6475 mask : object
6476 /
6477
6478Set the CPU affinity of the process identified by pid to mask.
6479
6480mask should be an iterable of integers identifying CPUs.
6481[clinic start generated code]*/
6482
Larry Hastings2f936352014-08-05 14:04:04 +10006483static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006484os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
6485/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006486{
Antoine Pitrou84869872012-08-04 16:16:35 +02006487 int ncpus;
6488 size_t setsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006489 cpu_set_t *cpu_set = NULL;
6490 PyObject *iterator = NULL, *item;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006491
Larry Hastings2f936352014-08-05 14:04:04 +10006492 iterator = PyObject_GetIter(mask);
Antoine Pitrou84869872012-08-04 16:16:35 +02006493 if (iterator == NULL)
6494 return NULL;
6495
6496 ncpus = NCPUS_START;
6497 setsize = CPU_ALLOC_SIZE(ncpus);
Larry Hastings2f936352014-08-05 14:04:04 +10006498 cpu_set = CPU_ALLOC(ncpus);
6499 if (cpu_set == NULL) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006500 PyErr_NoMemory();
6501 goto error;
6502 }
Larry Hastings2f936352014-08-05 14:04:04 +10006503 CPU_ZERO_S(setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006504
6505 while ((item = PyIter_Next(iterator))) {
6506 long cpu;
6507 if (!PyLong_Check(item)) {
6508 PyErr_Format(PyExc_TypeError,
6509 "expected an iterator of ints, "
6510 "but iterator yielded %R",
6511 Py_TYPE(item));
6512 Py_DECREF(item);
6513 goto error;
6514 }
6515 cpu = PyLong_AsLong(item);
6516 Py_DECREF(item);
6517 if (cpu < 0) {
6518 if (!PyErr_Occurred())
6519 PyErr_SetString(PyExc_ValueError, "negative CPU number");
6520 goto error;
6521 }
6522 if (cpu > INT_MAX - 1) {
6523 PyErr_SetString(PyExc_OverflowError, "CPU number too large");
6524 goto error;
6525 }
6526 if (cpu >= ncpus) {
6527 /* Grow CPU mask to fit the CPU number */
6528 int newncpus = ncpus;
6529 cpu_set_t *newmask;
6530 size_t newsetsize;
6531 while (newncpus <= cpu) {
6532 if (newncpus > INT_MAX / 2)
6533 newncpus = cpu + 1;
6534 else
6535 newncpus = newncpus * 2;
6536 }
6537 newmask = CPU_ALLOC(newncpus);
6538 if (newmask == NULL) {
6539 PyErr_NoMemory();
6540 goto error;
6541 }
6542 newsetsize = CPU_ALLOC_SIZE(newncpus);
6543 CPU_ZERO_S(newsetsize, newmask);
Larry Hastings2f936352014-08-05 14:04:04 +10006544 memcpy(newmask, cpu_set, setsize);
6545 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006546 setsize = newsetsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006547 cpu_set = newmask;
Antoine Pitrou84869872012-08-04 16:16:35 +02006548 ncpus = newncpus;
6549 }
Larry Hastings2f936352014-08-05 14:04:04 +10006550 CPU_SET_S(cpu, setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006551 }
Brandt Bucher45a30af2019-06-27 09:10:57 -07006552 if (PyErr_Occurred()) {
6553 goto error;
6554 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006555 Py_CLEAR(iterator);
6556
Larry Hastings2f936352014-08-05 14:04:04 +10006557 if (sched_setaffinity(pid, setsize, cpu_set)) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006558 posix_error();
6559 goto error;
6560 }
Larry Hastings2f936352014-08-05 14:04:04 +10006561 CPU_FREE(cpu_set);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006562 Py_RETURN_NONE;
Antoine Pitrou84869872012-08-04 16:16:35 +02006563
6564error:
Larry Hastings2f936352014-08-05 14:04:04 +10006565 if (cpu_set)
6566 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006567 Py_XDECREF(iterator);
6568 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006569}
6570
Larry Hastings2f936352014-08-05 14:04:04 +10006571
6572/*[clinic input]
6573os.sched_getaffinity
6574 pid: pid_t
6575 /
6576
Charles-François Natalidc87e4b2015-07-13 21:01:39 +01006577Return the affinity of the process identified by pid (or the current process if zero).
Larry Hastings2f936352014-08-05 14:04:04 +10006578
6579The affinity is returned as a set of CPU identifiers.
6580[clinic start generated code]*/
6581
Larry Hastings2f936352014-08-05 14:04:04 +10006582static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006583os_sched_getaffinity_impl(PyObject *module, pid_t pid)
Serhiy Storchaka2954f832016-07-07 18:20:03 +03006584/*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006585{
Antoine Pitrou84869872012-08-04 16:16:35 +02006586 int cpu, ncpus, count;
6587 size_t setsize;
6588 cpu_set_t *mask = NULL;
6589 PyObject *res = NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006590
Antoine Pitrou84869872012-08-04 16:16:35 +02006591 ncpus = NCPUS_START;
6592 while (1) {
6593 setsize = CPU_ALLOC_SIZE(ncpus);
6594 mask = CPU_ALLOC(ncpus);
6595 if (mask == NULL)
6596 return PyErr_NoMemory();
6597 if (sched_getaffinity(pid, setsize, mask) == 0)
6598 break;
6599 CPU_FREE(mask);
6600 if (errno != EINVAL)
6601 return posix_error();
6602 if (ncpus > INT_MAX / 2) {
6603 PyErr_SetString(PyExc_OverflowError, "could not allocate "
6604 "a large enough CPU set");
6605 return NULL;
6606 }
6607 ncpus = ncpus * 2;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006608 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006609
6610 res = PySet_New(NULL);
6611 if (res == NULL)
6612 goto error;
6613 for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
6614 if (CPU_ISSET_S(cpu, setsize, mask)) {
6615 PyObject *cpu_num = PyLong_FromLong(cpu);
6616 --count;
6617 if (cpu_num == NULL)
6618 goto error;
6619 if (PySet_Add(res, cpu_num)) {
6620 Py_DECREF(cpu_num);
6621 goto error;
6622 }
6623 Py_DECREF(cpu_num);
6624 }
6625 }
6626 CPU_FREE(mask);
6627 return res;
6628
6629error:
6630 if (mask)
6631 CPU_FREE(mask);
6632 Py_XDECREF(res);
6633 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006634}
6635
Benjamin Peterson2740af82011-08-02 17:41:34 -05006636#endif /* HAVE_SCHED_SETAFFINITY */
6637
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006638#endif /* HAVE_SCHED_H */
6639
Larry Hastings2f936352014-08-05 14:04:04 +10006640
Neal Norwitzb59798b2003-03-21 01:43:31 +00006641/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
Neal Norwitz2deaddb2003-03-21 03:08:31 +00006642/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
6643#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
Neal Norwitzb59798b2003-03-21 01:43:31 +00006644#define DEV_PTY_FILE "/dev/ptc"
6645#define HAVE_DEV_PTMX
6646#else
6647#define DEV_PTY_FILE "/dev/ptmx"
6648#endif
6649
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006650#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
Fred Drake8cef4cf2000-06-28 16:40:38 +00006651#ifdef HAVE_PTY_H
6652#include <pty.h>
6653#else
6654#ifdef HAVE_LIBUTIL_H
6655#include <libutil.h>
Ronald Oussoren755740f2010-02-07 19:56:39 +00006656#else
6657#ifdef HAVE_UTIL_H
6658#include <util.h>
6659#endif /* HAVE_UTIL_H */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006660#endif /* HAVE_LIBUTIL_H */
6661#endif /* HAVE_PTY_H */
Martin v. Löwis14e73b12003-01-01 09:51:12 +00006662#ifdef HAVE_STROPTS_H
6663#include <stropts.h>
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006664#endif
ngie-eign7745ec42018-02-14 11:54:28 -08006665#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006666
Larry Hastings2f936352014-08-05 14:04:04 +10006667
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006668#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
Larry Hastings2f936352014-08-05 14:04:04 +10006669/*[clinic input]
6670os.openpty
6671
6672Open a pseudo-terminal.
6673
6674Return a tuple of (master_fd, slave_fd) containing open file descriptors
6675for both the master and slave ends.
6676[clinic start generated code]*/
6677
Larry Hastings2f936352014-08-05 14:04:04 +10006678static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006679os_openpty_impl(PyObject *module)
6680/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006681{
Victor Stinnerdaf45552013-08-28 00:53:59 +02006682 int master_fd = -1, slave_fd = -1;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006683#ifndef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006684 char * slave_name;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006685#endif
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006686#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006687 PyOS_sighandler_t sig_saved;
Jakub Kulík6f9bc722018-12-31 03:16:40 +01006688#if defined(__sun) && defined(__SVR4)
Victor Stinner8c62be82010-05-06 00:08:46 +00006689 extern char *ptsname(int fildes);
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006690#endif
6691#endif
Thomas Wouters70c21a12000-07-14 14:28:33 +00006692
Thomas Wouters70c21a12000-07-14 14:28:33 +00006693#ifdef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006694 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006695 goto posix_error;
6696
6697 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6698 goto error;
6699 if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
6700 goto error;
6701
Neal Norwitzb59798b2003-03-21 01:43:31 +00006702#elif defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006703 slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
6704 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006705 goto posix_error;
6706 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6707 goto error;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006708
Victor Stinnerdaf45552013-08-28 00:53:59 +02006709 slave_fd = _Py_open(slave_name, O_RDWR);
Victor Stinner8c62be82010-05-06 00:08:46 +00006710 if (slave_fd < 0)
Victor Stinnera555cfc2015-03-18 00:22:14 +01006711 goto error;
Victor Stinnerdaf45552013-08-28 00:53:59 +02006712
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006713#else
Victor Stinner000de532013-11-25 23:19:58 +01006714 master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
Victor Stinner8c62be82010-05-06 00:08:46 +00006715 if (master_fd < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006716 goto posix_error;
6717
Victor Stinner8c62be82010-05-06 00:08:46 +00006718 sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006719
Victor Stinner8c62be82010-05-06 00:08:46 +00006720 /* change permission of slave */
6721 if (grantpt(master_fd) < 0) {
6722 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006723 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006724 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006725
Victor Stinner8c62be82010-05-06 00:08:46 +00006726 /* unlock slave */
6727 if (unlockpt(master_fd) < 0) {
6728 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006729 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006730 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006731
Victor Stinner8c62be82010-05-06 00:08:46 +00006732 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006733
Victor Stinner8c62be82010-05-06 00:08:46 +00006734 slave_name = ptsname(master_fd); /* get name of slave */
6735 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006736 goto posix_error;
6737
6738 slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
Victor Stinnera555cfc2015-03-18 00:22:14 +01006739 if (slave_fd == -1)
6740 goto error;
Victor Stinner000de532013-11-25 23:19:58 +01006741
6742 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6743 goto posix_error;
6744
Stefan Krahfb7c8ae2016-04-26 17:04:18 +02006745#if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
Victor Stinner8c62be82010-05-06 00:08:46 +00006746 ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
6747 ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
Neal Norwitz6700e472002-12-31 16:16:07 +00006748#ifndef __hpux
Victor Stinner8c62be82010-05-06 00:08:46 +00006749 ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
Neal Norwitz6700e472002-12-31 16:16:07 +00006750#endif /* __hpux */
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006751#endif /* HAVE_CYGWIN */
Thomas Wouters1e0c2f42000-07-24 16:06:23 +00006752#endif /* HAVE_OPENPTY */
Thomas Wouters70c21a12000-07-14 14:28:33 +00006753
Victor Stinner8c62be82010-05-06 00:08:46 +00006754 return Py_BuildValue("(ii)", master_fd, slave_fd);
Thomas Wouters70c21a12000-07-14 14:28:33 +00006755
Victor Stinnerdaf45552013-08-28 00:53:59 +02006756posix_error:
6757 posix_error();
6758error:
6759 if (master_fd != -1)
6760 close(master_fd);
6761 if (slave_fd != -1)
6762 close(slave_fd);
6763 return NULL;
Fred Drake8cef4cf2000-06-28 16:40:38 +00006764}
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006765#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006766
Larry Hastings2f936352014-08-05 14:04:04 +10006767
Fred Drake8cef4cf2000-06-28 16:40:38 +00006768#ifdef HAVE_FORKPTY
Larry Hastings2f936352014-08-05 14:04:04 +10006769/*[clinic input]
6770os.forkpty
6771
6772Fork a new process with a new pseudo-terminal as controlling tty.
6773
6774Returns a tuple of (pid, master_fd).
6775Like fork(), return pid of 0 to the child process,
6776and pid of child to the parent process.
6777To both, return fd of newly opened pseudo-terminal.
6778[clinic start generated code]*/
6779
Larry Hastings2f936352014-08-05 14:04:04 +10006780static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006781os_forkpty_impl(PyObject *module)
6782/*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006783{
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006784 int master_fd = -1;
Victor Stinner8c62be82010-05-06 00:08:46 +00006785 pid_t pid;
Tim Peters5aa91602002-01-30 05:46:57 +00006786
Eric Snow59032962018-09-14 14:17:20 -07006787 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6788 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6789 return NULL;
6790 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006791 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006792 pid = forkpty(&master_fd, NULL, NULL, NULL);
6793 if (pid == 0) {
6794 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006795 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006796 } else {
6797 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006798 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006799 }
6800 if (pid == -1)
6801 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006802 return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
Fred Drake8cef4cf2000-06-28 16:40:38 +00006803}
Larry Hastings2f936352014-08-05 14:04:04 +10006804#endif /* HAVE_FORKPTY */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006805
Ross Lagerwall7807c352011-03-17 20:20:30 +02006806
Guido van Rossumad0ee831995-03-01 10:34:45 +00006807#ifdef HAVE_GETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10006808/*[clinic input]
6809os.getegid
6810
6811Return the current process's effective group id.
6812[clinic start generated code]*/
6813
Larry Hastings2f936352014-08-05 14:04:04 +10006814static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006815os_getegid_impl(PyObject *module)
6816/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006817{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006818 return _PyLong_FromGid(getegid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006819}
Larry Hastings2f936352014-08-05 14:04:04 +10006820#endif /* HAVE_GETEGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006821
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006822
Guido van Rossumad0ee831995-03-01 10:34:45 +00006823#ifdef HAVE_GETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10006824/*[clinic input]
6825os.geteuid
6826
6827Return the current process's effective user id.
6828[clinic start generated code]*/
6829
Larry Hastings2f936352014-08-05 14:04:04 +10006830static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006831os_geteuid_impl(PyObject *module)
6832/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006833{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006834 return _PyLong_FromUid(geteuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006835}
Larry Hastings2f936352014-08-05 14:04:04 +10006836#endif /* HAVE_GETEUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006837
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006838
Guido van Rossumad0ee831995-03-01 10:34:45 +00006839#ifdef HAVE_GETGID
Larry Hastings2f936352014-08-05 14:04:04 +10006840/*[clinic input]
6841os.getgid
6842
6843Return the current process's group id.
6844[clinic start generated code]*/
6845
Larry Hastings2f936352014-08-05 14:04:04 +10006846static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006847os_getgid_impl(PyObject *module)
6848/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006849{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006850 return _PyLong_FromGid(getgid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006851}
Larry Hastings2f936352014-08-05 14:04:04 +10006852#endif /* HAVE_GETGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006853
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006854
Berker Peksag39404992016-09-15 20:45:16 +03006855#ifdef HAVE_GETPID
Larry Hastings2f936352014-08-05 14:04:04 +10006856/*[clinic input]
6857os.getpid
6858
6859Return the current process id.
6860[clinic start generated code]*/
6861
Larry Hastings2f936352014-08-05 14:04:04 +10006862static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006863os_getpid_impl(PyObject *module)
6864/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006865{
Victor Stinner8c62be82010-05-06 00:08:46 +00006866 return PyLong_FromPid(getpid());
Guido van Rossum85e3b011991-06-03 12:42:10 +00006867}
Berker Peksag39404992016-09-15 20:45:16 +03006868#endif /* HAVE_GETPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00006869
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07006870#ifdef NGROUPS_MAX
6871#define MAX_GROUPS NGROUPS_MAX
6872#else
6873 /* defined to be 16 on Solaris7, so this should be a small number */
6874#define MAX_GROUPS 64
6875#endif
6876
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006877#ifdef HAVE_GETGROUPLIST
Larry Hastings2f936352014-08-05 14:04:04 +10006878
6879/* AC 3.5: funny apple logic below */
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006880PyDoc_STRVAR(posix_getgrouplist__doc__,
6881"getgrouplist(user, group) -> list of groups to which a user belongs\n\n\
6882Returns a list of groups to which a user belongs.\n\n\
6883 user: username to lookup\n\
6884 group: base group id of the user");
6885
6886static PyObject *
6887posix_getgrouplist(PyObject *self, PyObject *args)
6888{
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006889 const char *user;
6890 int i, ngroups;
6891 PyObject *list;
6892#ifdef __APPLE__
6893 int *groups, basegid;
6894#else
6895 gid_t *groups, basegid;
6896#endif
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07006897
6898 /*
6899 * NGROUPS_MAX is defined by POSIX.1 as the maximum
6900 * number of supplimental groups a users can belong to.
6901 * We have to increment it by one because
6902 * getgrouplist() returns both the supplemental groups
6903 * and the primary group, i.e. all of the groups the
6904 * user belongs to.
6905 */
6906 ngroups = 1 + MAX_GROUPS;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006907
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006908#ifdef __APPLE__
6909 if (!PyArg_ParseTuple(args, "si:getgrouplist", &user, &basegid))
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006910 return NULL;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006911#else
6912 if (!PyArg_ParseTuple(args, "sO&:getgrouplist", &user,
6913 _Py_Gid_Converter, &basegid))
6914 return NULL;
6915#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006916
6917#ifdef __APPLE__
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006918 groups = PyMem_New(int, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006919#else
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006920 groups = PyMem_New(gid_t, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006921#endif
6922 if (groups == NULL)
6923 return PyErr_NoMemory();
6924
6925 if (getgrouplist(user, basegid, groups, &ngroups) == -1) {
6926 PyMem_Del(groups);
6927 return posix_error();
6928 }
6929
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006930#ifdef _Py_MEMORY_SANITIZER
6931 /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
6932 __msan_unpoison(&ngroups, sizeof(ngroups));
6933 __msan_unpoison(groups, ngroups*sizeof(*groups));
6934#endif
6935
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006936 list = PyList_New(ngroups);
6937 if (list == NULL) {
6938 PyMem_Del(groups);
6939 return NULL;
6940 }
6941
6942 for (i = 0; i < ngroups; i++) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006943#ifdef __APPLE__
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006944 PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006945#else
6946 PyObject *o = _PyLong_FromGid(groups[i]);
6947#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006948 if (o == NULL) {
6949 Py_DECREF(list);
6950 PyMem_Del(groups);
6951 return NULL;
6952 }
6953 PyList_SET_ITEM(list, i, o);
6954 }
6955
6956 PyMem_Del(groups);
6957
6958 return list;
6959}
Larry Hastings2f936352014-08-05 14:04:04 +10006960#endif /* HAVE_GETGROUPLIST */
6961
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006962
Fred Drakec9680921999-12-13 16:37:25 +00006963#ifdef HAVE_GETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10006964/*[clinic input]
6965os.getgroups
6966
6967Return list of supplemental group IDs for the process.
6968[clinic start generated code]*/
6969
Larry Hastings2f936352014-08-05 14:04:04 +10006970static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006971os_getgroups_impl(PyObject *module)
6972/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
Fred Drakec9680921999-12-13 16:37:25 +00006973{
6974 PyObject *result = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00006975 gid_t grouplist[MAX_GROUPS];
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006976
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00006977 /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006978 * This is a helper variable to store the intermediate result when
6979 * that happens.
6980 *
6981 * To keep the code readable the OSX behaviour is unconditional,
6982 * according to the POSIX spec this should be safe on all unix-y
6983 * systems.
6984 */
6985 gid_t* alt_grouplist = grouplist;
Victor Stinner8c62be82010-05-06 00:08:46 +00006986 int n;
Fred Drakec9680921999-12-13 16:37:25 +00006987
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006988#ifdef __APPLE__
6989 /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
6990 * there are more groups than can fit in grouplist. Therefore, on OS X
6991 * always first call getgroups with length 0 to get the actual number
6992 * of groups.
6993 */
6994 n = getgroups(0, NULL);
6995 if (n < 0) {
6996 return posix_error();
6997 } else if (n <= MAX_GROUPS) {
6998 /* groups will fit in existing array */
6999 alt_grouplist = grouplist;
7000 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02007001 alt_grouplist = PyMem_New(gid_t, n);
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007002 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07007003 return PyErr_NoMemory();
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007004 }
7005 }
7006
7007 n = getgroups(n, alt_grouplist);
7008 if (n == -1) {
7009 if (alt_grouplist != grouplist) {
7010 PyMem_Free(alt_grouplist);
7011 }
7012 return posix_error();
7013 }
7014#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007015 n = getgroups(MAX_GROUPS, grouplist);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007016 if (n < 0) {
7017 if (errno == EINVAL) {
7018 n = getgroups(0, NULL);
7019 if (n == -1) {
7020 return posix_error();
7021 }
7022 if (n == 0) {
7023 /* Avoid malloc(0) */
7024 alt_grouplist = grouplist;
7025 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02007026 alt_grouplist = PyMem_New(gid_t, n);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007027 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07007028 return PyErr_NoMemory();
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007029 }
7030 n = getgroups(n, alt_grouplist);
7031 if (n == -1) {
7032 PyMem_Free(alt_grouplist);
7033 return posix_error();
7034 }
7035 }
7036 } else {
7037 return posix_error();
7038 }
7039 }
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007040#endif
7041
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007042 result = PyList_New(n);
7043 if (result != NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007044 int i;
7045 for (i = 0; i < n; ++i) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007046 PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
Victor Stinner8c62be82010-05-06 00:08:46 +00007047 if (o == NULL) {
Stefan Krah0e803b32010-11-26 16:16:47 +00007048 Py_DECREF(result);
7049 result = NULL;
7050 break;
Fred Drakec9680921999-12-13 16:37:25 +00007051 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007052 PyList_SET_ITEM(result, i, o);
Fred Drakec9680921999-12-13 16:37:25 +00007053 }
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007054 }
7055
7056 if (alt_grouplist != grouplist) {
7057 PyMem_Free(alt_grouplist);
Victor Stinner8c62be82010-05-06 00:08:46 +00007058 }
Neal Norwitze241ce82003-02-17 18:17:05 +00007059
Fred Drakec9680921999-12-13 16:37:25 +00007060 return result;
7061}
Larry Hastings2f936352014-08-05 14:04:04 +10007062#endif /* HAVE_GETGROUPS */
Fred Drakec9680921999-12-13 16:37:25 +00007063
Antoine Pitroub7572f02009-12-02 20:46:48 +00007064#ifdef HAVE_INITGROUPS
7065PyDoc_STRVAR(posix_initgroups__doc__,
7066"initgroups(username, gid) -> None\n\n\
7067Call the system initgroups() to initialize the group access list with all of\n\
7068the groups of which the specified username is a member, plus the specified\n\
7069group id.");
7070
Larry Hastings2f936352014-08-05 14:04:04 +10007071/* AC 3.5: funny apple logic */
Antoine Pitroub7572f02009-12-02 20:46:48 +00007072static PyObject *
7073posix_initgroups(PyObject *self, PyObject *args)
7074{
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007075 PyObject *oname;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03007076 const char *username;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007077 int res;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007078#ifdef __APPLE__
7079 int gid;
7080#else
7081 gid_t gid;
7082#endif
Antoine Pitroub7572f02009-12-02 20:46:48 +00007083
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007084#ifdef __APPLE__
7085 if (!PyArg_ParseTuple(args, "O&i:initgroups",
7086 PyUnicode_FSConverter, &oname,
7087 &gid))
7088#else
7089 if (!PyArg_ParseTuple(args, "O&O&:initgroups",
7090 PyUnicode_FSConverter, &oname,
7091 _Py_Gid_Converter, &gid))
7092#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00007093 return NULL;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007094 username = PyBytes_AS_STRING(oname);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007095
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007096 res = initgroups(username, gid);
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007097 Py_DECREF(oname);
7098 if (res == -1)
Victor Stinner8c62be82010-05-06 00:08:46 +00007099 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007100
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007101 Py_RETURN_NONE;
Antoine Pitroub7572f02009-12-02 20:46:48 +00007102}
Larry Hastings2f936352014-08-05 14:04:04 +10007103#endif /* HAVE_INITGROUPS */
7104
Antoine Pitroub7572f02009-12-02 20:46:48 +00007105
Martin v. Löwis606edc12002-06-13 21:09:11 +00007106#ifdef HAVE_GETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10007107/*[clinic input]
7108os.getpgid
7109
7110 pid: pid_t
7111
7112Call the system call getpgid(), and return the result.
7113[clinic start generated code]*/
7114
Larry Hastings2f936352014-08-05 14:04:04 +10007115static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007116os_getpgid_impl(PyObject *module, pid_t pid)
7117/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007118{
7119 pid_t pgid = getpgid(pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007120 if (pgid < 0)
7121 return posix_error();
7122 return PyLong_FromPid(pgid);
Martin v. Löwis606edc12002-06-13 21:09:11 +00007123}
7124#endif /* HAVE_GETPGID */
7125
7126
Guido van Rossumb6775db1994-08-01 11:34:53 +00007127#ifdef HAVE_GETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007128/*[clinic input]
7129os.getpgrp
7130
7131Return the current process group id.
7132[clinic start generated code]*/
7133
Larry Hastings2f936352014-08-05 14:04:04 +10007134static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007135os_getpgrp_impl(PyObject *module)
7136/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
Guido van Rossum04814471991-06-04 20:23:49 +00007137{
Guido van Rossumb6775db1994-08-01 11:34:53 +00007138#ifdef GETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007139 return PyLong_FromPid(getpgrp(0));
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007140#else /* GETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007141 return PyLong_FromPid(getpgrp());
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007142#endif /* GETPGRP_HAVE_ARG */
Guido van Rossum04814471991-06-04 20:23:49 +00007143}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007144#endif /* HAVE_GETPGRP */
Guido van Rossum04814471991-06-04 20:23:49 +00007145
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007146
Guido van Rossumb6775db1994-08-01 11:34:53 +00007147#ifdef HAVE_SETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007148/*[clinic input]
7149os.setpgrp
7150
7151Make the current process the leader of its process group.
7152[clinic start generated code]*/
7153
Larry Hastings2f936352014-08-05 14:04:04 +10007154static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007155os_setpgrp_impl(PyObject *module)
7156/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00007157{
Guido van Rossum64933891994-10-20 21:56:42 +00007158#ifdef SETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007159 if (setpgrp(0, 0) < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007160#else /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007161 if (setpgrp() < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007162#endif /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007163 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007164 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00007165}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007166#endif /* HAVE_SETPGRP */
7167
Guido van Rossumad0ee831995-03-01 10:34:45 +00007168#ifdef HAVE_GETPPID
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007169
7170#ifdef MS_WINDOWS
7171#include <tlhelp32.h>
7172
7173static PyObject*
7174win32_getppid()
7175{
7176 HANDLE snapshot;
7177 pid_t mypid;
7178 PyObject* result = NULL;
7179 BOOL have_record;
7180 PROCESSENTRY32 pe;
7181
7182 mypid = getpid(); /* This function never fails */
7183
7184 snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
7185 if (snapshot == INVALID_HANDLE_VALUE)
7186 return PyErr_SetFromWindowsErr(GetLastError());
7187
7188 pe.dwSize = sizeof(pe);
7189 have_record = Process32First(snapshot, &pe);
7190 while (have_record) {
7191 if (mypid == (pid_t)pe.th32ProcessID) {
7192 /* We could cache the ulong value in a static variable. */
7193 result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
7194 break;
7195 }
7196
7197 have_record = Process32Next(snapshot, &pe);
7198 }
7199
7200 /* If our loop exits and our pid was not found (result will be NULL)
7201 * then GetLastError will return ERROR_NO_MORE_FILES. This is an
7202 * error anyway, so let's raise it. */
7203 if (!result)
7204 result = PyErr_SetFromWindowsErr(GetLastError());
7205
7206 CloseHandle(snapshot);
7207
7208 return result;
7209}
7210#endif /*MS_WINDOWS*/
7211
Larry Hastings2f936352014-08-05 14:04:04 +10007212
7213/*[clinic input]
7214os.getppid
7215
7216Return the parent's process id.
7217
7218If the parent process has already exited, Windows machines will still
7219return its id; others systems will return the id of the 'init' process (1).
7220[clinic start generated code]*/
7221
Larry Hastings2f936352014-08-05 14:04:04 +10007222static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007223os_getppid_impl(PyObject *module)
7224/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00007225{
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007226#ifdef MS_WINDOWS
7227 return win32_getppid();
7228#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007229 return PyLong_FromPid(getppid());
Guido van Rossumad0ee831995-03-01 10:34:45 +00007230#endif
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007231}
7232#endif /* HAVE_GETPPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007233
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007234
Fred Drake12c6e2d1999-12-14 21:25:03 +00007235#ifdef HAVE_GETLOGIN
Larry Hastings2f936352014-08-05 14:04:04 +10007236/*[clinic input]
7237os.getlogin
7238
7239Return the actual login name.
7240[clinic start generated code]*/
7241
Larry Hastings2f936352014-08-05 14:04:04 +10007242static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007243os_getlogin_impl(PyObject *module)
7244/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
Fred Drake12c6e2d1999-12-14 21:25:03 +00007245{
Victor Stinner8c62be82010-05-06 00:08:46 +00007246 PyObject *result = NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007247#ifdef MS_WINDOWS
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007248 wchar_t user_name[UNLEN + 1];
Victor Stinner63941882011-09-29 00:42:28 +02007249 DWORD num_chars = Py_ARRAY_LENGTH(user_name);
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007250
7251 if (GetUserNameW(user_name, &num_chars)) {
7252 /* num_chars is the number of unicode chars plus null terminator */
7253 result = PyUnicode_FromWideChar(user_name, num_chars - 1);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007254 }
7255 else
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007256 result = PyErr_SetFromWindowsErr(GetLastError());
7257#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007258 char *name;
7259 int old_errno = errno;
Fred Drake12c6e2d1999-12-14 21:25:03 +00007260
Victor Stinner8c62be82010-05-06 00:08:46 +00007261 errno = 0;
7262 name = getlogin();
7263 if (name == NULL) {
7264 if (errno)
Victor Stinnere039ffe2010-08-15 09:33:08 +00007265 posix_error();
Fred Drake12c6e2d1999-12-14 21:25:03 +00007266 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007267 PyErr_SetString(PyExc_OSError, "unable to determine login name");
Victor Stinner8c62be82010-05-06 00:08:46 +00007268 }
7269 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007270 result = PyUnicode_DecodeFSDefault(name);
Victor Stinner8c62be82010-05-06 00:08:46 +00007271 errno = old_errno;
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007272#endif
Fred Drake12c6e2d1999-12-14 21:25:03 +00007273 return result;
7274}
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007275#endif /* HAVE_GETLOGIN */
Fred Drake12c6e2d1999-12-14 21:25:03 +00007276
Larry Hastings2f936352014-08-05 14:04:04 +10007277
Guido van Rossumad0ee831995-03-01 10:34:45 +00007278#ifdef HAVE_GETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007279/*[clinic input]
7280os.getuid
7281
7282Return the current process's user id.
7283[clinic start generated code]*/
7284
Larry Hastings2f936352014-08-05 14:04:04 +10007285static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007286os_getuid_impl(PyObject *module)
7287/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00007288{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007289 return _PyLong_FromUid(getuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00007290}
Larry Hastings2f936352014-08-05 14:04:04 +10007291#endif /* HAVE_GETUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00007292
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007293
Brian Curtineb24d742010-04-12 17:16:38 +00007294#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007295#define HAVE_KILL
7296#endif /* MS_WINDOWS */
7297
7298#ifdef HAVE_KILL
7299/*[clinic input]
7300os.kill
7301
7302 pid: pid_t
7303 signal: Py_ssize_t
7304 /
7305
7306Kill a process with a signal.
7307[clinic start generated code]*/
7308
Larry Hastings2f936352014-08-05 14:04:04 +10007309static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007310os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
7311/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007312#ifndef MS_WINDOWS
7313{
7314 if (kill(pid, (int)signal) == -1)
7315 return posix_error();
7316 Py_RETURN_NONE;
7317}
7318#else /* !MS_WINDOWS */
Brian Curtineb24d742010-04-12 17:16:38 +00007319{
Amaury Forgeot d'Arc0a589c92010-05-15 20:35:12 +00007320 PyObject *result;
Larry Hastings2f936352014-08-05 14:04:04 +10007321 DWORD sig = (DWORD)signal;
7322 DWORD err;
Victor Stinner8c62be82010-05-06 00:08:46 +00007323 HANDLE handle;
Brian Curtineb24d742010-04-12 17:16:38 +00007324
Victor Stinner8c62be82010-05-06 00:08:46 +00007325 /* Console processes which share a common console can be sent CTRL+C or
7326 CTRL+BREAK events, provided they handle said events. */
7327 if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007328 if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007329 err = GetLastError();
7330 PyErr_SetFromWindowsErr(err);
7331 }
7332 else
7333 Py_RETURN_NONE;
7334 }
Brian Curtineb24d742010-04-12 17:16:38 +00007335
Victor Stinner8c62be82010-05-06 00:08:46 +00007336 /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
7337 attempt to open and terminate the process. */
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007338 handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007339 if (handle == NULL) {
7340 err = GetLastError();
7341 return PyErr_SetFromWindowsErr(err);
7342 }
Brian Curtineb24d742010-04-12 17:16:38 +00007343
Victor Stinner8c62be82010-05-06 00:08:46 +00007344 if (TerminateProcess(handle, sig) == 0) {
7345 err = GetLastError();
7346 result = PyErr_SetFromWindowsErr(err);
7347 } else {
7348 Py_INCREF(Py_None);
7349 result = Py_None;
7350 }
Brian Curtineb24d742010-04-12 17:16:38 +00007351
Victor Stinner8c62be82010-05-06 00:08:46 +00007352 CloseHandle(handle);
7353 return result;
Brian Curtineb24d742010-04-12 17:16:38 +00007354}
Larry Hastings2f936352014-08-05 14:04:04 +10007355#endif /* !MS_WINDOWS */
7356#endif /* HAVE_KILL */
7357
7358
7359#ifdef HAVE_KILLPG
7360/*[clinic input]
7361os.killpg
7362
7363 pgid: pid_t
7364 signal: int
7365 /
7366
7367Kill a process group with a signal.
7368[clinic start generated code]*/
7369
Larry Hastings2f936352014-08-05 14:04:04 +10007370static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007371os_killpg_impl(PyObject *module, pid_t pgid, int signal)
7372/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007373{
7374 /* XXX some man pages make the `pgid` parameter an int, others
7375 a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
7376 take the same type. Moreover, pid_t is always at least as wide as
7377 int (else compilation of this module fails), which is safe. */
7378 if (killpg(pgid, signal) == -1)
7379 return posix_error();
7380 Py_RETURN_NONE;
7381}
7382#endif /* HAVE_KILLPG */
7383
Brian Curtineb24d742010-04-12 17:16:38 +00007384
Guido van Rossumc0125471996-06-28 18:55:32 +00007385#ifdef HAVE_PLOCK
Guido van Rossumc0125471996-06-28 18:55:32 +00007386#ifdef HAVE_SYS_LOCK_H
7387#include <sys/lock.h>
7388#endif
7389
Larry Hastings2f936352014-08-05 14:04:04 +10007390/*[clinic input]
7391os.plock
7392 op: int
7393 /
7394
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007395Lock program segments into memory.");
Larry Hastings2f936352014-08-05 14:04:04 +10007396[clinic start generated code]*/
7397
Larry Hastings2f936352014-08-05 14:04:04 +10007398static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007399os_plock_impl(PyObject *module, int op)
7400/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007401{
Victor Stinner8c62be82010-05-06 00:08:46 +00007402 if (plock(op) == -1)
7403 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007404 Py_RETURN_NONE;
Guido van Rossumc0125471996-06-28 18:55:32 +00007405}
Larry Hastings2f936352014-08-05 14:04:04 +10007406#endif /* HAVE_PLOCK */
7407
Guido van Rossumc0125471996-06-28 18:55:32 +00007408
Guido van Rossumb6775db1994-08-01 11:34:53 +00007409#ifdef HAVE_SETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007410/*[clinic input]
7411os.setuid
7412
7413 uid: uid_t
7414 /
7415
7416Set the current process's user id.
7417[clinic start generated code]*/
7418
Larry Hastings2f936352014-08-05 14:04:04 +10007419static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007420os_setuid_impl(PyObject *module, uid_t uid)
7421/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007422{
Victor Stinner8c62be82010-05-06 00:08:46 +00007423 if (setuid(uid) < 0)
7424 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007425 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007426}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007427#endif /* HAVE_SETUID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007428
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007429
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007430#ifdef HAVE_SETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10007431/*[clinic input]
7432os.seteuid
7433
7434 euid: uid_t
7435 /
7436
7437Set the current process's effective user id.
7438[clinic start generated code]*/
7439
Larry Hastings2f936352014-08-05 14:04:04 +10007440static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007441os_seteuid_impl(PyObject *module, uid_t euid)
7442/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007443{
7444 if (seteuid(euid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007445 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007446 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007447}
7448#endif /* HAVE_SETEUID */
7449
Larry Hastings2f936352014-08-05 14:04:04 +10007450
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007451#ifdef HAVE_SETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10007452/*[clinic input]
7453os.setegid
7454
7455 egid: gid_t
7456 /
7457
7458Set the current process's effective group id.
7459[clinic start generated code]*/
7460
Larry Hastings2f936352014-08-05 14:04:04 +10007461static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007462os_setegid_impl(PyObject *module, gid_t egid)
7463/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007464{
7465 if (setegid(egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007466 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007467 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007468}
7469#endif /* HAVE_SETEGID */
7470
Larry Hastings2f936352014-08-05 14:04:04 +10007471
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007472#ifdef HAVE_SETREUID
Larry Hastings2f936352014-08-05 14:04:04 +10007473/*[clinic input]
7474os.setreuid
7475
7476 ruid: uid_t
7477 euid: uid_t
7478 /
7479
7480Set the current process's real and effective user ids.
7481[clinic start generated code]*/
7482
Larry Hastings2f936352014-08-05 14:04:04 +10007483static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007484os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
7485/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007486{
Victor Stinner8c62be82010-05-06 00:08:46 +00007487 if (setreuid(ruid, euid) < 0) {
7488 return posix_error();
7489 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007490 Py_RETURN_NONE;
Victor Stinner8c62be82010-05-06 00:08:46 +00007491 }
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007492}
7493#endif /* HAVE_SETREUID */
7494
Larry Hastings2f936352014-08-05 14:04:04 +10007495
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007496#ifdef HAVE_SETREGID
Larry Hastings2f936352014-08-05 14:04:04 +10007497/*[clinic input]
7498os.setregid
7499
7500 rgid: gid_t
7501 egid: gid_t
7502 /
7503
7504Set the current process's real and effective group ids.
7505[clinic start generated code]*/
7506
Larry Hastings2f936352014-08-05 14:04:04 +10007507static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007508os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
7509/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007510{
7511 if (setregid(rgid, egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007512 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007513 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007514}
7515#endif /* HAVE_SETREGID */
7516
Larry Hastings2f936352014-08-05 14:04:04 +10007517
Guido van Rossumb6775db1994-08-01 11:34:53 +00007518#ifdef HAVE_SETGID
Larry Hastings2f936352014-08-05 14:04:04 +10007519/*[clinic input]
7520os.setgid
7521 gid: gid_t
7522 /
7523
7524Set the current process's group id.
7525[clinic start generated code]*/
7526
Larry Hastings2f936352014-08-05 14:04:04 +10007527static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007528os_setgid_impl(PyObject *module, gid_t gid)
7529/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007530{
Victor Stinner8c62be82010-05-06 00:08:46 +00007531 if (setgid(gid) < 0)
7532 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007533 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007534}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007535#endif /* HAVE_SETGID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007536
Larry Hastings2f936352014-08-05 14:04:04 +10007537
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007538#ifdef HAVE_SETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007539/*[clinic input]
7540os.setgroups
7541
7542 groups: object
7543 /
7544
7545Set the groups of the current process to list.
7546[clinic start generated code]*/
7547
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007548static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007549os_setgroups(PyObject *module, PyObject *groups)
7550/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007551{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007552 Py_ssize_t i, len;
Victor Stinner8c62be82010-05-06 00:08:46 +00007553 gid_t grouplist[MAX_GROUPS];
Tim Peters5aa91602002-01-30 05:46:57 +00007554
Victor Stinner8c62be82010-05-06 00:08:46 +00007555 if (!PySequence_Check(groups)) {
7556 PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
7557 return NULL;
7558 }
7559 len = PySequence_Size(groups);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007560 if (len < 0) {
7561 return NULL;
7562 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007563 if (len > MAX_GROUPS) {
7564 PyErr_SetString(PyExc_ValueError, "too many groups");
7565 return NULL;
7566 }
7567 for(i = 0; i < len; i++) {
7568 PyObject *elem;
7569 elem = PySequence_GetItem(groups, i);
7570 if (!elem)
7571 return NULL;
7572 if (!PyLong_Check(elem)) {
7573 PyErr_SetString(PyExc_TypeError,
7574 "groups must be integers");
7575 Py_DECREF(elem);
7576 return NULL;
7577 } else {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007578 if (!_Py_Gid_Converter(elem, &grouplist[i])) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007579 Py_DECREF(elem);
7580 return NULL;
7581 }
7582 }
7583 Py_DECREF(elem);
7584 }
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007585
Victor Stinner8c62be82010-05-06 00:08:46 +00007586 if (setgroups(len, grouplist) < 0)
7587 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007588 Py_RETURN_NONE;
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007589}
7590#endif /* HAVE_SETGROUPS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007591
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007592#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
7593static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +01007594wait_helper(pid_t pid, int status, struct rusage *ru)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007595{
Victor Stinner8c62be82010-05-06 00:08:46 +00007596 PyObject *result;
Eddie Elizondob3966632019-11-05 07:16:14 -08007597 PyObject *struct_rusage;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007598
Victor Stinner8c62be82010-05-06 00:08:46 +00007599 if (pid == -1)
7600 return posix_error();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007601
Zackery Spytz682107c2019-09-09 09:48:32 -06007602 // If wait succeeded but no child was ready to report status, ru will not
7603 // have been populated.
7604 if (pid == 0) {
7605 memset(ru, 0, sizeof(*ru));
7606 }
7607
Eddie Elizondob3966632019-11-05 07:16:14 -08007608 PyObject *m = PyImport_ImportModuleNoBlock("resource");
7609 if (m == NULL)
7610 return NULL;
7611 struct_rusage = PyObject_GetAttr(m, _posixstate_global->struct_rusage);
7612 Py_DECREF(m);
7613 if (struct_rusage == NULL)
7614 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007615
Victor Stinner8c62be82010-05-06 00:08:46 +00007616 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
7617 result = PyStructSequence_New((PyTypeObject*) struct_rusage);
Eddie Elizondoe4db1f02019-11-25 19:07:37 -08007618 Py_DECREF(struct_rusage);
Victor Stinner8c62be82010-05-06 00:08:46 +00007619 if (!result)
7620 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007621
7622#ifndef doubletime
7623#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
7624#endif
7625
Victor Stinner8c62be82010-05-06 00:08:46 +00007626 PyStructSequence_SET_ITEM(result, 0,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007627 PyFloat_FromDouble(doubletime(ru->ru_utime)));
Victor Stinner8c62be82010-05-06 00:08:46 +00007628 PyStructSequence_SET_ITEM(result, 1,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007629 PyFloat_FromDouble(doubletime(ru->ru_stime)));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007630#define SET_INT(result, index, value)\
Victor Stinner8c62be82010-05-06 00:08:46 +00007631 PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
7632 SET_INT(result, 2, ru->ru_maxrss);
7633 SET_INT(result, 3, ru->ru_ixrss);
7634 SET_INT(result, 4, ru->ru_idrss);
7635 SET_INT(result, 5, ru->ru_isrss);
7636 SET_INT(result, 6, ru->ru_minflt);
7637 SET_INT(result, 7, ru->ru_majflt);
7638 SET_INT(result, 8, ru->ru_nswap);
7639 SET_INT(result, 9, ru->ru_inblock);
7640 SET_INT(result, 10, ru->ru_oublock);
7641 SET_INT(result, 11, ru->ru_msgsnd);
7642 SET_INT(result, 12, ru->ru_msgrcv);
7643 SET_INT(result, 13, ru->ru_nsignals);
7644 SET_INT(result, 14, ru->ru_nvcsw);
7645 SET_INT(result, 15, ru->ru_nivcsw);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007646#undef SET_INT
7647
Victor Stinner8c62be82010-05-06 00:08:46 +00007648 if (PyErr_Occurred()) {
7649 Py_DECREF(result);
7650 return NULL;
7651 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007652
Victor Stinner8c62be82010-05-06 00:08:46 +00007653 return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007654}
7655#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
7656
Larry Hastings2f936352014-08-05 14:04:04 +10007657
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007658#ifdef HAVE_WAIT3
Larry Hastings2f936352014-08-05 14:04:04 +10007659/*[clinic input]
7660os.wait3
7661
7662 options: int
7663Wait for completion of a child process.
7664
7665Returns a tuple of information about the child process:
7666 (pid, status, rusage)
7667[clinic start generated code]*/
7668
Larry Hastings2f936352014-08-05 14:04:04 +10007669static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007670os_wait3_impl(PyObject *module, int options)
7671/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007672{
Victor Stinner8c62be82010-05-06 00:08:46 +00007673 pid_t pid;
Victor Stinner8c62be82010-05-06 00:08:46 +00007674 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007675 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007676 WAIT_TYPE status;
7677 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007678
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007679 do {
7680 Py_BEGIN_ALLOW_THREADS
7681 pid = wait3(&status, options, &ru);
7682 Py_END_ALLOW_THREADS
7683 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7684 if (pid < 0)
7685 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007686
Victor Stinner4195b5c2012-02-08 23:03:19 +01007687 return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007688}
7689#endif /* HAVE_WAIT3 */
7690
Larry Hastings2f936352014-08-05 14:04:04 +10007691
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007692#ifdef HAVE_WAIT4
Larry Hastings2f936352014-08-05 14:04:04 +10007693/*[clinic input]
7694
7695os.wait4
7696
7697 pid: pid_t
7698 options: int
7699
7700Wait for completion of a specific child process.
7701
7702Returns a tuple of information about the child process:
7703 (pid, status, rusage)
7704[clinic start generated code]*/
7705
Larry Hastings2f936352014-08-05 14:04:04 +10007706static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007707os_wait4_impl(PyObject *module, pid_t pid, int options)
7708/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007709{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007710 pid_t res;
Victor Stinner8c62be82010-05-06 00:08:46 +00007711 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007712 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007713 WAIT_TYPE status;
7714 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007715
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007716 do {
7717 Py_BEGIN_ALLOW_THREADS
7718 res = wait4(pid, &status, options, &ru);
7719 Py_END_ALLOW_THREADS
7720 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7721 if (res < 0)
7722 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007723
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007724 return wait_helper(res, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007725}
7726#endif /* HAVE_WAIT4 */
7727
Larry Hastings2f936352014-08-05 14:04:04 +10007728
Ross Lagerwall7807c352011-03-17 20:20:30 +02007729#if defined(HAVE_WAITID) && !defined(__APPLE__)
Larry Hastings2f936352014-08-05 14:04:04 +10007730/*[clinic input]
7731os.waitid
7732
7733 idtype: idtype_t
7734 Must be one of be P_PID, P_PGID or P_ALL.
7735 id: id_t
7736 The id to wait on.
7737 options: int
7738 Constructed from the ORing of one or more of WEXITED, WSTOPPED
7739 or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
7740 /
7741
7742Returns the result of waiting for a process or processes.
7743
7744Returns either waitid_result or None if WNOHANG is specified and there are
7745no children in a waitable state.
7746[clinic start generated code]*/
7747
Larry Hastings2f936352014-08-05 14:04:04 +10007748static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007749os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
7750/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007751{
7752 PyObject *result;
7753 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007754 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007755 siginfo_t si;
7756 si.si_pid = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007757
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007758 do {
7759 Py_BEGIN_ALLOW_THREADS
7760 res = waitid(idtype, id, &si, options);
7761 Py_END_ALLOW_THREADS
7762 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7763 if (res < 0)
7764 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007765
7766 if (si.si_pid == 0)
7767 Py_RETURN_NONE;
7768
Eddie Elizondob3966632019-11-05 07:16:14 -08007769 PyObject *WaitidResultType = _posixstate(module)->WaitidResultType;
7770 result = PyStructSequence_New((PyTypeObject *)WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +02007771 if (!result)
7772 return NULL;
7773
7774 PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007775 PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
Ross Lagerwall7807c352011-03-17 20:20:30 +02007776 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
7777 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
7778 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
7779 if (PyErr_Occurred()) {
7780 Py_DECREF(result);
7781 return NULL;
7782 }
7783
7784 return result;
7785}
Larry Hastings2f936352014-08-05 14:04:04 +10007786#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
Ross Lagerwall7807c352011-03-17 20:20:30 +02007787
Larry Hastings2f936352014-08-05 14:04:04 +10007788
7789#if defined(HAVE_WAITPID)
7790/*[clinic input]
7791os.waitpid
7792 pid: pid_t
7793 options: int
7794 /
7795
7796Wait for completion of a given child process.
7797
7798Returns a tuple of information regarding the child process:
7799 (pid, status)
7800
7801The options argument is ignored on Windows.
7802[clinic start generated code]*/
7803
Larry Hastings2f936352014-08-05 14:04:04 +10007804static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007805os_waitpid_impl(PyObject *module, pid_t pid, int options)
7806/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007807{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007808 pid_t res;
7809 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007810 WAIT_TYPE status;
7811 WAIT_STATUS_INT(status) = 0;
Guido van Rossum54ecc3d1999-01-27 17:53:11 +00007812
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007813 do {
7814 Py_BEGIN_ALLOW_THREADS
7815 res = waitpid(pid, &status, options);
7816 Py_END_ALLOW_THREADS
7817 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7818 if (res < 0)
7819 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007820
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007821 return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
Guido van Rossum21803b81992-08-09 12:55:27 +00007822}
Tim Petersab034fa2002-02-01 11:27:43 +00007823#elif defined(HAVE_CWAIT)
Tim Petersab034fa2002-02-01 11:27:43 +00007824/* MS C has a variant of waitpid() that's usable for most purposes. */
Larry Hastings2f936352014-08-05 14:04:04 +10007825/*[clinic input]
7826os.waitpid
Benjamin Petersonca470632016-09-06 13:47:26 -07007827 pid: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +10007828 options: int
7829 /
7830
7831Wait for completion of a given process.
7832
7833Returns a tuple of information regarding the process:
7834 (pid, status << 8)
7835
7836The options argument is ignored on Windows.
7837[clinic start generated code]*/
7838
Larry Hastings2f936352014-08-05 14:04:04 +10007839static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -07007840os_waitpid_impl(PyObject *module, intptr_t pid, int options)
Victor Stinner581139c2016-09-06 15:54:20 -07007841/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007842{
7843 int status;
Benjamin Petersonca470632016-09-06 13:47:26 -07007844 intptr_t res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007845 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007846
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007847 do {
7848 Py_BEGIN_ALLOW_THREADS
Steve Dower11f43262016-11-19 18:33:39 -08007849 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007850 res = _cwait(&status, pid, options);
Steve Dower11f43262016-11-19 18:33:39 -08007851 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007852 Py_END_ALLOW_THREADS
7853 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinnerd3ffd322015-09-15 10:11:03 +02007854 if (res < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007855 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007856
Victor Stinner8c62be82010-05-06 00:08:46 +00007857 /* shift the status left a byte so this is more like the POSIX waitpid */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007858 return Py_BuildValue(_Py_PARSE_INTPTR "i", res, status << 8);
Tim Petersab034fa2002-02-01 11:27:43 +00007859}
Larry Hastings2f936352014-08-05 14:04:04 +10007860#endif
7861
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007862
Guido van Rossumad0ee831995-03-01 10:34:45 +00007863#ifdef HAVE_WAIT
Larry Hastings2f936352014-08-05 14:04:04 +10007864/*[clinic input]
7865os.wait
7866
7867Wait for completion of a child process.
7868
7869Returns a tuple of information about the child process:
7870 (pid, status)
7871[clinic start generated code]*/
7872
Larry Hastings2f936352014-08-05 14:04:04 +10007873static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007874os_wait_impl(PyObject *module)
7875/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
Guido van Rossum21803b81992-08-09 12:55:27 +00007876{
Victor Stinner8c62be82010-05-06 00:08:46 +00007877 pid_t pid;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007878 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007879 WAIT_TYPE status;
7880 WAIT_STATUS_INT(status) = 0;
Neal Norwitze241ce82003-02-17 18:17:05 +00007881
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007882 do {
7883 Py_BEGIN_ALLOW_THREADS
7884 pid = wait(&status);
7885 Py_END_ALLOW_THREADS
7886 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7887 if (pid < 0)
7888 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007889
Victor Stinner8c62be82010-05-06 00:08:46 +00007890 return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
Guido van Rossum85e3b011991-06-03 12:42:10 +00007891}
Larry Hastings2f936352014-08-05 14:04:04 +10007892#endif /* HAVE_WAIT */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007893
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -08007894#if defined(__linux__) && defined(__NR_pidfd_open)
7895/*[clinic input]
7896os.pidfd_open
7897 pid: pid_t
7898 flags: unsigned_int = 0
7899
7900Return a file descriptor referring to the process *pid*.
7901
7902The descriptor can be used to perform process management without races and
7903signals.
7904[clinic start generated code]*/
7905
7906static PyObject *
7907os_pidfd_open_impl(PyObject *module, pid_t pid, unsigned int flags)
7908/*[clinic end generated code: output=5c7252698947dc41 input=c3fd99ce947ccfef]*/
7909{
7910 int fd = syscall(__NR_pidfd_open, pid, flags);
7911 if (fd < 0) {
7912 return posix_error();
7913 }
7914 return PyLong_FromLong(fd);
7915}
7916#endif
7917
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007918
Larry Hastings9cf065c2012-06-22 16:30:09 -07007919#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007920/*[clinic input]
7921os.readlink
7922
7923 path: path_t
7924 *
7925 dir_fd: dir_fd(requires='readlinkat') = None
7926
7927Return a string representing the path to which the symbolic link points.
7928
7929If dir_fd is not None, it should be a file descriptor open to a directory,
7930and path should be relative; path will then be relative to that directory.
7931
7932dir_fd may not be implemented on your platform. If it is unavailable,
7933using it will raise a NotImplementedError.
7934[clinic start generated code]*/
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007935
Barry Warsaw53699e91996-12-10 23:23:01 +00007936static PyObject *
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007937os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
7938/*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00007939{
Berker Peksage0b5b202018-08-15 13:03:41 +03007940#if defined(HAVE_READLINK)
Christian Heimes3cb091e2016-09-23 20:24:28 +02007941 char buffer[MAXPATHLEN+1];
Larry Hastings9cf065c2012-06-22 16:30:09 -07007942 ssize_t length;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007943
7944 Py_BEGIN_ALLOW_THREADS
7945#ifdef HAVE_READLINKAT
7946 if (dir_fd != DEFAULT_DIR_FD)
7947 length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
7948 else
7949#endif
7950 length = readlink(path->narrow, buffer, MAXPATHLEN);
7951 Py_END_ALLOW_THREADS
7952
7953 if (length < 0) {
7954 return path_error(path);
7955 }
7956 buffer[length] = '\0';
7957
7958 if (PyUnicode_Check(path->object))
7959 return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
7960 else
7961 return PyBytes_FromStringAndSize(buffer, length);
Berker Peksage0b5b202018-08-15 13:03:41 +03007962#elif defined(MS_WINDOWS)
7963 DWORD n_bytes_returned;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007964 DWORD io_result = 0;
Berker Peksage0b5b202018-08-15 13:03:41 +03007965 HANDLE reparse_point_handle;
Berker Peksage0b5b202018-08-15 13:03:41 +03007966 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
7967 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Steve Dower993ac922019-09-03 12:50:51 -07007968 PyObject *result = NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00007969
Larry Hastings2f936352014-08-05 14:04:04 +10007970 /* First get a handle to the reparse point */
7971 Py_BEGIN_ALLOW_THREADS
7972 reparse_point_handle = CreateFileW(
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007973 path->wide,
Larry Hastings2f936352014-08-05 14:04:04 +10007974 0,
7975 0,
7976 0,
7977 OPEN_EXISTING,
7978 FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
7979 0);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007980 if (reparse_point_handle != INVALID_HANDLE_VALUE) {
7981 /* New call DeviceIoControl to read the reparse point */
7982 io_result = DeviceIoControl(
7983 reparse_point_handle,
7984 FSCTL_GET_REPARSE_POINT,
7985 0, 0, /* in buffer */
7986 target_buffer, sizeof(target_buffer),
7987 &n_bytes_returned,
7988 0 /* we're not using OVERLAPPED_IO */
7989 );
7990 CloseHandle(reparse_point_handle);
Berker Peksage0b5b202018-08-15 13:03:41 +03007991 }
Larry Hastings2f936352014-08-05 14:04:04 +10007992 Py_END_ALLOW_THREADS
7993
Berker Peksage0b5b202018-08-15 13:03:41 +03007994 if (io_result == 0) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007995 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03007996 }
Larry Hastings2f936352014-08-05 14:04:04 +10007997
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007998 wchar_t *name = NULL;
7999 Py_ssize_t nameLen = 0;
8000 if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
Larry Hastings2f936352014-08-05 14:04:04 +10008001 {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008002 name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
8003 rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
8004 nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
Larry Hastings2f936352014-08-05 14:04:04 +10008005 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008006 else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
8007 {
8008 name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
8009 rdb->MountPointReparseBuffer.SubstituteNameOffset);
8010 nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
8011 }
8012 else
8013 {
8014 PyErr_SetString(PyExc_ValueError, "not a symbolic link");
8015 }
8016 if (name) {
8017 if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
8018 /* Our buffer is mutable, so this is okay */
8019 name[1] = L'\\';
8020 }
8021 result = PyUnicode_FromWideChar(name, nameLen);
Steve Dower993ac922019-09-03 12:50:51 -07008022 if (result && path->narrow) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008023 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
8024 }
Berker Peksage0b5b202018-08-15 13:03:41 +03008025 }
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008026 return result;
Berker Peksage0b5b202018-08-15 13:03:41 +03008027#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008028}
Berker Peksage0b5b202018-08-15 13:03:41 +03008029#endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008030
Larry Hastings9cf065c2012-06-22 16:30:09 -07008031#ifdef HAVE_SYMLINK
Larry Hastings9cf065c2012-06-22 16:30:09 -07008032
8033#if defined(MS_WINDOWS)
8034
Steve Dower6921e732018-03-05 14:26:08 -08008035/* Remove the last portion of the path - return 0 on success */
8036static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008037_dirnameW(WCHAR *path)
8038{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008039 WCHAR *ptr;
Steve Dower6921e732018-03-05 14:26:08 -08008040 size_t length = wcsnlen_s(path, MAX_PATH);
8041 if (length == MAX_PATH) {
8042 return -1;
8043 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008044
8045 /* walk the path from the end until a backslash is encountered */
Steve Dower6921e732018-03-05 14:26:08 -08008046 for(ptr = path + length; ptr != path; ptr--) {
8047 if (*ptr == L'\\' || *ptr == L'/') {
Jason R. Coombs3a092862013-05-27 23:21:28 -04008048 break;
Steve Dower6921e732018-03-05 14:26:08 -08008049 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008050 }
8051 *ptr = 0;
Steve Dower6921e732018-03-05 14:26:08 -08008052 return 0;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008053}
8054
Victor Stinner31b3b922013-06-05 01:49:17 +02008055/* Is this path absolute? */
8056static int
8057_is_absW(const WCHAR *path)
8058{
Steve Dower6921e732018-03-05 14:26:08 -08008059 return path[0] == L'\\' || path[0] == L'/' ||
8060 (path[0] && path[1] == L':');
Jason R. Coombs3a092862013-05-27 23:21:28 -04008061}
8062
Steve Dower6921e732018-03-05 14:26:08 -08008063/* join root and rest with a backslash - return 0 on success */
8064static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008065_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
8066{
Victor Stinner31b3b922013-06-05 01:49:17 +02008067 if (_is_absW(rest)) {
Steve Dower6921e732018-03-05 14:26:08 -08008068 return wcscpy_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008069 }
8070
Steve Dower6921e732018-03-05 14:26:08 -08008071 if (wcscpy_s(dest_path, MAX_PATH, root)) {
8072 return -1;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008073 }
Steve Dower6921e732018-03-05 14:26:08 -08008074
8075 if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
8076 return -1;
8077 }
8078
8079 return wcscat_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008080}
8081
Victor Stinner31b3b922013-06-05 01:49:17 +02008082/* Return True if the path at src relative to dest is a directory */
8083static int
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03008084_check_dirW(LPCWSTR src, LPCWSTR dest)
Jason R. Coombs3a092862013-05-27 23:21:28 -04008085{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008086 WIN32_FILE_ATTRIBUTE_DATA src_info;
8087 WCHAR dest_parent[MAX_PATH];
8088 WCHAR src_resolved[MAX_PATH] = L"";
8089
8090 /* dest_parent = os.path.dirname(dest) */
Steve Dower6921e732018-03-05 14:26:08 -08008091 if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
8092 _dirnameW(dest_parent)) {
8093 return 0;
8094 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008095 /* src_resolved = os.path.join(dest_parent, src) */
Steve Dower6921e732018-03-05 14:26:08 -08008096 if (_joinW(src_resolved, dest_parent, src)) {
8097 return 0;
8098 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008099 return (
8100 GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
8101 && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
8102 );
8103}
Larry Hastings9cf065c2012-06-22 16:30:09 -07008104#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008105
Larry Hastings2f936352014-08-05 14:04:04 +10008106
8107/*[clinic input]
8108os.symlink
8109 src: path_t
8110 dst: path_t
8111 target_is_directory: bool = False
8112 *
8113 dir_fd: dir_fd(requires='symlinkat')=None
8114
8115# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
8116
8117Create a symbolic link pointing to src named dst.
8118
8119target_is_directory is required on Windows if the target is to be
8120 interpreted as a directory. (On Windows, symlink requires
8121 Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
8122 target_is_directory is ignored on non-Windows platforms.
8123
8124If dir_fd is not None, it should be a file descriptor open to a directory,
8125 and path should be relative; path will then be relative to that directory.
8126dir_fd may not be implemented on your platform.
8127 If it is unavailable, using it will raise a NotImplementedError.
8128
8129[clinic start generated code]*/
8130
Larry Hastings2f936352014-08-05 14:04:04 +10008131static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008132os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
Larry Hastings89964c42015-04-14 18:07:59 -04008133 int target_is_directory, int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008134/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008135{
Larry Hastings9cf065c2012-06-22 16:30:09 -07008136#ifdef MS_WINDOWS
8137 DWORD result;
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008138 DWORD flags = 0;
8139
8140 /* Assumed true, set to false if detected to not be available. */
8141 static int windows_has_symlink_unprivileged_flag = TRUE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008142#else
8143 int result;
8144#endif
8145
Larry Hastings9cf065c2012-06-22 16:30:09 -07008146#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008147
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008148 if (windows_has_symlink_unprivileged_flag) {
8149 /* Allow non-admin symlinks if system allows it. */
8150 flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
8151 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008152
Larry Hastings9cf065c2012-06-22 16:30:09 -07008153 Py_BEGIN_ALLOW_THREADS
Steve Dower6921e732018-03-05 14:26:08 -08008154 _Py_BEGIN_SUPPRESS_IPH
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008155 /* if src is a directory, ensure flags==1 (target_is_directory bit) */
8156 if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
8157 flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
8158 }
8159
8160 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
Steve Dower6921e732018-03-05 14:26:08 -08008161 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07008162 Py_END_ALLOW_THREADS
8163
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008164 if (windows_has_symlink_unprivileged_flag && !result &&
8165 ERROR_INVALID_PARAMETER == GetLastError()) {
8166
8167 Py_BEGIN_ALLOW_THREADS
8168 _Py_BEGIN_SUPPRESS_IPH
8169 /* This error might be caused by
8170 SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
8171 Try again, and update windows_has_symlink_unprivileged_flag if we
8172 are successful this time.
8173
8174 NOTE: There is a risk of a race condition here if there are other
8175 conditions than the flag causing ERROR_INVALID_PARAMETER, and
8176 another process (or thread) changes that condition in between our
8177 calls to CreateSymbolicLink.
8178 */
8179 flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
8180 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
8181 _Py_END_SUPPRESS_IPH
8182 Py_END_ALLOW_THREADS
8183
8184 if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
8185 windows_has_symlink_unprivileged_flag = FALSE;
8186 }
8187 }
8188
Larry Hastings2f936352014-08-05 14:04:04 +10008189 if (!result)
8190 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008191
8192#else
8193
Steve Dower6921e732018-03-05 14:26:08 -08008194 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
8195 PyErr_SetString(PyExc_ValueError,
8196 "symlink: src and dst must be the same type");
8197 return NULL;
8198 }
8199
Larry Hastings9cf065c2012-06-22 16:30:09 -07008200 Py_BEGIN_ALLOW_THREADS
8201#if HAVE_SYMLINKAT
8202 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10008203 result = symlinkat(src->narrow, dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008204 else
8205#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008206 result = symlink(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008207 Py_END_ALLOW_THREADS
8208
Larry Hastings2f936352014-08-05 14:04:04 +10008209 if (result)
8210 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008211#endif
8212
Larry Hastings2f936352014-08-05 14:04:04 +10008213 Py_RETURN_NONE;
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008214}
8215#endif /* HAVE_SYMLINK */
8216
Larry Hastings9cf065c2012-06-22 16:30:09 -07008217
Brian Curtind40e6f72010-07-08 21:39:08 +00008218
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008219
Larry Hastings605a62d2012-06-24 04:33:36 -07008220static PyStructSequence_Field times_result_fields[] = {
8221 {"user", "user time"},
8222 {"system", "system time"},
8223 {"children_user", "user time of children"},
8224 {"children_system", "system time of children"},
8225 {"elapsed", "elapsed time since an arbitrary point in the past"},
8226 {NULL}
8227};
8228
8229PyDoc_STRVAR(times_result__doc__,
8230"times_result: Result from os.times().\n\n\
8231This object may be accessed either as a tuple of\n\
8232 (user, system, children_user, children_system, elapsed),\n\
8233or via the attributes user, system, children_user, children_system,\n\
8234and elapsed.\n\
8235\n\
8236See os.times for more information.");
8237
8238static PyStructSequence_Desc times_result_desc = {
8239 "times_result", /* name */
8240 times_result__doc__, /* doc */
8241 times_result_fields,
8242 5
8243};
8244
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008245#ifdef MS_WINDOWS
8246#define HAVE_TIMES /* mandatory, for the method table */
8247#endif
Larry Hastings605a62d2012-06-24 04:33:36 -07008248
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008249#ifdef HAVE_TIMES
Larry Hastings605a62d2012-06-24 04:33:36 -07008250
8251static PyObject *
8252build_times_result(double user, double system,
8253 double children_user, double children_system,
8254 double elapsed)
8255{
Eddie Elizondob3966632019-11-05 07:16:14 -08008256 PyObject *TimesResultType = _posixstate_global->TimesResultType;
8257 PyObject *value = PyStructSequence_New((PyTypeObject *)TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07008258 if (value == NULL)
8259 return NULL;
8260
8261#define SET(i, field) \
8262 { \
8263 PyObject *o = PyFloat_FromDouble(field); \
8264 if (!o) { \
8265 Py_DECREF(value); \
8266 return NULL; \
8267 } \
8268 PyStructSequence_SET_ITEM(value, i, o); \
8269 } \
8270
8271 SET(0, user);
8272 SET(1, system);
8273 SET(2, children_user);
8274 SET(3, children_system);
8275 SET(4, elapsed);
8276
8277#undef SET
8278
8279 return value;
8280}
8281
Larry Hastings605a62d2012-06-24 04:33:36 -07008282
Larry Hastings2f936352014-08-05 14:04:04 +10008283#ifndef MS_WINDOWS
8284#define NEED_TICKS_PER_SECOND
8285static long ticks_per_second = -1;
8286#endif /* MS_WINDOWS */
8287
8288/*[clinic input]
8289os.times
8290
8291Return a collection containing process timing information.
8292
8293The object returned behaves like a named tuple with these fields:
8294 (utime, stime, cutime, cstime, elapsed_time)
8295All fields are floating point numbers.
8296[clinic start generated code]*/
8297
Larry Hastings2f936352014-08-05 14:04:04 +10008298static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008299os_times_impl(PyObject *module)
8300/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008301#ifdef MS_WINDOWS
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008302{
Victor Stinner8c62be82010-05-06 00:08:46 +00008303 FILETIME create, exit, kernel, user;
8304 HANDLE hProc;
8305 hProc = GetCurrentProcess();
8306 GetProcessTimes(hProc, &create, &exit, &kernel, &user);
8307 /* The fields of a FILETIME structure are the hi and lo part
8308 of a 64-bit value expressed in 100 nanosecond units.
8309 1e7 is one second in such units; 1e-7 the inverse.
8310 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
8311 */
Larry Hastings605a62d2012-06-24 04:33:36 -07008312 return build_times_result(
Victor Stinner8c62be82010-05-06 00:08:46 +00008313 (double)(user.dwHighDateTime*429.4967296 +
8314 user.dwLowDateTime*1e-7),
8315 (double)(kernel.dwHighDateTime*429.4967296 +
8316 kernel.dwLowDateTime*1e-7),
8317 (double)0,
8318 (double)0,
8319 (double)0);
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008320}
Larry Hastings2f936352014-08-05 14:04:04 +10008321#else /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008322{
Larry Hastings2f936352014-08-05 14:04:04 +10008323
8324
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008325 struct tms t;
8326 clock_t c;
8327 errno = 0;
8328 c = times(&t);
8329 if (c == (clock_t) -1)
8330 return posix_error();
8331 return build_times_result(
8332 (double)t.tms_utime / ticks_per_second,
8333 (double)t.tms_stime / ticks_per_second,
8334 (double)t.tms_cutime / ticks_per_second,
8335 (double)t.tms_cstime / ticks_per_second,
8336 (double)c / ticks_per_second);
8337}
Larry Hastings2f936352014-08-05 14:04:04 +10008338#endif /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008339#endif /* HAVE_TIMES */
8340
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008341
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008342#ifdef HAVE_GETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008343/*[clinic input]
8344os.getsid
8345
8346 pid: pid_t
8347 /
8348
8349Call the system call getsid(pid) and return the result.
8350[clinic start generated code]*/
8351
Larry Hastings2f936352014-08-05 14:04:04 +10008352static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008353os_getsid_impl(PyObject *module, pid_t pid)
8354/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008355{
Victor Stinner8c62be82010-05-06 00:08:46 +00008356 int sid;
Victor Stinner8c62be82010-05-06 00:08:46 +00008357 sid = getsid(pid);
8358 if (sid < 0)
8359 return posix_error();
8360 return PyLong_FromLong((long)sid);
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008361}
8362#endif /* HAVE_GETSID */
8363
8364
Guido van Rossumb6775db1994-08-01 11:34:53 +00008365#ifdef HAVE_SETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008366/*[clinic input]
8367os.setsid
8368
8369Call the system call setsid().
8370[clinic start generated code]*/
8371
Larry Hastings2f936352014-08-05 14:04:04 +10008372static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008373os_setsid_impl(PyObject *module)
8374/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00008375{
Victor Stinner8c62be82010-05-06 00:08:46 +00008376 if (setsid() < 0)
8377 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008378 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008379}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008380#endif /* HAVE_SETSID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008381
Larry Hastings2f936352014-08-05 14:04:04 +10008382
Guido van Rossumb6775db1994-08-01 11:34:53 +00008383#ifdef HAVE_SETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10008384/*[clinic input]
8385os.setpgid
8386
8387 pid: pid_t
8388 pgrp: pid_t
8389 /
8390
8391Call the system call setpgid(pid, pgrp).
8392[clinic start generated code]*/
8393
Larry Hastings2f936352014-08-05 14:04:04 +10008394static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008395os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
8396/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008397{
Victor Stinner8c62be82010-05-06 00:08:46 +00008398 if (setpgid(pid, pgrp) < 0)
8399 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008400 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008401}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008402#endif /* HAVE_SETPGID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008403
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008404
Guido van Rossumb6775db1994-08-01 11:34:53 +00008405#ifdef HAVE_TCGETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008406/*[clinic input]
8407os.tcgetpgrp
8408
8409 fd: int
8410 /
8411
8412Return the process group associated with the terminal specified by fd.
8413[clinic start generated code]*/
8414
Larry Hastings2f936352014-08-05 14:04:04 +10008415static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008416os_tcgetpgrp_impl(PyObject *module, int fd)
8417/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008418{
8419 pid_t pgid = tcgetpgrp(fd);
Victor Stinner8c62be82010-05-06 00:08:46 +00008420 if (pgid < 0)
8421 return posix_error();
8422 return PyLong_FromPid(pgid);
Guido van Rossum7066dd71992-09-17 17:54:56 +00008423}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008424#endif /* HAVE_TCGETPGRP */
Guido van Rossum7066dd71992-09-17 17:54:56 +00008425
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008426
Guido van Rossumb6775db1994-08-01 11:34:53 +00008427#ifdef HAVE_TCSETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008428/*[clinic input]
8429os.tcsetpgrp
8430
8431 fd: int
8432 pgid: pid_t
8433 /
8434
8435Set the process group associated with the terminal specified by fd.
8436[clinic start generated code]*/
8437
Larry Hastings2f936352014-08-05 14:04:04 +10008438static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008439os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
8440/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008441{
Victor Stinner8c62be82010-05-06 00:08:46 +00008442 if (tcsetpgrp(fd, pgid) < 0)
8443 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008444 Py_RETURN_NONE;
Guido van Rossum7066dd71992-09-17 17:54:56 +00008445}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008446#endif /* HAVE_TCSETPGRP */
Guido van Rossum22db57e1992-04-05 14:25:30 +00008447
Guido van Rossum687dd131993-05-17 08:34:16 +00008448/* Functions acting on file descriptors */
8449
Victor Stinnerdaf45552013-08-28 00:53:59 +02008450#ifdef O_CLOEXEC
8451extern int _Py_open_cloexec_works;
8452#endif
8453
Larry Hastings2f936352014-08-05 14:04:04 +10008454
8455/*[clinic input]
8456os.open -> int
8457 path: path_t
8458 flags: int
8459 mode: int = 0o777
8460 *
8461 dir_fd: dir_fd(requires='openat') = None
8462
8463# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
8464
8465Open a file for low level IO. Returns a file descriptor (integer).
8466
8467If dir_fd is not None, it should be a file descriptor open to a directory,
8468 and path should be relative; path will then be relative to that directory.
8469dir_fd may not be implemented on your platform.
8470 If it is unavailable, using it will raise a NotImplementedError.
8471[clinic start generated code]*/
8472
Larry Hastings2f936352014-08-05 14:04:04 +10008473static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008474os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
8475/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008476{
8477 int fd;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008478 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008479
Victor Stinnerdaf45552013-08-28 00:53:59 +02008480#ifdef O_CLOEXEC
8481 int *atomic_flag_works = &_Py_open_cloexec_works;
8482#elif !defined(MS_WINDOWS)
8483 int *atomic_flag_works = NULL;
8484#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +00008485
Victor Stinnerdaf45552013-08-28 00:53:59 +02008486#ifdef MS_WINDOWS
8487 flags |= O_NOINHERIT;
8488#elif defined(O_CLOEXEC)
8489 flags |= O_CLOEXEC;
8490#endif
8491
Steve Dowerb82e17e2019-05-23 08:45:22 -07008492 if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
8493 return -1;
8494 }
8495
Steve Dower8fc89802015-04-12 00:26:27 -04008496 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008497 do {
8498 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008499#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07008500 fd = _wopen(path->wide, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008501#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07008502#ifdef HAVE_OPENAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008503 if (dir_fd != DEFAULT_DIR_FD)
8504 fd = openat(dir_fd, path->narrow, flags, mode);
8505 else
Steve Dower6230aaf2016-09-09 09:03:15 -07008506#endif /* HAVE_OPENAT */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008507 fd = open(path->narrow, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008508#endif /* !MS_WINDOWS */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008509 Py_END_ALLOW_THREADS
8510 } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04008511 _Py_END_SUPPRESS_IPH
Guido van Rossum687dd131993-05-17 08:34:16 +00008512
Victor Stinnerd3ffd322015-09-15 10:11:03 +02008513 if (fd < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008514 if (!async_err)
8515 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Larry Hastings2f936352014-08-05 14:04:04 +10008516 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008517 }
8518
Victor Stinnerdaf45552013-08-28 00:53:59 +02008519#ifndef MS_WINDOWS
8520 if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
8521 close(fd);
Larry Hastings2f936352014-08-05 14:04:04 +10008522 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008523 }
8524#endif
8525
Larry Hastings2f936352014-08-05 14:04:04 +10008526 return fd;
8527}
8528
8529
8530/*[clinic input]
8531os.close
8532
8533 fd: int
8534
8535Close a file descriptor.
8536[clinic start generated code]*/
8537
Barry Warsaw53699e91996-12-10 23:23:01 +00008538static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008539os_close_impl(PyObject *module, int fd)
8540/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00008541{
Larry Hastings2f936352014-08-05 14:04:04 +10008542 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008543 /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
8544 * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
8545 * for more details.
8546 */
Victor Stinner8c62be82010-05-06 00:08:46 +00008547 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008548 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008549 res = close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04008550 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008551 Py_END_ALLOW_THREADS
8552 if (res < 0)
8553 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008554 Py_RETURN_NONE;
Guido van Rossum687dd131993-05-17 08:34:16 +00008555}
8556
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008557
Jakub Kulíke20134f2019-09-11 17:11:57 +02008558#ifdef HAVE_FDWALK
8559static int
8560_fdwalk_close_func(void *lohi, int fd)
8561{
8562 int lo = ((int *)lohi)[0];
8563 int hi = ((int *)lohi)[1];
8564
8565 if (fd >= hi)
8566 return 1;
8567 else if (fd >= lo)
8568 close(fd);
8569 return 0;
8570}
8571#endif /* HAVE_FDWALK */
8572
Larry Hastings2f936352014-08-05 14:04:04 +10008573/*[clinic input]
8574os.closerange
8575
8576 fd_low: int
8577 fd_high: int
8578 /
8579
8580Closes all file descriptors in [fd_low, fd_high), ignoring errors.
8581[clinic start generated code]*/
8582
Larry Hastings2f936352014-08-05 14:04:04 +10008583static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008584os_closerange_impl(PyObject *module, int fd_low, int fd_high)
8585/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008586{
Jakub Kulíke20134f2019-09-11 17:11:57 +02008587#ifdef HAVE_FDWALK
8588 int lohi[2];
8589#else
Larry Hastings2f936352014-08-05 14:04:04 +10008590 int i;
Jakub Kulíke20134f2019-09-11 17:11:57 +02008591#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00008592 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008593 _Py_BEGIN_SUPPRESS_IPH
Jakub Kulíke20134f2019-09-11 17:11:57 +02008594#ifdef HAVE_FDWALK
8595 lohi[0] = Py_MAX(fd_low, 0);
8596 lohi[1] = fd_high;
8597 fdwalk(_fdwalk_close_func, lohi);
8598#else
Benjamin Peterson207116b2016-09-08 11:28:06 -07008599 for (i = Py_MAX(fd_low, 0); i < fd_high; i++)
Steve Dower940f33a2016-09-08 11:21:54 -07008600 close(i);
Jakub Kulíke20134f2019-09-11 17:11:57 +02008601#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008602 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008603 Py_END_ALLOW_THREADS
8604 Py_RETURN_NONE;
Christian Heimesfdab48e2008-01-20 09:06:41 +00008605}
8606
8607
Larry Hastings2f936352014-08-05 14:04:04 +10008608/*[clinic input]
8609os.dup -> int
8610
8611 fd: int
8612 /
8613
8614Return a duplicate of a file descriptor.
8615[clinic start generated code]*/
8616
Larry Hastings2f936352014-08-05 14:04:04 +10008617static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008618os_dup_impl(PyObject *module, int fd)
8619/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008620{
8621 return _Py_dup(fd);
Guido van Rossum687dd131993-05-17 08:34:16 +00008622}
8623
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008624
Larry Hastings2f936352014-08-05 14:04:04 +10008625/*[clinic input]
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008626os.dup2 -> int
Larry Hastings2f936352014-08-05 14:04:04 +10008627 fd: int
8628 fd2: int
8629 inheritable: bool=True
8630
8631Duplicate file descriptor.
8632[clinic start generated code]*/
8633
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008634static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008635os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008636/*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008637{
Stéphane Wirtel3d86e482018-01-30 07:04:36 +01008638 int res = 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008639#if defined(HAVE_DUP3) && \
8640 !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
8641 /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
Alexey Izbyshevb3caf382018-02-20 10:25:46 +03008642 static int dup3_works = -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008643#endif
8644
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008645 if (fd < 0 || fd2 < 0) {
8646 posix_error();
8647 return -1;
8648 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008649
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008650 /* dup2() can fail with EINTR if the target FD is already open, because it
8651 * then has to be closed. See os_close_impl() for why we don't handle EINTR
8652 * upon close(), and therefore below.
8653 */
Victor Stinnerdaf45552013-08-28 00:53:59 +02008654#ifdef MS_WINDOWS
8655 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008656 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008657 res = dup2(fd, fd2);
Steve Dower8fc89802015-04-12 00:26:27 -04008658 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02008659 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008660 if (res < 0) {
8661 posix_error();
8662 return -1;
8663 }
8664 res = fd2; // msvcrt dup2 returns 0 on success.
Victor Stinnerdaf45552013-08-28 00:53:59 +02008665
8666 /* Character files like console cannot be make non-inheritable */
8667 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8668 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008669 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008670 }
8671
8672#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
8673 Py_BEGIN_ALLOW_THREADS
8674 if (!inheritable)
8675 res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
8676 else
8677 res = dup2(fd, fd2);
8678 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008679 if (res < 0) {
8680 posix_error();
8681 return -1;
8682 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008683
8684#else
8685
8686#ifdef HAVE_DUP3
8687 if (!inheritable && dup3_works != 0) {
8688 Py_BEGIN_ALLOW_THREADS
8689 res = dup3(fd, fd2, O_CLOEXEC);
8690 Py_END_ALLOW_THREADS
8691 if (res < 0) {
8692 if (dup3_works == -1)
8693 dup3_works = (errno != ENOSYS);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008694 if (dup3_works) {
8695 posix_error();
8696 return -1;
8697 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008698 }
8699 }
8700
8701 if (inheritable || dup3_works == 0)
8702 {
8703#endif
8704 Py_BEGIN_ALLOW_THREADS
8705 res = dup2(fd, fd2);
8706 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008707 if (res < 0) {
8708 posix_error();
8709 return -1;
8710 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008711
8712 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8713 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008714 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008715 }
8716#ifdef HAVE_DUP3
8717 }
8718#endif
8719
8720#endif
8721
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008722 return res;
Guido van Rossum687dd131993-05-17 08:34:16 +00008723}
8724
Larry Hastings2f936352014-08-05 14:04:04 +10008725
Ross Lagerwall7807c352011-03-17 20:20:30 +02008726#ifdef HAVE_LOCKF
Larry Hastings2f936352014-08-05 14:04:04 +10008727/*[clinic input]
8728os.lockf
8729
8730 fd: int
8731 An open file descriptor.
8732 command: int
8733 One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
8734 length: Py_off_t
8735 The number of bytes to lock, starting at the current position.
8736 /
8737
8738Apply, test or remove a POSIX lock on an open file descriptor.
8739
8740[clinic start generated code]*/
8741
Larry Hastings2f936352014-08-05 14:04:04 +10008742static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008743os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
8744/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008745{
8746 int res;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008747
8748 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008749 res = lockf(fd, command, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008750 Py_END_ALLOW_THREADS
8751
8752 if (res < 0)
8753 return posix_error();
8754
8755 Py_RETURN_NONE;
8756}
Larry Hastings2f936352014-08-05 14:04:04 +10008757#endif /* HAVE_LOCKF */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008758
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008759
Larry Hastings2f936352014-08-05 14:04:04 +10008760/*[clinic input]
8761os.lseek -> Py_off_t
8762
8763 fd: int
8764 position: Py_off_t
8765 how: int
8766 /
8767
8768Set the position of a file descriptor. Return the new position.
8769
8770Return the new cursor position in number of bytes
8771relative to the beginning of the file.
8772[clinic start generated code]*/
8773
Larry Hastings2f936352014-08-05 14:04:04 +10008774static Py_off_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008775os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
8776/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008777{
8778 Py_off_t result;
8779
Guido van Rossum687dd131993-05-17 08:34:16 +00008780#ifdef SEEK_SET
Victor Stinner8c62be82010-05-06 00:08:46 +00008781 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
8782 switch (how) {
Larry Hastings2f936352014-08-05 14:04:04 +10008783 case 0: how = SEEK_SET; break;
8784 case 1: how = SEEK_CUR; break;
8785 case 2: how = SEEK_END; break;
Victor Stinner8c62be82010-05-06 00:08:46 +00008786 }
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00008787#endif /* SEEK_END */
Guido van Rossum94f6f721999-01-06 18:42:14 +00008788
Victor Stinner8c62be82010-05-06 00:08:46 +00008789 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008790 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner14b9b112013-06-25 00:37:25 +02008791#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10008792 result = _lseeki64(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008793#else
Larry Hastings2f936352014-08-05 14:04:04 +10008794 result = lseek(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008795#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008796 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008797 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008798 if (result < 0)
8799 posix_error();
Guido van Rossum94f6f721999-01-06 18:42:14 +00008800
Larry Hastings2f936352014-08-05 14:04:04 +10008801 return result;
Guido van Rossum687dd131993-05-17 08:34:16 +00008802}
8803
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008804
Larry Hastings2f936352014-08-05 14:04:04 +10008805/*[clinic input]
8806os.read
8807 fd: int
8808 length: Py_ssize_t
8809 /
8810
8811Read from a file descriptor. Returns a bytes object.
8812[clinic start generated code]*/
8813
Larry Hastings2f936352014-08-05 14:04:04 +10008814static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008815os_read_impl(PyObject *module, int fd, Py_ssize_t length)
8816/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008817{
Victor Stinner8c62be82010-05-06 00:08:46 +00008818 Py_ssize_t n;
8819 PyObject *buffer;
Larry Hastings2f936352014-08-05 14:04:04 +10008820
8821 if (length < 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008822 errno = EINVAL;
8823 return posix_error();
8824 }
Larry Hastings2f936352014-08-05 14:04:04 +10008825
Victor Stinner9a0d7a72018-11-22 15:03:40 +01008826 length = Py_MIN(length, _PY_READ_MAX);
Larry Hastings2f936352014-08-05 14:04:04 +10008827
8828 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Victor Stinner8c62be82010-05-06 00:08:46 +00008829 if (buffer == NULL)
8830 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008831
Victor Stinner66aab0c2015-03-19 22:53:20 +01008832 n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
8833 if (n == -1) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008834 Py_DECREF(buffer);
Victor Stinner66aab0c2015-03-19 22:53:20 +01008835 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00008836 }
Larry Hastings2f936352014-08-05 14:04:04 +10008837
8838 if (n != length)
Victor Stinner8c62be82010-05-06 00:08:46 +00008839 _PyBytes_Resize(&buffer, n);
Larry Hastings2f936352014-08-05 14:04:04 +10008840
Victor Stinner8c62be82010-05-06 00:08:46 +00008841 return buffer;
Guido van Rossum687dd131993-05-17 08:34:16 +00008842}
8843
Ross Lagerwall7807c352011-03-17 20:20:30 +02008844#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008845 || defined(__APPLE__))) \
8846 || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
8847 || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
8848static int
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008849iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008850{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008851 Py_ssize_t i, j;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008852
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008853 *iov = PyMem_New(struct iovec, cnt);
8854 if (*iov == NULL) {
8855 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008856 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008857 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008858
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008859 *buf = PyMem_New(Py_buffer, cnt);
8860 if (*buf == NULL) {
8861 PyMem_Del(*iov);
8862 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008863 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008864 }
8865
8866 for (i = 0; i < cnt; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008867 PyObject *item = PySequence_GetItem(seq, i);
8868 if (item == NULL)
8869 goto fail;
8870 if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
8871 Py_DECREF(item);
8872 goto fail;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008873 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008874 Py_DECREF(item);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008875 (*iov)[i].iov_base = (*buf)[i].buf;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008876 (*iov)[i].iov_len = (*buf)[i].len;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008877 }
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008878 return 0;
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008879
8880fail:
8881 PyMem_Del(*iov);
8882 for (j = 0; j < i; j++) {
8883 PyBuffer_Release(&(*buf)[j]);
8884 }
8885 PyMem_Del(*buf);
Victor Stinner57ddf782014-01-08 15:21:28 +01008886 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008887}
8888
8889static void
8890iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
8891{
8892 int i;
8893 PyMem_Del(iov);
8894 for (i = 0; i < cnt; i++) {
8895 PyBuffer_Release(&buf[i]);
8896 }
8897 PyMem_Del(buf);
8898}
8899#endif
8900
Larry Hastings2f936352014-08-05 14:04:04 +10008901
Ross Lagerwall7807c352011-03-17 20:20:30 +02008902#ifdef HAVE_READV
Larry Hastings2f936352014-08-05 14:04:04 +10008903/*[clinic input]
8904os.readv -> Py_ssize_t
8905
8906 fd: int
8907 buffers: object
8908 /
8909
8910Read from a file descriptor fd into an iterable of buffers.
8911
8912The buffers should be mutable buffers accepting bytes.
8913readv will transfer data into each buffer until it is full
8914and then move on to the next buffer in the sequence to hold
8915the rest of the data.
8916
8917readv returns the total number of bytes read,
8918which may be less than the total capacity of all the buffers.
8919[clinic start generated code]*/
8920
Larry Hastings2f936352014-08-05 14:04:04 +10008921static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008922os_readv_impl(PyObject *module, int fd, PyObject *buffers)
8923/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008924{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008925 Py_ssize_t cnt, n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008926 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008927 struct iovec *iov;
8928 Py_buffer *buf;
8929
Larry Hastings2f936352014-08-05 14:04:04 +10008930 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008931 PyErr_SetString(PyExc_TypeError,
8932 "readv() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10008933 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008934 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02008935
Larry Hastings2f936352014-08-05 14:04:04 +10008936 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008937 if (cnt < 0)
8938 return -1;
Larry Hastings2f936352014-08-05 14:04:04 +10008939
8940 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
8941 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008942
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008943 do {
8944 Py_BEGIN_ALLOW_THREADS
8945 n = readv(fd, iov, cnt);
8946 Py_END_ALLOW_THREADS
8947 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02008948
8949 iov_cleanup(iov, buf, cnt);
Larry Hastings2f936352014-08-05 14:04:04 +10008950 if (n < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008951 if (!async_err)
8952 posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008953 return -1;
8954 }
Victor Stinner57ddf782014-01-08 15:21:28 +01008955
Larry Hastings2f936352014-08-05 14:04:04 +10008956 return n;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008957}
Larry Hastings2f936352014-08-05 14:04:04 +10008958#endif /* HAVE_READV */
8959
Ross Lagerwall7807c352011-03-17 20:20:30 +02008960
8961#ifdef HAVE_PREAD
Larry Hastings2f936352014-08-05 14:04:04 +10008962/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10008963os.pread
8964
8965 fd: int
Dong-hee Naad7736f2019-09-25 14:47:04 +09008966 length: Py_ssize_t
Larry Hastings2f936352014-08-05 14:04:04 +10008967 offset: Py_off_t
8968 /
8969
8970Read a number of bytes from a file descriptor starting at a particular offset.
8971
8972Read length bytes from file descriptor fd, starting at offset bytes from
8973the beginning of the file. The file offset remains unchanged.
8974[clinic start generated code]*/
8975
Larry Hastings2f936352014-08-05 14:04:04 +10008976static PyObject *
Dong-hee Naad7736f2019-09-25 14:47:04 +09008977os_pread_impl(PyObject *module, int fd, Py_ssize_t length, Py_off_t offset)
8978/*[clinic end generated code: output=3f875c1eef82e32f input=85cb4a5589627144]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008979{
Ross Lagerwall7807c352011-03-17 20:20:30 +02008980 Py_ssize_t n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008981 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008982 PyObject *buffer;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008983
Larry Hastings2f936352014-08-05 14:04:04 +10008984 if (length < 0) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008985 errno = EINVAL;
8986 return posix_error();
8987 }
Larry Hastings2f936352014-08-05 14:04:04 +10008988 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008989 if (buffer == NULL)
8990 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008991
8992 do {
8993 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008994 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008995 n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04008996 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008997 Py_END_ALLOW_THREADS
8998 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8999
Ross Lagerwall7807c352011-03-17 20:20:30 +02009000 if (n < 0) {
9001 Py_DECREF(buffer);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009002 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009003 }
Larry Hastings2f936352014-08-05 14:04:04 +10009004 if (n != length)
Ross Lagerwall7807c352011-03-17 20:20:30 +02009005 _PyBytes_Resize(&buffer, n);
9006 return buffer;
9007}
Larry Hastings2f936352014-08-05 14:04:04 +10009008#endif /* HAVE_PREAD */
Ross Lagerwall7807c352011-03-17 20:20:30 +02009009
Pablo Galindo4defba32018-01-27 16:16:37 +00009010#if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
9011/*[clinic input]
9012os.preadv -> Py_ssize_t
9013
9014 fd: int
9015 buffers: object
9016 offset: Py_off_t
9017 flags: int = 0
9018 /
9019
9020Reads from a file descriptor into a number of mutable bytes-like objects.
9021
9022Combines the functionality of readv() and pread(). As readv(), it will
9023transfer data into each buffer until it is full and then move on to the next
9024buffer in the sequence to hold the rest of the data. Its fourth argument,
9025specifies the file offset at which the input operation is to be performed. It
9026will return the total number of bytes read (which can be less than the total
9027capacity of all the objects).
9028
9029The flags argument contains a bitwise OR of zero or more of the following flags:
9030
9031- RWF_HIPRI
9032- RWF_NOWAIT
9033
9034Using non-zero flags requires Linux 4.6 or newer.
9035[clinic start generated code]*/
9036
9037static Py_ssize_t
9038os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9039 int flags)
9040/*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
9041{
9042 Py_ssize_t cnt, n;
9043 int async_err = 0;
9044 struct iovec *iov;
9045 Py_buffer *buf;
9046
9047 if (!PySequence_Check(buffers)) {
9048 PyErr_SetString(PyExc_TypeError,
9049 "preadv2() arg 2 must be a sequence");
9050 return -1;
9051 }
9052
9053 cnt = PySequence_Size(buffers);
9054 if (cnt < 0) {
9055 return -1;
9056 }
9057
9058#ifndef HAVE_PREADV2
9059 if(flags != 0) {
9060 argument_unavailable_error("preadv2", "flags");
9061 return -1;
9062 }
9063#endif
9064
9065 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
9066 return -1;
9067 }
9068#ifdef HAVE_PREADV2
9069 do {
9070 Py_BEGIN_ALLOW_THREADS
9071 _Py_BEGIN_SUPPRESS_IPH
9072 n = preadv2(fd, iov, cnt, offset, flags);
9073 _Py_END_SUPPRESS_IPH
9074 Py_END_ALLOW_THREADS
9075 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9076#else
9077 do {
9078 Py_BEGIN_ALLOW_THREADS
9079 _Py_BEGIN_SUPPRESS_IPH
9080 n = preadv(fd, iov, cnt, offset);
9081 _Py_END_SUPPRESS_IPH
9082 Py_END_ALLOW_THREADS
9083 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9084#endif
9085
9086 iov_cleanup(iov, buf, cnt);
9087 if (n < 0) {
9088 if (!async_err) {
9089 posix_error();
9090 }
9091 return -1;
9092 }
9093
9094 return n;
9095}
9096#endif /* HAVE_PREADV */
9097
Larry Hastings2f936352014-08-05 14:04:04 +10009098
9099/*[clinic input]
9100os.write -> Py_ssize_t
9101
9102 fd: int
9103 data: Py_buffer
9104 /
9105
9106Write a bytes object to a file descriptor.
9107[clinic start generated code]*/
9108
Larry Hastings2f936352014-08-05 14:04:04 +10009109static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009110os_write_impl(PyObject *module, int fd, Py_buffer *data)
9111/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009112{
Victor Stinner66aab0c2015-03-19 22:53:20 +01009113 return _Py_write(fd, data->buf, data->len);
Ross Lagerwall7807c352011-03-17 20:20:30 +02009114}
9115
9116#ifdef HAVE_SENDFILE
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009117PyDoc_STRVAR(posix_sendfile__doc__,
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009118"sendfile(out_fd, in_fd, offset, count) -> byteswritten\n\
9119sendfile(out_fd, in_fd, offset, count[, headers][, trailers], flags=0)\n\
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009120 -> byteswritten\n\
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009121Copy count bytes from file descriptor in_fd to file descriptor out_fd.");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009122
Larry Hastings2f936352014-08-05 14:04:04 +10009123/* AC 3.5: don't bother converting, has optional group*/
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009124static PyObject *
9125posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict)
9126{
9127 int in, out;
9128 Py_ssize_t ret;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009129 int async_err = 0;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009130 off_t offset;
9131
9132#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
9133#ifndef __APPLE__
9134 Py_ssize_t len;
9135#endif
9136 PyObject *headers = NULL, *trailers = NULL;
9137 Py_buffer *hbuf, *tbuf;
9138 off_t sbytes;
9139 struct sf_hdtr sf;
9140 int flags = 0;
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009141 static char *keywords[] = {"out_fd", "in_fd",
Benjamin Petersond8a43b42011-02-26 21:35:16 +00009142 "offset", "count",
9143 "headers", "trailers", "flags", NULL};
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009144
Victor Stinner6ce0dbf2013-07-07 16:32:36 +02009145 sf.headers = NULL;
9146 sf.trailers = NULL;
9147
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009148#ifdef __APPLE__
9149 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&O&|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10009150 keywords, &out, &in, Py_off_t_converter, &offset, Py_off_t_converter, &sbytes,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009151#else
9152 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&n|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10009153 keywords, &out, &in, Py_off_t_converter, &offset, &len,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009154#endif
9155 &headers, &trailers, &flags))
9156 return NULL;
9157 if (headers != NULL) {
9158 if (!PySequence_Check(headers)) {
9159 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009160 "sendfile() headers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009161 return NULL;
9162 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009163 Py_ssize_t i = PySequence_Size(headers);
9164 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009165 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009166 if (i > INT_MAX) {
9167 PyErr_SetString(PyExc_OverflowError,
9168 "sendfile() header is too large");
9169 return NULL;
9170 }
9171 if (i > 0) {
9172 sf.hdr_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009173 if (iov_setup(&(sf.headers), &hbuf,
9174 headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009175 return NULL;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009176#ifdef __APPLE__
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009177 for (i = 0; i < sf.hdr_cnt; i++) {
9178 Py_ssize_t blen = sf.headers[i].iov_len;
9179# define OFF_T_MAX 0x7fffffffffffffff
9180 if (sbytes >= OFF_T_MAX - blen) {
9181 PyErr_SetString(PyExc_OverflowError,
9182 "sendfile() header is too large");
9183 return NULL;
9184 }
9185 sbytes += blen;
9186 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009187#endif
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009188 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009189 }
9190 }
9191 if (trailers != NULL) {
9192 if (!PySequence_Check(trailers)) {
9193 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009194 "sendfile() trailers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009195 return NULL;
9196 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009197 Py_ssize_t i = PySequence_Size(trailers);
9198 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009199 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009200 if (i > INT_MAX) {
9201 PyErr_SetString(PyExc_OverflowError,
9202 "sendfile() trailer is too large");
9203 return NULL;
9204 }
9205 if (i > 0) {
9206 sf.trl_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009207 if (iov_setup(&(sf.trailers), &tbuf,
9208 trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009209 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009210 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009211 }
9212 }
9213
Steve Dower8fc89802015-04-12 00:26:27 -04009214 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009215 do {
9216 Py_BEGIN_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009217#ifdef __APPLE__
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009218 ret = sendfile(in, out, offset, &sbytes, &sf, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009219#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009220 ret = sendfile(in, out, offset, len, &sf, &sbytes, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009221#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009222 Py_END_ALLOW_THREADS
9223 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04009224 _Py_END_SUPPRESS_IPH
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009225
9226 if (sf.headers != NULL)
9227 iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
9228 if (sf.trailers != NULL)
9229 iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
9230
9231 if (ret < 0) {
9232 if ((errno == EAGAIN) || (errno == EBUSY)) {
9233 if (sbytes != 0) {
9234 // some data has been sent
9235 goto done;
9236 }
9237 else {
9238 // no data has been sent; upper application is supposed
9239 // to retry on EAGAIN or EBUSY
9240 return posix_error();
9241 }
9242 }
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009243 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009244 }
9245 goto done;
9246
9247done:
9248 #if !defined(HAVE_LARGEFILE_SUPPORT)
9249 return Py_BuildValue("l", sbytes);
9250 #else
9251 return Py_BuildValue("L", sbytes);
9252 #endif
9253
9254#else
9255 Py_ssize_t count;
9256 PyObject *offobj;
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009257 static char *keywords[] = {"out_fd", "in_fd",
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009258 "offset", "count", NULL};
9259 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiOn:sendfile",
9260 keywords, &out, &in, &offobj, &count))
9261 return NULL;
Benjamin Peterson840ef8f2016-09-07 14:45:10 -07009262#ifdef __linux__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009263 if (offobj == Py_None) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009264 do {
9265 Py_BEGIN_ALLOW_THREADS
9266 ret = sendfile(out, in, NULL, count);
9267 Py_END_ALLOW_THREADS
9268 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009269 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009270 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodola'ff1a7352011-04-19 09:47:16 +02009271 return Py_BuildValue("n", ret);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009272 }
9273#endif
Larry Hastings2f936352014-08-05 14:04:04 +10009274 if (!Py_off_t_converter(offobj, &offset))
Antoine Pitroudcc20b82011-02-26 13:38:35 +00009275 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009276
9277 do {
9278 Py_BEGIN_ALLOW_THREADS
9279 ret = sendfile(out, in, &offset, count);
9280 Py_END_ALLOW_THREADS
9281 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009282 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009283 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009284 return Py_BuildValue("n", ret);
9285#endif
9286}
Larry Hastings2f936352014-08-05 14:04:04 +10009287#endif /* HAVE_SENDFILE */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009288
Larry Hastings2f936352014-08-05 14:04:04 +10009289
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009290#if defined(__APPLE__)
9291/*[clinic input]
9292os._fcopyfile
9293
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009294 in_fd: int
9295 out_fd: int
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009296 flags: int
9297 /
9298
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009299Efficiently copy content or metadata of 2 regular file descriptors (macOS).
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009300[clinic start generated code]*/
9301
9302static PyObject *
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009303os__fcopyfile_impl(PyObject *module, int in_fd, int out_fd, int flags)
9304/*[clinic end generated code: output=c9d1a35a992e401b input=1e34638a86948795]*/
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009305{
9306 int ret;
9307
9308 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009309 ret = fcopyfile(in_fd, out_fd, NULL, flags);
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009310 Py_END_ALLOW_THREADS
9311 if (ret < 0)
9312 return posix_error();
9313 Py_RETURN_NONE;
9314}
9315#endif
9316
9317
Larry Hastings2f936352014-08-05 14:04:04 +10009318/*[clinic input]
9319os.fstat
9320
9321 fd : int
9322
9323Perform a stat system call on the given file descriptor.
9324
9325Like stat(), but for an open file descriptor.
9326Equivalent to os.stat(fd).
9327[clinic start generated code]*/
9328
Larry Hastings2f936352014-08-05 14:04:04 +10009329static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009330os_fstat_impl(PyObject *module, int fd)
9331/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009332{
Victor Stinner8c62be82010-05-06 00:08:46 +00009333 STRUCT_STAT st;
9334 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009335 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009336
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009337 do {
9338 Py_BEGIN_ALLOW_THREADS
9339 res = FSTAT(fd, &st);
9340 Py_END_ALLOW_THREADS
9341 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner8c62be82010-05-06 00:08:46 +00009342 if (res != 0) {
Martin v. Löwis14694662006-02-03 12:54:16 +00009343#ifdef MS_WINDOWS
Victor Stinnerb024e842012-10-31 22:24:06 +01009344 return PyErr_SetFromWindowsErr(0);
Martin v. Löwis14694662006-02-03 12:54:16 +00009345#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009346 return (!async_err) ? posix_error() : NULL;
Martin v. Löwis14694662006-02-03 12:54:16 +00009347#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00009348 }
Tim Peters5aa91602002-01-30 05:46:57 +00009349
Victor Stinner4195b5c2012-02-08 23:03:19 +01009350 return _pystat_fromstructstat(&st);
Guido van Rossum687dd131993-05-17 08:34:16 +00009351}
9352
Larry Hastings2f936352014-08-05 14:04:04 +10009353
9354/*[clinic input]
9355os.isatty -> bool
9356 fd: int
9357 /
9358
9359Return True if the fd is connected to a terminal.
9360
9361Return True if the file descriptor is an open file descriptor
9362connected to the slave end of a terminal.
9363[clinic start generated code]*/
9364
Larry Hastings2f936352014-08-05 14:04:04 +10009365static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009366os_isatty_impl(PyObject *module, int fd)
9367/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009368{
Steve Dower8fc89802015-04-12 00:26:27 -04009369 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -04009370 _Py_BEGIN_SUPPRESS_IPH
9371 return_value = isatty(fd);
9372 _Py_END_SUPPRESS_IPH
9373 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +10009374}
9375
9376
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009377#ifdef HAVE_PIPE
Larry Hastings2f936352014-08-05 14:04:04 +10009378/*[clinic input]
9379os.pipe
9380
9381Create a pipe.
9382
9383Returns a tuple of two file descriptors:
9384 (read_fd, write_fd)
9385[clinic start generated code]*/
9386
Larry Hastings2f936352014-08-05 14:04:04 +10009387static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009388os_pipe_impl(PyObject *module)
9389/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00009390{
Victor Stinner8c62be82010-05-06 00:08:46 +00009391 int fds[2];
Victor Stinnerdaf45552013-08-28 00:53:59 +02009392#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00009393 HANDLE read, write;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009394 SECURITY_ATTRIBUTES attr;
Victor Stinner8c62be82010-05-06 00:08:46 +00009395 BOOL ok;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009396#else
9397 int res;
9398#endif
9399
9400#ifdef MS_WINDOWS
9401 attr.nLength = sizeof(attr);
9402 attr.lpSecurityDescriptor = NULL;
9403 attr.bInheritHandle = FALSE;
9404
9405 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08009406 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009407 ok = CreatePipe(&read, &write, &attr, 0);
9408 if (ok) {
Benjamin Petersonca470632016-09-06 13:47:26 -07009409 fds[0] = _open_osfhandle((intptr_t)read, _O_RDONLY);
9410 fds[1] = _open_osfhandle((intptr_t)write, _O_WRONLY);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009411 if (fds[0] == -1 || fds[1] == -1) {
9412 CloseHandle(read);
9413 CloseHandle(write);
9414 ok = 0;
9415 }
9416 }
Steve Dowerc3630612016-11-19 18:41:16 -08009417 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009418 Py_END_ALLOW_THREADS
9419
Victor Stinner8c62be82010-05-06 00:08:46 +00009420 if (!ok)
Victor Stinnerb024e842012-10-31 22:24:06 +01009421 return PyErr_SetFromWindowsErr(0);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009422#else
9423
9424#ifdef HAVE_PIPE2
9425 Py_BEGIN_ALLOW_THREADS
9426 res = pipe2(fds, O_CLOEXEC);
9427 Py_END_ALLOW_THREADS
9428
9429 if (res != 0 && errno == ENOSYS)
9430 {
9431#endif
9432 Py_BEGIN_ALLOW_THREADS
9433 res = pipe(fds);
9434 Py_END_ALLOW_THREADS
9435
9436 if (res == 0) {
9437 if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
9438 close(fds[0]);
9439 close(fds[1]);
9440 return NULL;
9441 }
9442 if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
9443 close(fds[0]);
9444 close(fds[1]);
9445 return NULL;
9446 }
9447 }
9448#ifdef HAVE_PIPE2
9449 }
9450#endif
9451
9452 if (res != 0)
9453 return PyErr_SetFromErrno(PyExc_OSError);
9454#endif /* !MS_WINDOWS */
9455 return Py_BuildValue("(ii)", fds[0], fds[1]);
Guido van Rossum687dd131993-05-17 08:34:16 +00009456}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009457#endif /* HAVE_PIPE */
9458
Larry Hastings2f936352014-08-05 14:04:04 +10009459
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009460#ifdef HAVE_PIPE2
Larry Hastings2f936352014-08-05 14:04:04 +10009461/*[clinic input]
9462os.pipe2
9463
9464 flags: int
9465 /
9466
9467Create a pipe with flags set atomically.
9468
9469Returns a tuple of two file descriptors:
9470 (read_fd, write_fd)
9471
9472flags can be constructed by ORing together one or more of these values:
9473O_NONBLOCK, O_CLOEXEC.
9474[clinic start generated code]*/
9475
Larry Hastings2f936352014-08-05 14:04:04 +10009476static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009477os_pipe2_impl(PyObject *module, int flags)
9478/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009479{
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009480 int fds[2];
9481 int res;
9482
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009483 res = pipe2(fds, flags);
9484 if (res != 0)
9485 return posix_error();
9486 return Py_BuildValue("(ii)", fds[0], fds[1]);
9487}
9488#endif /* HAVE_PIPE2 */
9489
Larry Hastings2f936352014-08-05 14:04:04 +10009490
Ross Lagerwall7807c352011-03-17 20:20:30 +02009491#ifdef HAVE_WRITEV
Larry Hastings2f936352014-08-05 14:04:04 +10009492/*[clinic input]
9493os.writev -> Py_ssize_t
9494 fd: int
9495 buffers: object
9496 /
9497
9498Iterate over buffers, and write the contents of each to a file descriptor.
9499
9500Returns the total number of bytes written.
9501buffers must be a sequence of bytes-like objects.
9502[clinic start generated code]*/
9503
Larry Hastings2f936352014-08-05 14:04:04 +10009504static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009505os_writev_impl(PyObject *module, int fd, PyObject *buffers)
9506/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009507{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009508 Py_ssize_t cnt;
Larry Hastings2f936352014-08-05 14:04:04 +10009509 Py_ssize_t result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009510 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009511 struct iovec *iov;
9512 Py_buffer *buf;
Larry Hastings2f936352014-08-05 14:04:04 +10009513
9514 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009515 PyErr_SetString(PyExc_TypeError,
9516 "writev() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009517 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009518 }
Larry Hastings2f936352014-08-05 14:04:04 +10009519 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009520 if (cnt < 0)
9521 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009522
Larry Hastings2f936352014-08-05 14:04:04 +10009523 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9524 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009525 }
9526
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009527 do {
9528 Py_BEGIN_ALLOW_THREADS
9529 result = writev(fd, iov, cnt);
9530 Py_END_ALLOW_THREADS
9531 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009532
9533 iov_cleanup(iov, buf, cnt);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009534 if (result < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009535 posix_error();
Victor Stinner57ddf782014-01-08 15:21:28 +01009536
Georg Brandl306336b2012-06-24 12:55:33 +02009537 return result;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009538}
Larry Hastings2f936352014-08-05 14:04:04 +10009539#endif /* HAVE_WRITEV */
9540
9541
9542#ifdef HAVE_PWRITE
9543/*[clinic input]
9544os.pwrite -> Py_ssize_t
9545
9546 fd: int
9547 buffer: Py_buffer
9548 offset: Py_off_t
9549 /
9550
9551Write bytes to a file descriptor starting at a particular offset.
9552
9553Write buffer to fd, starting at offset bytes from the beginning of
9554the file. Returns the number of bytes writte. Does not change the
9555current file offset.
9556[clinic start generated code]*/
9557
Larry Hastings2f936352014-08-05 14:04:04 +10009558static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009559os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
9560/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009561{
9562 Py_ssize_t size;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009563 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009564
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009565 do {
9566 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009567 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009568 size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009569 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009570 Py_END_ALLOW_THREADS
9571 } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +10009572
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009573 if (size < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009574 posix_error();
9575 return size;
9576}
9577#endif /* HAVE_PWRITE */
9578
Pablo Galindo4defba32018-01-27 16:16:37 +00009579#if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
9580/*[clinic input]
9581os.pwritev -> Py_ssize_t
9582
9583 fd: int
9584 buffers: object
9585 offset: Py_off_t
9586 flags: int = 0
9587 /
9588
9589Writes the contents of bytes-like objects to a file descriptor at a given offset.
9590
9591Combines the functionality of writev() and pwrite(). All buffers must be a sequence
9592of bytes-like objects. Buffers are processed in array order. Entire contents of first
9593buffer is written before proceeding to second, and so on. The operating system may
9594set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
9595This function writes the contents of each object to the file descriptor and returns
9596the total number of bytes written.
9597
9598The flags argument contains a bitwise OR of zero or more of the following flags:
9599
9600- RWF_DSYNC
9601- RWF_SYNC
9602
9603Using non-zero flags requires Linux 4.7 or newer.
9604[clinic start generated code]*/
9605
9606static Py_ssize_t
9607os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9608 int flags)
9609/*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=803dc5ddbf0cfd3b]*/
9610{
9611 Py_ssize_t cnt;
9612 Py_ssize_t result;
9613 int async_err = 0;
9614 struct iovec *iov;
9615 Py_buffer *buf;
9616
9617 if (!PySequence_Check(buffers)) {
9618 PyErr_SetString(PyExc_TypeError,
9619 "pwritev() arg 2 must be a sequence");
9620 return -1;
9621 }
9622
9623 cnt = PySequence_Size(buffers);
9624 if (cnt < 0) {
9625 return -1;
9626 }
9627
9628#ifndef HAVE_PWRITEV2
9629 if(flags != 0) {
9630 argument_unavailable_error("pwritev2", "flags");
9631 return -1;
9632 }
9633#endif
9634
9635 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9636 return -1;
9637 }
9638#ifdef HAVE_PWRITEV2
9639 do {
9640 Py_BEGIN_ALLOW_THREADS
9641 _Py_BEGIN_SUPPRESS_IPH
9642 result = pwritev2(fd, iov, cnt, offset, flags);
9643 _Py_END_SUPPRESS_IPH
9644 Py_END_ALLOW_THREADS
9645 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9646#else
9647 do {
9648 Py_BEGIN_ALLOW_THREADS
9649 _Py_BEGIN_SUPPRESS_IPH
9650 result = pwritev(fd, iov, cnt, offset);
9651 _Py_END_SUPPRESS_IPH
9652 Py_END_ALLOW_THREADS
9653 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9654#endif
9655
9656 iov_cleanup(iov, buf, cnt);
9657 if (result < 0) {
9658 if (!async_err) {
9659 posix_error();
9660 }
9661 return -1;
9662 }
9663
9664 return result;
9665}
9666#endif /* HAVE_PWRITEV */
9667
Pablo Galindoaac4d032019-05-31 19:39:47 +01009668#ifdef HAVE_COPY_FILE_RANGE
9669/*[clinic input]
9670
9671os.copy_file_range
9672 src: int
9673 Source file descriptor.
9674 dst: int
9675 Destination file descriptor.
9676 count: Py_ssize_t
9677 Number of bytes to copy.
9678 offset_src: object = None
9679 Starting offset in src.
9680 offset_dst: object = None
9681 Starting offset in dst.
9682
9683Copy count bytes from one file descriptor to another.
9684
9685If offset_src is None, then src is read from the current position;
9686respectively for offset_dst.
9687[clinic start generated code]*/
9688
9689static PyObject *
9690os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
9691 PyObject *offset_src, PyObject *offset_dst)
9692/*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
9693{
9694 off_t offset_src_val, offset_dst_val;
9695 off_t *p_offset_src = NULL;
9696 off_t *p_offset_dst = NULL;
9697 Py_ssize_t ret;
9698 int async_err = 0;
9699 /* The flags argument is provided to allow
9700 * for future extensions and currently must be to 0. */
9701 int flags = 0;
Pablo Galindo4defba32018-01-27 16:16:37 +00009702
9703
Pablo Galindoaac4d032019-05-31 19:39:47 +01009704 if (count < 0) {
9705 PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
9706 return NULL;
9707 }
9708
9709 if (offset_src != Py_None) {
9710 if (!Py_off_t_converter(offset_src, &offset_src_val)) {
9711 return NULL;
9712 }
9713 p_offset_src = &offset_src_val;
9714 }
9715
9716 if (offset_dst != Py_None) {
9717 if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
9718 return NULL;
9719 }
9720 p_offset_dst = &offset_dst_val;
9721 }
9722
9723 do {
9724 Py_BEGIN_ALLOW_THREADS
9725 ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
9726 Py_END_ALLOW_THREADS
9727 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9728
9729 if (ret < 0) {
9730 return (!async_err) ? posix_error() : NULL;
9731 }
9732
9733 return PyLong_FromSsize_t(ret);
9734}
9735#endif /* HAVE_COPY_FILE_RANGE*/
Larry Hastings2f936352014-08-05 14:04:04 +10009736
9737#ifdef HAVE_MKFIFO
9738/*[clinic input]
9739os.mkfifo
9740
9741 path: path_t
9742 mode: int=0o666
9743 *
9744 dir_fd: dir_fd(requires='mkfifoat')=None
9745
9746Create a "fifo" (a POSIX named pipe).
9747
9748If dir_fd is not None, it should be a file descriptor open to a directory,
9749 and path should be relative; path will then be relative to that directory.
9750dir_fd may not be implemented on your platform.
9751 If it is unavailable, using it will raise a NotImplementedError.
9752[clinic start generated code]*/
9753
Larry Hastings2f936352014-08-05 14:04:04 +10009754static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009755os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
9756/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009757{
9758 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009759 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009760
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009761 do {
9762 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009763#ifdef HAVE_MKFIFOAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009764 if (dir_fd != DEFAULT_DIR_FD)
9765 result = mkfifoat(dir_fd, path->narrow, mode);
9766 else
Ross Lagerwall7807c352011-03-17 20:20:30 +02009767#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009768 result = mkfifo(path->narrow, mode);
9769 Py_END_ALLOW_THREADS
9770 } while (result != 0 && errno == EINTR &&
9771 !(async_err = PyErr_CheckSignals()));
9772 if (result != 0)
9773 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009774
9775 Py_RETURN_NONE;
9776}
9777#endif /* HAVE_MKFIFO */
9778
9779
9780#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
9781/*[clinic input]
9782os.mknod
9783
9784 path: path_t
9785 mode: int=0o600
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009786 device: dev_t=0
Larry Hastings2f936352014-08-05 14:04:04 +10009787 *
9788 dir_fd: dir_fd(requires='mknodat')=None
9789
9790Create a node in the file system.
9791
9792Create a node in the file system (file, device special file or named pipe)
9793at path. mode specifies both the permissions to use and the
9794type of node to be created, being combined (bitwise OR) with one of
9795S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
9796device defines the newly created device special file (probably using
9797os.makedev()). Otherwise device is ignored.
9798
9799If dir_fd is not None, it should be a file descriptor open to a directory,
9800 and path should be relative; path will then be relative to that directory.
9801dir_fd may not be implemented on your platform.
9802 If it is unavailable, using it will raise a NotImplementedError.
9803[clinic start generated code]*/
9804
Larry Hastings2f936352014-08-05 14:04:04 +10009805static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009806os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
Larry Hastings89964c42015-04-14 18:07:59 -04009807 int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009808/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009809{
9810 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009811 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009812
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009813 do {
9814 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009815#ifdef HAVE_MKNODAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009816 if (dir_fd != DEFAULT_DIR_FD)
9817 result = mknodat(dir_fd, path->narrow, mode, device);
9818 else
Larry Hastings2f936352014-08-05 14:04:04 +10009819#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009820 result = mknod(path->narrow, mode, device);
9821 Py_END_ALLOW_THREADS
9822 } while (result != 0 && errno == EINTR &&
9823 !(async_err = PyErr_CheckSignals()));
9824 if (result != 0)
9825 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009826
9827 Py_RETURN_NONE;
9828}
9829#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
9830
9831
9832#ifdef HAVE_DEVICE_MACROS
9833/*[clinic input]
9834os.major -> unsigned_int
9835
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009836 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009837 /
9838
9839Extracts a device major number from a raw device number.
9840[clinic start generated code]*/
9841
Larry Hastings2f936352014-08-05 14:04:04 +10009842static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009843os_major_impl(PyObject *module, dev_t device)
9844/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009845{
9846 return major(device);
9847}
9848
9849
9850/*[clinic input]
9851os.minor -> unsigned_int
9852
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009853 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009854 /
9855
9856Extracts a device minor number from a raw device number.
9857[clinic start generated code]*/
9858
Larry Hastings2f936352014-08-05 14:04:04 +10009859static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009860os_minor_impl(PyObject *module, dev_t device)
9861/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009862{
9863 return minor(device);
9864}
9865
9866
9867/*[clinic input]
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009868os.makedev -> dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009869
9870 major: int
9871 minor: int
9872 /
9873
9874Composes a raw device number from the major and minor device numbers.
9875[clinic start generated code]*/
9876
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009877static dev_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009878os_makedev_impl(PyObject *module, int major, int minor)
9879/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009880{
9881 return makedev(major, minor);
9882}
9883#endif /* HAVE_DEVICE_MACROS */
9884
9885
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009886#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009887/*[clinic input]
9888os.ftruncate
9889
9890 fd: int
9891 length: Py_off_t
9892 /
9893
9894Truncate a file, specified by file descriptor, to a specific length.
9895[clinic start generated code]*/
9896
Larry Hastings2f936352014-08-05 14:04:04 +10009897static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009898os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
9899/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009900{
9901 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009902 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009903
Steve Dowerb82e17e2019-05-23 08:45:22 -07009904 if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
9905 return NULL;
9906 }
9907
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009908 do {
9909 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009910 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009911#ifdef MS_WINDOWS
9912 result = _chsize_s(fd, length);
9913#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009914 result = ftruncate(fd, length);
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009915#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009916 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009917 Py_END_ALLOW_THREADS
9918 } while (result != 0 && errno == EINTR &&
9919 !(async_err = PyErr_CheckSignals()));
9920 if (result != 0)
9921 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009922 Py_RETURN_NONE;
9923}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009924#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009925
9926
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009927#if defined HAVE_TRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009928/*[clinic input]
9929os.truncate
9930 path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
9931 length: Py_off_t
9932
9933Truncate a file, specified by path, to a specific length.
9934
9935On some platforms, path may also be specified as an open file descriptor.
9936 If this functionality is unavailable, using it raises an exception.
9937[clinic start generated code]*/
9938
Larry Hastings2f936352014-08-05 14:04:04 +10009939static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009940os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
9941/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009942{
9943 int result;
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009944#ifdef MS_WINDOWS
9945 int fd;
9946#endif
9947
9948 if (path->fd != -1)
9949 return os_ftruncate_impl(module, path->fd, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009950
Steve Dowerb82e17e2019-05-23 08:45:22 -07009951 if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
9952 return NULL;
9953 }
9954
Larry Hastings2f936352014-08-05 14:04:04 +10009955 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009956 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009957#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07009958 fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
Victor Stinnercc0bbbc2015-04-25 00:21:52 +02009959 if (fd < 0)
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009960 result = -1;
9961 else {
9962 result = _chsize_s(fd, length);
9963 close(fd);
9964 if (result < 0)
9965 errno = result;
9966 }
9967#else
9968 result = truncate(path->narrow, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009969#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009970 _Py_END_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10009971 Py_END_ALLOW_THREADS
9972 if (result < 0)
Alexey Izbyshev83460312018-10-20 03:28:22 +03009973 return posix_path_error(path);
Larry Hastings2f936352014-08-05 14:04:04 +10009974
9975 Py_RETURN_NONE;
9976}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009977#endif /* HAVE_TRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009978
Ross Lagerwall7807c352011-03-17 20:20:30 +02009979
Victor Stinnerd6b17692014-09-30 12:20:05 +02009980/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
9981 and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
9982 defined, which is the case in Python on AIX. AIX bug report:
9983 http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
9984#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
9985# define POSIX_FADVISE_AIX_BUG
9986#endif
9987
Victor Stinnerec39e262014-09-30 12:35:58 +02009988
Victor Stinnerd6b17692014-09-30 12:20:05 +02009989#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +10009990/*[clinic input]
9991os.posix_fallocate
9992
9993 fd: int
9994 offset: Py_off_t
9995 length: Py_off_t
9996 /
9997
9998Ensure a file has allocated at least a particular number of bytes on disk.
9999
10000Ensure that the file specified by fd encompasses a range of bytes
10001starting at offset bytes from the beginning and continuing for length bytes.
10002[clinic start generated code]*/
10003
Larry Hastings2f936352014-08-05 14:04:04 +100010004static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010005os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -040010006 Py_off_t length)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010007/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010008{
10009 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010010 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010011
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010012 do {
10013 Py_BEGIN_ALLOW_THREADS
10014 result = posix_fallocate(fd, offset, length);
10015 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010016 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10017
10018 if (result == 0)
10019 Py_RETURN_NONE;
10020
10021 if (async_err)
10022 return NULL;
10023
10024 errno = result;
10025 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010026}
Victor Stinnerec39e262014-09-30 12:35:58 +020010027#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
Larry Hastings2f936352014-08-05 14:04:04 +100010028
Ross Lagerwall7807c352011-03-17 20:20:30 +020010029
Victor Stinnerd6b17692014-09-30 12:20:05 +020010030#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +100010031/*[clinic input]
10032os.posix_fadvise
10033
10034 fd: int
10035 offset: Py_off_t
10036 length: Py_off_t
10037 advice: int
10038 /
10039
10040Announce an intention to access data in a specific pattern.
10041
10042Announce an intention to access data in a specific pattern, thus allowing
10043the kernel to make optimizations.
10044The advice applies to the region of the file specified by fd starting at
10045offset and continuing for length bytes.
10046advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
10047POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
10048POSIX_FADV_DONTNEED.
10049[clinic start generated code]*/
10050
Larry Hastings2f936352014-08-05 14:04:04 +100010051static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010052os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -040010053 Py_off_t length, int advice)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010054/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010055{
10056 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010057 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010058
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010059 do {
10060 Py_BEGIN_ALLOW_THREADS
10061 result = posix_fadvise(fd, offset, length, advice);
10062 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010063 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10064
10065 if (result == 0)
10066 Py_RETURN_NONE;
10067
10068 if (async_err)
10069 return NULL;
10070
10071 errno = result;
10072 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010073}
Victor Stinnerec39e262014-09-30 12:35:58 +020010074#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
Ross Lagerwall7807c352011-03-17 20:20:30 +020010075
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000010076
Thomas Hellerf78f12a2007-11-08 19:33:05 +000010077#ifdef MS_WINDOWS
Victor Stinner161e7b32020-01-24 11:53:44 +010010078static PyObject*
10079win32_putenv(PyObject *name, PyObject *value)
10080{
10081 /* Search from index 1 because on Windows starting '=' is allowed for
10082 defining hidden environment variables. */
10083 if (PyUnicode_GET_LENGTH(name) == 0 ||
10084 PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
10085 {
10086 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10087 return NULL;
10088 }
10089 PyObject *unicode;
10090 if (value != NULL) {
10091 unicode = PyUnicode_FromFormat("%U=%U", name, value);
10092 }
10093 else {
10094 unicode = PyUnicode_FromFormat("%U=", name);
10095 }
10096 if (unicode == NULL) {
10097 return NULL;
10098 }
10099
10100 Py_ssize_t size;
10101 /* PyUnicode_AsWideCharString() rejects embedded null characters */
10102 wchar_t *env = PyUnicode_AsWideCharString(unicode, &size);
10103 Py_DECREF(unicode);
10104
10105 if (env == NULL) {
10106 return NULL;
10107 }
10108 if (size > _MAX_ENV) {
10109 PyErr_Format(PyExc_ValueError,
10110 "the environment variable is longer than %u characters",
10111 _MAX_ENV);
10112 PyMem_Free(env);
10113 return NULL;
10114 }
10115
10116 /* _wputenv() and SetEnvironmentVariableW() update the environment in the
10117 Process Environment Block (PEB). _wputenv() also updates CRT 'environ'
10118 and '_wenviron' variables, whereas SetEnvironmentVariableW() does not.
10119
10120 Prefer _wputenv() to be compatible with C libraries using CRT
10121 variables and CRT functions using these variables (ex: getenv()). */
10122 int err = _wputenv(env);
10123 PyMem_Free(env);
10124
10125 if (err) {
10126 posix_error();
10127 return NULL;
10128 }
10129
10130 Py_RETURN_NONE;
10131}
10132#endif
10133
10134
10135#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010136/*[clinic input]
10137os.putenv
10138
10139 name: unicode
10140 value: unicode
10141 /
10142
10143Change or add an environment variable.
10144[clinic start generated code]*/
10145
Larry Hastings2f936352014-08-05 14:04:04 +100010146static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010147os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10148/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010149{
Victor Stinner161e7b32020-01-24 11:53:44 +010010150 return win32_putenv(name, value);
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010151}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010152#else
Larry Hastings2f936352014-08-05 14:04:04 +100010153/*[clinic input]
10154os.putenv
Guido van Rossumb6a47161997-09-15 22:54:34 +000010155
Larry Hastings2f936352014-08-05 14:04:04 +100010156 name: FSConverter
10157 value: FSConverter
10158 /
10159
10160Change or add an environment variable.
10161[clinic start generated code]*/
10162
Larry Hastings2f936352014-08-05 14:04:04 +100010163static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010164os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10165/*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010166{
Serhiy Storchaka77703942017-06-25 07:33:01 +030010167 const char *name_string = PyBytes_AS_STRING(name);
10168 const char *value_string = PyBytes_AS_STRING(value);
Larry Hastings2f936352014-08-05 14:04:04 +100010169
Serhiy Storchaka77703942017-06-25 07:33:01 +030010170 if (strchr(name_string, '=') != NULL) {
10171 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10172 return NULL;
10173 }
Victor Stinnerb477d192020-01-22 22:48:16 +010010174
Victor Stinnerb477d192020-01-22 22:48:16 +010010175 if (setenv(name_string, value_string, 1)) {
10176 return posix_error();
10177 }
Larry Hastings2f936352014-08-05 14:04:04 +100010178 Py_RETURN_NONE;
10179}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010180#endif /* !defined(MS_WINDOWS) */
Larry Hastings2f936352014-08-05 14:04:04 +100010181
10182
Victor Stinner161e7b32020-01-24 11:53:44 +010010183#ifdef MS_WINDOWS
10184/*[clinic input]
10185os.unsetenv
10186 name: unicode
10187 /
10188
10189Delete an environment variable.
10190[clinic start generated code]*/
10191
10192static PyObject *
10193os_unsetenv_impl(PyObject *module, PyObject *name)
10194/*[clinic end generated code: output=54c4137ab1834f02 input=4d6a1747cc526d2f]*/
10195{
10196 return win32_putenv(name, NULL);
10197}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010198#else
Larry Hastings2f936352014-08-05 14:04:04 +100010199/*[clinic input]
10200os.unsetenv
10201 name: FSConverter
10202 /
10203
10204Delete an environment variable.
10205[clinic start generated code]*/
10206
Larry Hastings2f936352014-08-05 14:04:04 +100010207static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010208os_unsetenv_impl(PyObject *module, PyObject *name)
10209/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010210{
Victor Stinner984890f2011-11-24 13:53:38 +010010211#ifdef HAVE_BROKEN_UNSETENV
10212 unsetenv(PyBytes_AS_STRING(name));
10213#else
Victor Stinner161e7b32020-01-24 11:53:44 +010010214 int err = unsetenv(PyBytes_AS_STRING(name));
10215 if (err) {
Victor Stinner60b385e2011-11-22 22:01:28 +010010216 return posix_error();
Victor Stinner161e7b32020-01-24 11:53:44 +010010217 }
Victor Stinner984890f2011-11-24 13:53:38 +010010218#endif
Guido van Rossumc524d952001-10-19 01:31:59 +000010219
Victor Stinner84ae1182010-05-06 22:05:07 +000010220 Py_RETURN_NONE;
Guido van Rossumc524d952001-10-19 01:31:59 +000010221}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010222#endif /* !MS_WINDOWS */
Guido van Rossumc524d952001-10-19 01:31:59 +000010223
Larry Hastings2f936352014-08-05 14:04:04 +100010224
10225/*[clinic input]
10226os.strerror
10227
10228 code: int
10229 /
10230
10231Translate an error code to a message string.
10232[clinic start generated code]*/
10233
Larry Hastings2f936352014-08-05 14:04:04 +100010234static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010235os_strerror_impl(PyObject *module, int code)
10236/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010237{
10238 char *message = strerror(code);
Victor Stinner8c62be82010-05-06 00:08:46 +000010239 if (message == NULL) {
10240 PyErr_SetString(PyExc_ValueError,
10241 "strerror() argument out of range");
10242 return NULL;
10243 }
Victor Stinner1b579672011-12-17 05:47:23 +010010244 return PyUnicode_DecodeLocale(message, "surrogateescape");
Guido van Rossumb6a47161997-09-15 22:54:34 +000010245}
Guido van Rossumb6a47161997-09-15 22:54:34 +000010246
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010247
Guido van Rossumc9641791998-08-04 15:26:23 +000010248#ifdef HAVE_SYS_WAIT_H
Fred Drake106c1a02002-04-23 15:58:02 +000010249#ifdef WCOREDUMP
Larry Hastings2f936352014-08-05 14:04:04 +100010250/*[clinic input]
10251os.WCOREDUMP -> bool
10252
10253 status: int
10254 /
10255
10256Return True if the process returning status was dumped to a core file.
10257[clinic start generated code]*/
10258
Larry Hastings2f936352014-08-05 14:04:04 +100010259static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010260os_WCOREDUMP_impl(PyObject *module, int status)
10261/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010262{
10263 WAIT_TYPE wait_status;
10264 WAIT_STATUS_INT(wait_status) = status;
10265 return WCOREDUMP(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010266}
10267#endif /* WCOREDUMP */
10268
Larry Hastings2f936352014-08-05 14:04:04 +100010269
Fred Drake106c1a02002-04-23 15:58:02 +000010270#ifdef WIFCONTINUED
Larry Hastings2f936352014-08-05 14:04:04 +100010271/*[clinic input]
10272os.WIFCONTINUED -> bool
10273
10274 status: int
10275
10276Return True if a particular process was continued from a job control stop.
10277
10278Return True if the process returning status was continued from a
10279job control stop.
10280[clinic start generated code]*/
10281
Larry Hastings2f936352014-08-05 14:04:04 +100010282static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010283os_WIFCONTINUED_impl(PyObject *module, int status)
10284/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010285{
10286 WAIT_TYPE wait_status;
10287 WAIT_STATUS_INT(wait_status) = status;
10288 return WIFCONTINUED(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010289}
10290#endif /* WIFCONTINUED */
10291
Larry Hastings2f936352014-08-05 14:04:04 +100010292
Guido van Rossumc9641791998-08-04 15:26:23 +000010293#ifdef WIFSTOPPED
Larry Hastings2f936352014-08-05 14:04:04 +100010294/*[clinic input]
10295os.WIFSTOPPED -> bool
10296
10297 status: int
10298
10299Return True if the process returning status was stopped.
10300[clinic start generated code]*/
10301
Larry Hastings2f936352014-08-05 14:04:04 +100010302static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010303os_WIFSTOPPED_impl(PyObject *module, int status)
10304/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010305{
10306 WAIT_TYPE wait_status;
10307 WAIT_STATUS_INT(wait_status) = status;
10308 return WIFSTOPPED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010309}
10310#endif /* WIFSTOPPED */
10311
Larry Hastings2f936352014-08-05 14:04:04 +100010312
Guido van Rossumc9641791998-08-04 15:26:23 +000010313#ifdef WIFSIGNALED
Larry Hastings2f936352014-08-05 14:04:04 +100010314/*[clinic input]
10315os.WIFSIGNALED -> bool
10316
10317 status: int
10318
10319Return True if the process returning status was terminated by a signal.
10320[clinic start generated code]*/
10321
Larry Hastings2f936352014-08-05 14:04:04 +100010322static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010323os_WIFSIGNALED_impl(PyObject *module, int status)
10324/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010325{
10326 WAIT_TYPE wait_status;
10327 WAIT_STATUS_INT(wait_status) = status;
10328 return WIFSIGNALED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010329}
10330#endif /* WIFSIGNALED */
10331
Larry Hastings2f936352014-08-05 14:04:04 +100010332
Guido van Rossumc9641791998-08-04 15:26:23 +000010333#ifdef WIFEXITED
Larry Hastings2f936352014-08-05 14:04:04 +100010334/*[clinic input]
10335os.WIFEXITED -> bool
10336
10337 status: int
10338
10339Return True if the process returning status exited via the exit() system call.
10340[clinic start generated code]*/
10341
Larry Hastings2f936352014-08-05 14:04:04 +100010342static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010343os_WIFEXITED_impl(PyObject *module, int status)
10344/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010345{
10346 WAIT_TYPE wait_status;
10347 WAIT_STATUS_INT(wait_status) = status;
10348 return WIFEXITED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010349}
10350#endif /* WIFEXITED */
10351
Larry Hastings2f936352014-08-05 14:04:04 +100010352
Guido van Rossum54ecc3d1999-01-27 17:53:11 +000010353#ifdef WEXITSTATUS
Larry Hastings2f936352014-08-05 14:04:04 +100010354/*[clinic input]
10355os.WEXITSTATUS -> int
10356
10357 status: int
10358
10359Return the process return code from status.
10360[clinic start generated code]*/
10361
Larry Hastings2f936352014-08-05 14:04:04 +100010362static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010363os_WEXITSTATUS_impl(PyObject *module, int status)
10364/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010365{
10366 WAIT_TYPE wait_status;
10367 WAIT_STATUS_INT(wait_status) = status;
10368 return WEXITSTATUS(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010369}
10370#endif /* WEXITSTATUS */
10371
Larry Hastings2f936352014-08-05 14:04:04 +100010372
Guido van Rossumc9641791998-08-04 15:26:23 +000010373#ifdef WTERMSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010374/*[clinic input]
10375os.WTERMSIG -> int
10376
10377 status: int
10378
10379Return the signal that terminated the process that provided the status value.
10380[clinic start generated code]*/
10381
Larry Hastings2f936352014-08-05 14:04:04 +100010382static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010383os_WTERMSIG_impl(PyObject *module, int status)
10384/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010385{
10386 WAIT_TYPE wait_status;
10387 WAIT_STATUS_INT(wait_status) = status;
10388 return WTERMSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010389}
10390#endif /* WTERMSIG */
10391
Larry Hastings2f936352014-08-05 14:04:04 +100010392
Guido van Rossumc9641791998-08-04 15:26:23 +000010393#ifdef WSTOPSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010394/*[clinic input]
10395os.WSTOPSIG -> int
10396
10397 status: int
10398
10399Return the signal that stopped the process that provided the status value.
10400[clinic start generated code]*/
10401
Larry Hastings2f936352014-08-05 14:04:04 +100010402static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010403os_WSTOPSIG_impl(PyObject *module, int status)
10404/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010405{
10406 WAIT_TYPE wait_status;
10407 WAIT_STATUS_INT(wait_status) = status;
10408 return WSTOPSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010409}
10410#endif /* WSTOPSIG */
Guido van Rossumc9641791998-08-04 15:26:23 +000010411#endif /* HAVE_SYS_WAIT_H */
10412
10413
Thomas Wouters477c8d52006-05-27 19:21:47 +000010414#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossumd5753e11999-10-19 13:29:23 +000010415#ifdef _SCO_DS
10416/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
10417 needed definitions in sys/statvfs.h */
10418#define _SVID3
10419#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000010420#include <sys/statvfs.h>
10421
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010422static PyObject*
10423_pystatvfs_fromstructstatvfs(struct statvfs st) {
Eddie Elizondob3966632019-11-05 07:16:14 -080010424 PyObject *StatVFSResultType = _posixstate_global->StatVFSResultType;
10425 PyObject *v = PyStructSequence_New((PyTypeObject *)StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000010426 if (v == NULL)
10427 return NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010428
10429#if !defined(HAVE_LARGEFILE_SUPPORT)
Victor Stinner8c62be82010-05-06 00:08:46 +000010430 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10431 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10432 PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
10433 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
10434 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
10435 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
10436 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
10437 PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
10438 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10439 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010440#else
Victor Stinner8c62be82010-05-06 00:08:46 +000010441 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10442 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10443 PyStructSequence_SET_ITEM(v, 2,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010444 PyLong_FromLongLong((long long) st.f_blocks));
Victor Stinner8c62be82010-05-06 00:08:46 +000010445 PyStructSequence_SET_ITEM(v, 3,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010446 PyLong_FromLongLong((long long) st.f_bfree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010447 PyStructSequence_SET_ITEM(v, 4,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010448 PyLong_FromLongLong((long long) st.f_bavail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010449 PyStructSequence_SET_ITEM(v, 5,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010450 PyLong_FromLongLong((long long) st.f_files));
Victor Stinner8c62be82010-05-06 00:08:46 +000010451 PyStructSequence_SET_ITEM(v, 6,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010452 PyLong_FromLongLong((long long) st.f_ffree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010453 PyStructSequence_SET_ITEM(v, 7,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010454 PyLong_FromLongLong((long long) st.f_favail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010455 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10456 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010457#endif
Michael Felt502d5512018-01-05 13:01:58 +010010458/* The _ALL_SOURCE feature test macro defines f_fsid as a structure
10459 * (issue #32390). */
10460#if defined(_AIX) && defined(_ALL_SOURCE)
10461 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
10462#else
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +010010463 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid));
Michael Felt502d5512018-01-05 13:01:58 +010010464#endif
Victor Stinnerf0a7bac2013-10-30 18:55:24 +010010465 if (PyErr_Occurred()) {
10466 Py_DECREF(v);
10467 return NULL;
10468 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010469
Victor Stinner8c62be82010-05-06 00:08:46 +000010470 return v;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010471}
10472
Larry Hastings2f936352014-08-05 14:04:04 +100010473
10474/*[clinic input]
10475os.fstatvfs
10476 fd: int
10477 /
10478
10479Perform an fstatvfs system call on the given fd.
10480
10481Equivalent to statvfs(fd).
10482[clinic start generated code]*/
10483
Larry Hastings2f936352014-08-05 14:04:04 +100010484static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010485os_fstatvfs_impl(PyObject *module, int fd)
10486/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010487{
10488 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010489 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010490 struct statvfs st;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010491
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010492 do {
10493 Py_BEGIN_ALLOW_THREADS
10494 result = fstatvfs(fd, &st);
10495 Py_END_ALLOW_THREADS
10496 } while (result != 0 && errno == EINTR &&
10497 !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +100010498 if (result != 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010499 return (!async_err) ? posix_error() : NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010500
Victor Stinner8c62be82010-05-06 00:08:46 +000010501 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010502}
Larry Hastings2f936352014-08-05 14:04:04 +100010503#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
Guido van Rossum94f6f721999-01-06 18:42:14 +000010504
10505
Thomas Wouters477c8d52006-05-27 19:21:47 +000010506#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossum94f6f721999-01-06 18:42:14 +000010507#include <sys/statvfs.h>
Larry Hastings2f936352014-08-05 14:04:04 +100010508/*[clinic input]
10509os.statvfs
Guido van Rossum94f6f721999-01-06 18:42:14 +000010510
Larry Hastings2f936352014-08-05 14:04:04 +100010511 path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
10512
10513Perform a statvfs system call on the given path.
10514
10515path may always be specified as a string.
10516On some platforms, path may also be specified as an open file descriptor.
10517 If this functionality is unavailable, using it raises an exception.
10518[clinic start generated code]*/
10519
Larry Hastings2f936352014-08-05 14:04:04 +100010520static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010521os_statvfs_impl(PyObject *module, path_t *path)
10522/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010523{
10524 int result;
10525 struct statvfs st;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010526
10527 Py_BEGIN_ALLOW_THREADS
10528#ifdef HAVE_FSTATVFS
Larry Hastings2f936352014-08-05 14:04:04 +100010529 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -070010530#ifdef __APPLE__
10531 /* handle weak-linking on Mac OS X 10.3 */
10532 if (fstatvfs == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010533 fd_specified("statvfs", path->fd);
10534 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010535 }
10536#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010537 result = fstatvfs(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010538 }
10539 else
10540#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010541 result = statvfs(path->narrow, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010542 Py_END_ALLOW_THREADS
10543
10544 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100010545 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010546 }
10547
Larry Hastings2f936352014-08-05 14:04:04 +100010548 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010549}
Larry Hastings2f936352014-08-05 14:04:04 +100010550#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
10551
Guido van Rossum94f6f721999-01-06 18:42:14 +000010552
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010553#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010554/*[clinic input]
10555os._getdiskusage
10556
Steve Dower23ad6d02018-02-22 10:39:10 -080010557 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +100010558
10559Return disk usage statistics about the given path as a (total, free) tuple.
10560[clinic start generated code]*/
10561
Larry Hastings2f936352014-08-05 14:04:04 +100010562static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -080010563os__getdiskusage_impl(PyObject *module, path_t *path)
10564/*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010565{
10566 BOOL retval;
10567 ULARGE_INTEGER _, total, free;
Joe Pamerc8c02492018-09-25 10:57:36 -040010568 DWORD err = 0;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010569
10570 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -080010571 retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010572 Py_END_ALLOW_THREADS
Joe Pamerc8c02492018-09-25 10:57:36 -040010573 if (retval == 0) {
10574 if (GetLastError() == ERROR_DIRECTORY) {
10575 wchar_t *dir_path = NULL;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010576
Joe Pamerc8c02492018-09-25 10:57:36 -040010577 dir_path = PyMem_New(wchar_t, path->length + 1);
10578 if (dir_path == NULL) {
10579 return PyErr_NoMemory();
10580 }
10581
10582 wcscpy_s(dir_path, path->length + 1, path->wide);
10583
10584 if (_dirnameW(dir_path) != -1) {
10585 Py_BEGIN_ALLOW_THREADS
10586 retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
10587 Py_END_ALLOW_THREADS
10588 }
10589 /* Record the last error in case it's modified by PyMem_Free. */
10590 err = GetLastError();
10591 PyMem_Free(dir_path);
10592 if (retval) {
10593 goto success;
10594 }
10595 }
10596 return PyErr_SetFromWindowsErr(err);
10597 }
10598
10599success:
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010600 return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
10601}
Larry Hastings2f936352014-08-05 14:04:04 +100010602#endif /* MS_WINDOWS */
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010603
10604
Fred Drakec9680921999-12-13 16:37:25 +000010605/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
10606 * It maps strings representing configuration variable names to
10607 * integer values, allowing those functions to be called with the
Thomas Wouters7e474022000-07-16 12:04:32 +000010608 * magic names instead of polluting the module's namespace with tons of
Fred Drake12c6e2d1999-12-14 21:25:03 +000010609 * rarely-used constants. There are three separate tables that use
10610 * these definitions.
Fred Drakebec628d1999-12-15 18:31:10 +000010611 *
10612 * This code is always included, even if none of the interfaces that
10613 * need it are included. The #if hackery needed to avoid it would be
10614 * sufficiently pervasive that it's not worth the loss of readability.
Fred Drakec9680921999-12-13 16:37:25 +000010615 */
10616struct constdef {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020010617 const char *name;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010618 int value;
Fred Drakec9680921999-12-13 16:37:25 +000010619};
10620
Fred Drake12c6e2d1999-12-14 21:25:03 +000010621static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010622conv_confname(PyObject *arg, int *valuep, struct constdef *table,
Guido van Rossum7d5baac2007-08-27 23:24:46 +000010623 size_t tablesize)
Fred Drake12c6e2d1999-12-14 21:25:03 +000010624{
Christian Heimes217cfd12007-12-02 14:31:20 +000010625 if (PyLong_Check(arg)) {
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010626 int value = _PyLong_AsInt(arg);
10627 if (value == -1 && PyErr_Occurred())
10628 return 0;
10629 *valuep = value;
Stefan Krah0e803b32010-11-26 16:16:47 +000010630 return 1;
Fred Drake12c6e2d1999-12-14 21:25:03 +000010631 }
Guido van Rossumbce56a62007-05-10 18:04:33 +000010632 else {
Stefan Krah0e803b32010-11-26 16:16:47 +000010633 /* look up the value in the table using a binary search */
10634 size_t lo = 0;
10635 size_t mid;
10636 size_t hi = tablesize;
10637 int cmp;
10638 const char *confname;
10639 if (!PyUnicode_Check(arg)) {
10640 PyErr_SetString(PyExc_TypeError,
10641 "configuration names must be strings or integers");
10642 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010643 }
Serhiy Storchaka06515832016-11-20 09:13:07 +020010644 confname = PyUnicode_AsUTF8(arg);
Stefan Krah0e803b32010-11-26 16:16:47 +000010645 if (confname == NULL)
10646 return 0;
10647 while (lo < hi) {
10648 mid = (lo + hi) / 2;
10649 cmp = strcmp(confname, table[mid].name);
10650 if (cmp < 0)
10651 hi = mid;
10652 else if (cmp > 0)
10653 lo = mid + 1;
10654 else {
10655 *valuep = table[mid].value;
10656 return 1;
10657 }
10658 }
10659 PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
10660 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010661 }
Fred Drake12c6e2d1999-12-14 21:25:03 +000010662}
10663
10664
10665#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
10666static struct constdef posix_constants_pathconf[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010667#ifdef _PC_ABI_AIO_XFER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010668 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000010669#endif
10670#ifdef _PC_ABI_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010671 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010672#endif
Fred Drakec9680921999-12-13 16:37:25 +000010673#ifdef _PC_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010674 {"PC_ASYNC_IO", _PC_ASYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010675#endif
10676#ifdef _PC_CHOWN_RESTRICTED
Victor Stinner8c62be82010-05-06 00:08:46 +000010677 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
Fred Drakec9680921999-12-13 16:37:25 +000010678#endif
10679#ifdef _PC_FILESIZEBITS
Victor Stinner8c62be82010-05-06 00:08:46 +000010680 {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
Fred Drakec9680921999-12-13 16:37:25 +000010681#endif
10682#ifdef _PC_LAST
Victor Stinner8c62be82010-05-06 00:08:46 +000010683 {"PC_LAST", _PC_LAST},
Fred Drakec9680921999-12-13 16:37:25 +000010684#endif
10685#ifdef _PC_LINK_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010686 {"PC_LINK_MAX", _PC_LINK_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010687#endif
10688#ifdef _PC_MAX_CANON
Victor Stinner8c62be82010-05-06 00:08:46 +000010689 {"PC_MAX_CANON", _PC_MAX_CANON},
Fred Drakec9680921999-12-13 16:37:25 +000010690#endif
10691#ifdef _PC_MAX_INPUT
Victor Stinner8c62be82010-05-06 00:08:46 +000010692 {"PC_MAX_INPUT", _PC_MAX_INPUT},
Fred Drakec9680921999-12-13 16:37:25 +000010693#endif
10694#ifdef _PC_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010695 {"PC_NAME_MAX", _PC_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010696#endif
10697#ifdef _PC_NO_TRUNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010698 {"PC_NO_TRUNC", _PC_NO_TRUNC},
Fred Drakec9680921999-12-13 16:37:25 +000010699#endif
10700#ifdef _PC_PATH_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010701 {"PC_PATH_MAX", _PC_PATH_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010702#endif
10703#ifdef _PC_PIPE_BUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010704 {"PC_PIPE_BUF", _PC_PIPE_BUF},
Fred Drakec9680921999-12-13 16:37:25 +000010705#endif
10706#ifdef _PC_PRIO_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010707 {"PC_PRIO_IO", _PC_PRIO_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010708#endif
10709#ifdef _PC_SOCK_MAXBUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010710 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
Fred Drakec9680921999-12-13 16:37:25 +000010711#endif
10712#ifdef _PC_SYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010713 {"PC_SYNC_IO", _PC_SYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010714#endif
10715#ifdef _PC_VDISABLE
Victor Stinner8c62be82010-05-06 00:08:46 +000010716 {"PC_VDISABLE", _PC_VDISABLE},
Fred Drakec9680921999-12-13 16:37:25 +000010717#endif
Jesus Cea7e9065c2010-10-25 13:02:04 +000010718#ifdef _PC_ACL_ENABLED
10719 {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
10720#endif
10721#ifdef _PC_MIN_HOLE_SIZE
10722 {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
10723#endif
10724#ifdef _PC_ALLOC_SIZE_MIN
10725 {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
10726#endif
10727#ifdef _PC_REC_INCR_XFER_SIZE
10728 {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
10729#endif
10730#ifdef _PC_REC_MAX_XFER_SIZE
10731 {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
10732#endif
10733#ifdef _PC_REC_MIN_XFER_SIZE
10734 {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
10735#endif
10736#ifdef _PC_REC_XFER_ALIGN
10737 {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
10738#endif
10739#ifdef _PC_SYMLINK_MAX
10740 {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
10741#endif
10742#ifdef _PC_XATTR_ENABLED
10743 {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
10744#endif
10745#ifdef _PC_XATTR_EXISTS
10746 {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
10747#endif
10748#ifdef _PC_TIMESTAMP_RESOLUTION
10749 {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
10750#endif
Fred Drakec9680921999-12-13 16:37:25 +000010751};
10752
Fred Drakec9680921999-12-13 16:37:25 +000010753static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010754conv_path_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010755{
10756 return conv_confname(arg, valuep, posix_constants_pathconf,
10757 sizeof(posix_constants_pathconf)
10758 / sizeof(struct constdef));
10759}
10760#endif
10761
Larry Hastings2f936352014-08-05 14:04:04 +100010762
Fred Drakec9680921999-12-13 16:37:25 +000010763#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010764/*[clinic input]
10765os.fpathconf -> long
10766
10767 fd: int
10768 name: path_confname
10769 /
10770
10771Return the configuration limit name for the file descriptor fd.
10772
10773If there is no limit, return -1.
10774[clinic start generated code]*/
10775
Larry Hastings2f936352014-08-05 14:04:04 +100010776static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010777os_fpathconf_impl(PyObject *module, int fd, int name)
10778/*[clinic end generated code: output=d5b7042425fc3e21 input=5942a024d3777810]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010779{
10780 long limit;
10781
10782 errno = 0;
10783 limit = fpathconf(fd, name);
10784 if (limit == -1 && errno != 0)
10785 posix_error();
10786
10787 return limit;
10788}
10789#endif /* HAVE_FPATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010790
10791
10792#ifdef HAVE_PATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010793/*[clinic input]
10794os.pathconf -> long
10795 path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
10796 name: path_confname
10797
10798Return the configuration limit name for the file or directory path.
10799
10800If there is no limit, return -1.
10801On some platforms, path may also be specified as an open file descriptor.
10802 If this functionality is unavailable, using it raises an exception.
10803[clinic start generated code]*/
10804
Larry Hastings2f936352014-08-05 14:04:04 +100010805static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010806os_pathconf_impl(PyObject *module, path_t *path, int name)
10807/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010808{
Victor Stinner8c62be82010-05-06 00:08:46 +000010809 long limit;
Fred Drakec9680921999-12-13 16:37:25 +000010810
Victor Stinner8c62be82010-05-06 00:08:46 +000010811 errno = 0;
Georg Brandl306336b2012-06-24 12:55:33 +020010812#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010813 if (path->fd != -1)
10814 limit = fpathconf(path->fd, name);
Georg Brandl306336b2012-06-24 12:55:33 +020010815 else
10816#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010817 limit = pathconf(path->narrow, name);
Victor Stinner8c62be82010-05-06 00:08:46 +000010818 if (limit == -1 && errno != 0) {
10819 if (errno == EINVAL)
Stefan Krah99439262010-11-26 12:58:05 +000010820 /* could be a path or name problem */
10821 posix_error();
Fred Drakec9680921999-12-13 16:37:25 +000010822 else
Larry Hastings2f936352014-08-05 14:04:04 +100010823 path_error(path);
Victor Stinner8c62be82010-05-06 00:08:46 +000010824 }
Larry Hastings2f936352014-08-05 14:04:04 +100010825
10826 return limit;
Fred Drakec9680921999-12-13 16:37:25 +000010827}
Larry Hastings2f936352014-08-05 14:04:04 +100010828#endif /* HAVE_PATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010829
10830#ifdef HAVE_CONFSTR
10831static struct constdef posix_constants_confstr[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010832#ifdef _CS_ARCHITECTURE
Victor Stinner8c62be82010-05-06 00:08:46 +000010833 {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
Fred Draked86ed291999-12-15 15:34:33 +000010834#endif
Mark Dickinson876d7c82010-04-16 12:47:52 +000010835#ifdef _CS_GNU_LIBC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010836 {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010837#endif
10838#ifdef _CS_GNU_LIBPTHREAD_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010839 {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010840#endif
Fred Draked86ed291999-12-15 15:34:33 +000010841#ifdef _CS_HOSTNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010842 {"CS_HOSTNAME", _CS_HOSTNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010843#endif
10844#ifdef _CS_HW_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010845 {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010846#endif
10847#ifdef _CS_HW_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010848 {"CS_HW_SERIAL", _CS_HW_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010849#endif
10850#ifdef _CS_INITTAB_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010851 {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010852#endif
Fred Drakec9680921999-12-13 16:37:25 +000010853#ifdef _CS_LFS64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010854 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010855#endif
10856#ifdef _CS_LFS64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010857 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010858#endif
10859#ifdef _CS_LFS64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010860 {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010861#endif
10862#ifdef _CS_LFS64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010863 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010864#endif
10865#ifdef _CS_LFS_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010866 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010867#endif
10868#ifdef _CS_LFS_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010869 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010870#endif
10871#ifdef _CS_LFS_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010872 {"CS_LFS_LIBS", _CS_LFS_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010873#endif
10874#ifdef _CS_LFS_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010875 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010876#endif
Fred Draked86ed291999-12-15 15:34:33 +000010877#ifdef _CS_MACHINE
Victor Stinner8c62be82010-05-06 00:08:46 +000010878 {"CS_MACHINE", _CS_MACHINE},
Fred Draked86ed291999-12-15 15:34:33 +000010879#endif
Fred Drakec9680921999-12-13 16:37:25 +000010880#ifdef _CS_PATH
Victor Stinner8c62be82010-05-06 00:08:46 +000010881 {"CS_PATH", _CS_PATH},
Fred Drakec9680921999-12-13 16:37:25 +000010882#endif
Fred Draked86ed291999-12-15 15:34:33 +000010883#ifdef _CS_RELEASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010884 {"CS_RELEASE", _CS_RELEASE},
Fred Draked86ed291999-12-15 15:34:33 +000010885#endif
10886#ifdef _CS_SRPC_DOMAIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010887 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
Fred Draked86ed291999-12-15 15:34:33 +000010888#endif
10889#ifdef _CS_SYSNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010890 {"CS_SYSNAME", _CS_SYSNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010891#endif
10892#ifdef _CS_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010893 {"CS_VERSION", _CS_VERSION},
Fred Draked86ed291999-12-15 15:34:33 +000010894#endif
Fred Drakec9680921999-12-13 16:37:25 +000010895#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010896 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010897#endif
10898#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010899 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010900#endif
10901#ifdef _CS_XBS5_ILP32_OFF32_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010902 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010903#endif
10904#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010905 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010906#endif
10907#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010908 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010909#endif
10910#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010911 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010912#endif
10913#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010914 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010915#endif
10916#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010917 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010918#endif
10919#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010920 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010921#endif
10922#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010923 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010924#endif
10925#ifdef _CS_XBS5_LP64_OFF64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010926 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010927#endif
10928#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010929 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010930#endif
10931#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010932 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010933#endif
10934#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010935 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010936#endif
10937#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010938 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010939#endif
10940#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010941 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010942#endif
Fred Draked86ed291999-12-15 15:34:33 +000010943#ifdef _MIPS_CS_AVAIL_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010944 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010945#endif
10946#ifdef _MIPS_CS_BASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010947 {"MIPS_CS_BASE", _MIPS_CS_BASE},
Fred Draked86ed291999-12-15 15:34:33 +000010948#endif
10949#ifdef _MIPS_CS_HOSTID
Victor Stinner8c62be82010-05-06 00:08:46 +000010950 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
Fred Draked86ed291999-12-15 15:34:33 +000010951#endif
10952#ifdef _MIPS_CS_HW_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010953 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010954#endif
10955#ifdef _MIPS_CS_NUM_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010956 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010957#endif
10958#ifdef _MIPS_CS_OSREL_MAJ
Victor Stinner8c62be82010-05-06 00:08:46 +000010959 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
Fred Draked86ed291999-12-15 15:34:33 +000010960#endif
10961#ifdef _MIPS_CS_OSREL_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010962 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
Fred Draked86ed291999-12-15 15:34:33 +000010963#endif
10964#ifdef _MIPS_CS_OSREL_PATCH
Victor Stinner8c62be82010-05-06 00:08:46 +000010965 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
Fred Draked86ed291999-12-15 15:34:33 +000010966#endif
10967#ifdef _MIPS_CS_OS_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010968 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010969#endif
10970#ifdef _MIPS_CS_OS_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010971 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010972#endif
10973#ifdef _MIPS_CS_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010974 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010975#endif
10976#ifdef _MIPS_CS_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010977 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010978#endif
10979#ifdef _MIPS_CS_VENDOR
Victor Stinner8c62be82010-05-06 00:08:46 +000010980 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
Fred Draked86ed291999-12-15 15:34:33 +000010981#endif
Fred Drakec9680921999-12-13 16:37:25 +000010982};
10983
10984static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010985conv_confstr_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010986{
10987 return conv_confname(arg, valuep, posix_constants_confstr,
10988 sizeof(posix_constants_confstr)
10989 / sizeof(struct constdef));
10990}
10991
Larry Hastings2f936352014-08-05 14:04:04 +100010992
10993/*[clinic input]
10994os.confstr
10995
10996 name: confstr_confname
10997 /
10998
10999Return a string-valued system configuration variable.
11000[clinic start generated code]*/
11001
Larry Hastings2f936352014-08-05 14:04:04 +100011002static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011003os_confstr_impl(PyObject *module, int name)
11004/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
Fred Drakec9680921999-12-13 16:37:25 +000011005{
11006 PyObject *result = NULL;
Victor Stinnercb043522010-09-10 23:49:04 +000011007 char buffer[255];
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011008 size_t len;
Fred Drakec9680921999-12-13 16:37:25 +000011009
Victor Stinnercb043522010-09-10 23:49:04 +000011010 errno = 0;
11011 len = confstr(name, buffer, sizeof(buffer));
11012 if (len == 0) {
11013 if (errno) {
11014 posix_error();
11015 return NULL;
Fred Drakec9680921999-12-13 16:37:25 +000011016 }
11017 else {
Victor Stinnercb043522010-09-10 23:49:04 +000011018 Py_RETURN_NONE;
Fred Drakec9680921999-12-13 16:37:25 +000011019 }
11020 }
Victor Stinnercb043522010-09-10 23:49:04 +000011021
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011022 if (len >= sizeof(buffer)) {
Victor Stinnercbc18f32014-12-05 22:51:51 +010011023 size_t len2;
Victor Stinnercb043522010-09-10 23:49:04 +000011024 char *buf = PyMem_Malloc(len);
11025 if (buf == NULL)
11026 return PyErr_NoMemory();
Victor Stinnercbc18f32014-12-05 22:51:51 +010011027 len2 = confstr(name, buf, len);
11028 assert(len == len2);
Christian Heimes8714cfd2015-04-21 10:57:41 +020011029 result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
Victor Stinnercb043522010-09-10 23:49:04 +000011030 PyMem_Free(buf);
11031 }
11032 else
11033 result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
Fred Drakec9680921999-12-13 16:37:25 +000011034 return result;
11035}
Larry Hastings2f936352014-08-05 14:04:04 +100011036#endif /* HAVE_CONFSTR */
Fred Drakec9680921999-12-13 16:37:25 +000011037
11038
11039#ifdef HAVE_SYSCONF
11040static struct constdef posix_constants_sysconf[] = {
11041#ifdef _SC_2_CHAR_TERM
Victor Stinner8c62be82010-05-06 00:08:46 +000011042 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
Fred Drakec9680921999-12-13 16:37:25 +000011043#endif
11044#ifdef _SC_2_C_BIND
Victor Stinner8c62be82010-05-06 00:08:46 +000011045 {"SC_2_C_BIND", _SC_2_C_BIND},
Fred Drakec9680921999-12-13 16:37:25 +000011046#endif
11047#ifdef _SC_2_C_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011048 {"SC_2_C_DEV", _SC_2_C_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011049#endif
11050#ifdef _SC_2_C_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011051 {"SC_2_C_VERSION", _SC_2_C_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011052#endif
11053#ifdef _SC_2_FORT_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011054 {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011055#endif
11056#ifdef _SC_2_FORT_RUN
Victor Stinner8c62be82010-05-06 00:08:46 +000011057 {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
Fred Drakec9680921999-12-13 16:37:25 +000011058#endif
11059#ifdef _SC_2_LOCALEDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000011060 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
Fred Drakec9680921999-12-13 16:37:25 +000011061#endif
11062#ifdef _SC_2_SW_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011063 {"SC_2_SW_DEV", _SC_2_SW_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011064#endif
11065#ifdef _SC_2_UPE
Victor Stinner8c62be82010-05-06 00:08:46 +000011066 {"SC_2_UPE", _SC_2_UPE},
Fred Drakec9680921999-12-13 16:37:25 +000011067#endif
11068#ifdef _SC_2_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011069 {"SC_2_VERSION", _SC_2_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011070#endif
Fred Draked86ed291999-12-15 15:34:33 +000011071#ifdef _SC_ABI_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011072 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
Fred Draked86ed291999-12-15 15:34:33 +000011073#endif
11074#ifdef _SC_ACL
Victor Stinner8c62be82010-05-06 00:08:46 +000011075 {"SC_ACL", _SC_ACL},
Fred Draked86ed291999-12-15 15:34:33 +000011076#endif
Fred Drakec9680921999-12-13 16:37:25 +000011077#ifdef _SC_AIO_LISTIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011078 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011079#endif
Fred Drakec9680921999-12-13 16:37:25 +000011080#ifdef _SC_AIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011081 {"SC_AIO_MAX", _SC_AIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011082#endif
11083#ifdef _SC_AIO_PRIO_DELTA_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011084 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011085#endif
11086#ifdef _SC_ARG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011087 {"SC_ARG_MAX", _SC_ARG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011088#endif
11089#ifdef _SC_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011090 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011091#endif
11092#ifdef _SC_ATEXIT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011093 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011094#endif
Fred Draked86ed291999-12-15 15:34:33 +000011095#ifdef _SC_AUDIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011096 {"SC_AUDIT", _SC_AUDIT},
Fred Draked86ed291999-12-15 15:34:33 +000011097#endif
Fred Drakec9680921999-12-13 16:37:25 +000011098#ifdef _SC_AVPHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011099 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011100#endif
11101#ifdef _SC_BC_BASE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011102 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011103#endif
11104#ifdef _SC_BC_DIM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011105 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011106#endif
11107#ifdef _SC_BC_SCALE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011108 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011109#endif
11110#ifdef _SC_BC_STRING_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011111 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011112#endif
Fred Draked86ed291999-12-15 15:34:33 +000011113#ifdef _SC_CAP
Victor Stinner8c62be82010-05-06 00:08:46 +000011114 {"SC_CAP", _SC_CAP},
Fred Draked86ed291999-12-15 15:34:33 +000011115#endif
Fred Drakec9680921999-12-13 16:37:25 +000011116#ifdef _SC_CHARCLASS_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011117 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011118#endif
11119#ifdef _SC_CHAR_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011120 {"SC_CHAR_BIT", _SC_CHAR_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011121#endif
11122#ifdef _SC_CHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011123 {"SC_CHAR_MAX", _SC_CHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011124#endif
11125#ifdef _SC_CHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011126 {"SC_CHAR_MIN", _SC_CHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011127#endif
11128#ifdef _SC_CHILD_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011129 {"SC_CHILD_MAX", _SC_CHILD_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011130#endif
11131#ifdef _SC_CLK_TCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011132 {"SC_CLK_TCK", _SC_CLK_TCK},
Fred Drakec9680921999-12-13 16:37:25 +000011133#endif
11134#ifdef _SC_COHER_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011135 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011136#endif
11137#ifdef _SC_COLL_WEIGHTS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011138 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011139#endif
11140#ifdef _SC_DCACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011141 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011142#endif
11143#ifdef _SC_DCACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011144 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011145#endif
11146#ifdef _SC_DCACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011147 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011148#endif
11149#ifdef _SC_DCACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011150 {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011151#endif
11152#ifdef _SC_DCACHE_TBLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011153 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011154#endif
11155#ifdef _SC_DELAYTIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011156 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011157#endif
11158#ifdef _SC_EQUIV_CLASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011159 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011160#endif
11161#ifdef _SC_EXPR_NEST_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011162 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011163#endif
11164#ifdef _SC_FSYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000011165 {"SC_FSYNC", _SC_FSYNC},
Fred Drakec9680921999-12-13 16:37:25 +000011166#endif
11167#ifdef _SC_GETGR_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011168 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011169#endif
11170#ifdef _SC_GETPW_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011171 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011172#endif
11173#ifdef _SC_ICACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011174 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011175#endif
11176#ifdef _SC_ICACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011177 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011178#endif
11179#ifdef _SC_ICACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011180 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011181#endif
11182#ifdef _SC_ICACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011183 {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011184#endif
Fred Draked86ed291999-12-15 15:34:33 +000011185#ifdef _SC_INF
Victor Stinner8c62be82010-05-06 00:08:46 +000011186 {"SC_INF", _SC_INF},
Fred Draked86ed291999-12-15 15:34:33 +000011187#endif
Fred Drakec9680921999-12-13 16:37:25 +000011188#ifdef _SC_INT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011189 {"SC_INT_MAX", _SC_INT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011190#endif
11191#ifdef _SC_INT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011192 {"SC_INT_MIN", _SC_INT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011193#endif
11194#ifdef _SC_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011195 {"SC_IOV_MAX", _SC_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011196#endif
Fred Draked86ed291999-12-15 15:34:33 +000011197#ifdef _SC_IP_SECOPTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011198 {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
Fred Draked86ed291999-12-15 15:34:33 +000011199#endif
Fred Drakec9680921999-12-13 16:37:25 +000011200#ifdef _SC_JOB_CONTROL
Victor Stinner8c62be82010-05-06 00:08:46 +000011201 {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
Fred Drakec9680921999-12-13 16:37:25 +000011202#endif
Fred Draked86ed291999-12-15 15:34:33 +000011203#ifdef _SC_KERN_POINTERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011204 {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
Fred Draked86ed291999-12-15 15:34:33 +000011205#endif
11206#ifdef _SC_KERN_SIM
Victor Stinner8c62be82010-05-06 00:08:46 +000011207 {"SC_KERN_SIM", _SC_KERN_SIM},
Fred Draked86ed291999-12-15 15:34:33 +000011208#endif
Fred Drakec9680921999-12-13 16:37:25 +000011209#ifdef _SC_LINE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011210 {"SC_LINE_MAX", _SC_LINE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011211#endif
11212#ifdef _SC_LOGIN_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011213 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011214#endif
11215#ifdef _SC_LOGNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011216 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011217#endif
11218#ifdef _SC_LONG_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011219 {"SC_LONG_BIT", _SC_LONG_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011220#endif
Fred Draked86ed291999-12-15 15:34:33 +000011221#ifdef _SC_MAC
Victor Stinner8c62be82010-05-06 00:08:46 +000011222 {"SC_MAC", _SC_MAC},
Fred Draked86ed291999-12-15 15:34:33 +000011223#endif
Fred Drakec9680921999-12-13 16:37:25 +000011224#ifdef _SC_MAPPED_FILES
Victor Stinner8c62be82010-05-06 00:08:46 +000011225 {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
Fred Drakec9680921999-12-13 16:37:25 +000011226#endif
11227#ifdef _SC_MAXPID
Victor Stinner8c62be82010-05-06 00:08:46 +000011228 {"SC_MAXPID", _SC_MAXPID},
Fred Drakec9680921999-12-13 16:37:25 +000011229#endif
11230#ifdef _SC_MB_LEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011231 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011232#endif
11233#ifdef _SC_MEMLOCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011234 {"SC_MEMLOCK", _SC_MEMLOCK},
Fred Drakec9680921999-12-13 16:37:25 +000011235#endif
11236#ifdef _SC_MEMLOCK_RANGE
Victor Stinner8c62be82010-05-06 00:08:46 +000011237 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
Fred Drakec9680921999-12-13 16:37:25 +000011238#endif
11239#ifdef _SC_MEMORY_PROTECTION
Victor Stinner8c62be82010-05-06 00:08:46 +000011240 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
Fred Drakec9680921999-12-13 16:37:25 +000011241#endif
11242#ifdef _SC_MESSAGE_PASSING
Victor Stinner8c62be82010-05-06 00:08:46 +000011243 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
Fred Drakec9680921999-12-13 16:37:25 +000011244#endif
Fred Draked86ed291999-12-15 15:34:33 +000011245#ifdef _SC_MMAP_FIXED_ALIGNMENT
Victor Stinner8c62be82010-05-06 00:08:46 +000011246 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
Fred Draked86ed291999-12-15 15:34:33 +000011247#endif
Fred Drakec9680921999-12-13 16:37:25 +000011248#ifdef _SC_MQ_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011249 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011250#endif
11251#ifdef _SC_MQ_PRIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011252 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011253#endif
Fred Draked86ed291999-12-15 15:34:33 +000011254#ifdef _SC_NACLS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011255 {"SC_NACLS_MAX", _SC_NACLS_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000011256#endif
Fred Drakec9680921999-12-13 16:37:25 +000011257#ifdef _SC_NGROUPS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011258 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011259#endif
11260#ifdef _SC_NL_ARGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011261 {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011262#endif
11263#ifdef _SC_NL_LANGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011264 {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011265#endif
11266#ifdef _SC_NL_MSGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011267 {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011268#endif
11269#ifdef _SC_NL_NMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011270 {"SC_NL_NMAX", _SC_NL_NMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011271#endif
11272#ifdef _SC_NL_SETMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011273 {"SC_NL_SETMAX", _SC_NL_SETMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011274#endif
11275#ifdef _SC_NL_TEXTMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011276 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011277#endif
11278#ifdef _SC_NPROCESSORS_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011279 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
Fred Drakec9680921999-12-13 16:37:25 +000011280#endif
11281#ifdef _SC_NPROCESSORS_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011282 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
Fred Drakec9680921999-12-13 16:37:25 +000011283#endif
Fred Draked86ed291999-12-15 15:34:33 +000011284#ifdef _SC_NPROC_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011285 {"SC_NPROC_CONF", _SC_NPROC_CONF},
Fred Draked86ed291999-12-15 15:34:33 +000011286#endif
11287#ifdef _SC_NPROC_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011288 {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
Fred Draked86ed291999-12-15 15:34:33 +000011289#endif
Fred Drakec9680921999-12-13 16:37:25 +000011290#ifdef _SC_NZERO
Victor Stinner8c62be82010-05-06 00:08:46 +000011291 {"SC_NZERO", _SC_NZERO},
Fred Drakec9680921999-12-13 16:37:25 +000011292#endif
11293#ifdef _SC_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011294 {"SC_OPEN_MAX", _SC_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011295#endif
11296#ifdef _SC_PAGESIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011297 {"SC_PAGESIZE", _SC_PAGESIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011298#endif
11299#ifdef _SC_PAGE_SIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011300 {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011301#endif
11302#ifdef _SC_PASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011303 {"SC_PASS_MAX", _SC_PASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011304#endif
11305#ifdef _SC_PHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011306 {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011307#endif
11308#ifdef _SC_PII
Victor Stinner8c62be82010-05-06 00:08:46 +000011309 {"SC_PII", _SC_PII},
Fred Drakec9680921999-12-13 16:37:25 +000011310#endif
11311#ifdef _SC_PII_INTERNET
Victor Stinner8c62be82010-05-06 00:08:46 +000011312 {"SC_PII_INTERNET", _SC_PII_INTERNET},
Fred Drakec9680921999-12-13 16:37:25 +000011313#endif
11314#ifdef _SC_PII_INTERNET_DGRAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011315 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
Fred Drakec9680921999-12-13 16:37:25 +000011316#endif
11317#ifdef _SC_PII_INTERNET_STREAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011318 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
Fred Drakec9680921999-12-13 16:37:25 +000011319#endif
11320#ifdef _SC_PII_OSI
Victor Stinner8c62be82010-05-06 00:08:46 +000011321 {"SC_PII_OSI", _SC_PII_OSI},
Fred Drakec9680921999-12-13 16:37:25 +000011322#endif
11323#ifdef _SC_PII_OSI_CLTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011324 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
Fred Drakec9680921999-12-13 16:37:25 +000011325#endif
11326#ifdef _SC_PII_OSI_COTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011327 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
Fred Drakec9680921999-12-13 16:37:25 +000011328#endif
11329#ifdef _SC_PII_OSI_M
Victor Stinner8c62be82010-05-06 00:08:46 +000011330 {"SC_PII_OSI_M", _SC_PII_OSI_M},
Fred Drakec9680921999-12-13 16:37:25 +000011331#endif
11332#ifdef _SC_PII_SOCKET
Victor Stinner8c62be82010-05-06 00:08:46 +000011333 {"SC_PII_SOCKET", _SC_PII_SOCKET},
Fred Drakec9680921999-12-13 16:37:25 +000011334#endif
11335#ifdef _SC_PII_XTI
Victor Stinner8c62be82010-05-06 00:08:46 +000011336 {"SC_PII_XTI", _SC_PII_XTI},
Fred Drakec9680921999-12-13 16:37:25 +000011337#endif
11338#ifdef _SC_POLL
Victor Stinner8c62be82010-05-06 00:08:46 +000011339 {"SC_POLL", _SC_POLL},
Fred Drakec9680921999-12-13 16:37:25 +000011340#endif
11341#ifdef _SC_PRIORITIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011342 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011343#endif
11344#ifdef _SC_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011345 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011346#endif
11347#ifdef _SC_REALTIME_SIGNALS
Victor Stinner8c62be82010-05-06 00:08:46 +000011348 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
Fred Drakec9680921999-12-13 16:37:25 +000011349#endif
11350#ifdef _SC_RE_DUP_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011351 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011352#endif
11353#ifdef _SC_RTSIG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011354 {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011355#endif
11356#ifdef _SC_SAVED_IDS
Victor Stinner8c62be82010-05-06 00:08:46 +000011357 {"SC_SAVED_IDS", _SC_SAVED_IDS},
Fred Drakec9680921999-12-13 16:37:25 +000011358#endif
11359#ifdef _SC_SCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011360 {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011361#endif
11362#ifdef _SC_SCHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011363 {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011364#endif
11365#ifdef _SC_SELECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011366 {"SC_SELECT", _SC_SELECT},
Fred Drakec9680921999-12-13 16:37:25 +000011367#endif
11368#ifdef _SC_SEMAPHORES
Victor Stinner8c62be82010-05-06 00:08:46 +000011369 {"SC_SEMAPHORES", _SC_SEMAPHORES},
Fred Drakec9680921999-12-13 16:37:25 +000011370#endif
11371#ifdef _SC_SEM_NSEMS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011372 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011373#endif
11374#ifdef _SC_SEM_VALUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011375 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011376#endif
11377#ifdef _SC_SHARED_MEMORY_OBJECTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011378 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
Fred Drakec9680921999-12-13 16:37:25 +000011379#endif
11380#ifdef _SC_SHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011381 {"SC_SHRT_MAX", _SC_SHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011382#endif
11383#ifdef _SC_SHRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011384 {"SC_SHRT_MIN", _SC_SHRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011385#endif
11386#ifdef _SC_SIGQUEUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011387 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011388#endif
11389#ifdef _SC_SIGRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011390 {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011391#endif
11392#ifdef _SC_SIGRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011393 {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011394#endif
Fred Draked86ed291999-12-15 15:34:33 +000011395#ifdef _SC_SOFTPOWER
Victor Stinner8c62be82010-05-06 00:08:46 +000011396 {"SC_SOFTPOWER", _SC_SOFTPOWER},
Fred Draked86ed291999-12-15 15:34:33 +000011397#endif
Fred Drakec9680921999-12-13 16:37:25 +000011398#ifdef _SC_SPLIT_CACHE
Victor Stinner8c62be82010-05-06 00:08:46 +000011399 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
Fred Drakec9680921999-12-13 16:37:25 +000011400#endif
11401#ifdef _SC_SSIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011402 {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011403#endif
11404#ifdef _SC_STACK_PROT
Victor Stinner8c62be82010-05-06 00:08:46 +000011405 {"SC_STACK_PROT", _SC_STACK_PROT},
Fred Drakec9680921999-12-13 16:37:25 +000011406#endif
11407#ifdef _SC_STREAM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011408 {"SC_STREAM_MAX", _SC_STREAM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011409#endif
11410#ifdef _SC_SYNCHRONIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011411 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011412#endif
11413#ifdef _SC_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011414 {"SC_THREADS", _SC_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011415#endif
11416#ifdef _SC_THREAD_ATTR_STACKADDR
Victor Stinner8c62be82010-05-06 00:08:46 +000011417 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
Fred Drakec9680921999-12-13 16:37:25 +000011418#endif
11419#ifdef _SC_THREAD_ATTR_STACKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011420 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011421#endif
11422#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011423 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011424#endif
11425#ifdef _SC_THREAD_KEYS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011426 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011427#endif
11428#ifdef _SC_THREAD_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011429 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011430#endif
11431#ifdef _SC_THREAD_PRIO_INHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011432 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
Fred Drakec9680921999-12-13 16:37:25 +000011433#endif
11434#ifdef _SC_THREAD_PRIO_PROTECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011435 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
Fred Drakec9680921999-12-13 16:37:25 +000011436#endif
11437#ifdef _SC_THREAD_PROCESS_SHARED
Victor Stinner8c62be82010-05-06 00:08:46 +000011438 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
Fred Drakec9680921999-12-13 16:37:25 +000011439#endif
11440#ifdef _SC_THREAD_SAFE_FUNCTIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011441 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011442#endif
11443#ifdef _SC_THREAD_STACK_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011444 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011445#endif
11446#ifdef _SC_THREAD_THREADS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011447 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011448#endif
11449#ifdef _SC_TIMERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011450 {"SC_TIMERS", _SC_TIMERS},
Fred Drakec9680921999-12-13 16:37:25 +000011451#endif
11452#ifdef _SC_TIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011453 {"SC_TIMER_MAX", _SC_TIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011454#endif
11455#ifdef _SC_TTY_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011456 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011457#endif
11458#ifdef _SC_TZNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011459 {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011460#endif
11461#ifdef _SC_T_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011462 {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011463#endif
11464#ifdef _SC_UCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011465 {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011466#endif
11467#ifdef _SC_UINT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011468 {"SC_UINT_MAX", _SC_UINT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011469#endif
11470#ifdef _SC_UIO_MAXIOV
Victor Stinner8c62be82010-05-06 00:08:46 +000011471 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
Fred Drakec9680921999-12-13 16:37:25 +000011472#endif
11473#ifdef _SC_ULONG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011474 {"SC_ULONG_MAX", _SC_ULONG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011475#endif
11476#ifdef _SC_USHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011477 {"SC_USHRT_MAX", _SC_USHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011478#endif
11479#ifdef _SC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011480 {"SC_VERSION", _SC_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011481#endif
11482#ifdef _SC_WORD_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011483 {"SC_WORD_BIT", _SC_WORD_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011484#endif
11485#ifdef _SC_XBS5_ILP32_OFF32
Victor Stinner8c62be82010-05-06 00:08:46 +000011486 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
Fred Drakec9680921999-12-13 16:37:25 +000011487#endif
11488#ifdef _SC_XBS5_ILP32_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011489 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011490#endif
11491#ifdef _SC_XBS5_LP64_OFF64
Victor Stinner8c62be82010-05-06 00:08:46 +000011492 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
Fred Drakec9680921999-12-13 16:37:25 +000011493#endif
11494#ifdef _SC_XBS5_LPBIG_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011495 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011496#endif
11497#ifdef _SC_XOPEN_CRYPT
Victor Stinner8c62be82010-05-06 00:08:46 +000011498 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
Fred Drakec9680921999-12-13 16:37:25 +000011499#endif
11500#ifdef _SC_XOPEN_ENH_I18N
Victor Stinner8c62be82010-05-06 00:08:46 +000011501 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
Fred Drakec9680921999-12-13 16:37:25 +000011502#endif
11503#ifdef _SC_XOPEN_LEGACY
Victor Stinner8c62be82010-05-06 00:08:46 +000011504 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
Fred Drakec9680921999-12-13 16:37:25 +000011505#endif
11506#ifdef _SC_XOPEN_REALTIME
Victor Stinner8c62be82010-05-06 00:08:46 +000011507 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
Fred Drakec9680921999-12-13 16:37:25 +000011508#endif
11509#ifdef _SC_XOPEN_REALTIME_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011510 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011511#endif
11512#ifdef _SC_XOPEN_SHM
Victor Stinner8c62be82010-05-06 00:08:46 +000011513 {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
Fred Drakec9680921999-12-13 16:37:25 +000011514#endif
11515#ifdef _SC_XOPEN_UNIX
Victor Stinner8c62be82010-05-06 00:08:46 +000011516 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
Fred Drakec9680921999-12-13 16:37:25 +000011517#endif
11518#ifdef _SC_XOPEN_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011519 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011520#endif
11521#ifdef _SC_XOPEN_XCU_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011522 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011523#endif
11524#ifdef _SC_XOPEN_XPG2
Victor Stinner8c62be82010-05-06 00:08:46 +000011525 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
Fred Drakec9680921999-12-13 16:37:25 +000011526#endif
11527#ifdef _SC_XOPEN_XPG3
Victor Stinner8c62be82010-05-06 00:08:46 +000011528 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
Fred Drakec9680921999-12-13 16:37:25 +000011529#endif
11530#ifdef _SC_XOPEN_XPG4
Victor Stinner8c62be82010-05-06 00:08:46 +000011531 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
Fred Drakec9680921999-12-13 16:37:25 +000011532#endif
11533};
11534
11535static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011536conv_sysconf_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011537{
11538 return conv_confname(arg, valuep, posix_constants_sysconf,
11539 sizeof(posix_constants_sysconf)
11540 / sizeof(struct constdef));
11541}
11542
Larry Hastings2f936352014-08-05 14:04:04 +100011543
11544/*[clinic input]
11545os.sysconf -> long
11546 name: sysconf_confname
11547 /
11548
11549Return an integer-valued system configuration variable.
11550[clinic start generated code]*/
11551
Larry Hastings2f936352014-08-05 14:04:04 +100011552static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011553os_sysconf_impl(PyObject *module, int name)
11554/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011555{
11556 long value;
11557
11558 errno = 0;
11559 value = sysconf(name);
11560 if (value == -1 && errno != 0)
11561 posix_error();
11562 return value;
11563}
11564#endif /* HAVE_SYSCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011565
11566
Fred Drakebec628d1999-12-15 18:31:10 +000011567/* This code is used to ensure that the tables of configuration value names
Serhiy Storchaka56a6d852014-12-01 18:28:43 +020011568 * are in sorted order as required by conv_confname(), and also to build
Fred Drakebec628d1999-12-15 18:31:10 +000011569 * the exported dictionaries that are used to publish information about the
11570 * names available on the host platform.
11571 *
11572 * Sorting the table at runtime ensures that the table is properly ordered
11573 * when used, even for platforms we're not able to test on. It also makes
11574 * it easier to add additional entries to the tables.
Fred Draked86ed291999-12-15 15:34:33 +000011575 */
Fred Drakebec628d1999-12-15 18:31:10 +000011576
11577static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011578cmp_constdefs(const void *v1, const void *v2)
Fred Drakebec628d1999-12-15 18:31:10 +000011579{
11580 const struct constdef *c1 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011581 (const struct constdef *) v1;
Fred Drakebec628d1999-12-15 18:31:10 +000011582 const struct constdef *c2 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011583 (const struct constdef *) v2;
Fred Drakebec628d1999-12-15 18:31:10 +000011584
11585 return strcmp(c1->name, c2->name);
11586}
11587
11588static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011589setup_confname_table(struct constdef *table, size_t tablesize,
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011590 const char *tablename, PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011591{
Fred Drakebec628d1999-12-15 18:31:10 +000011592 PyObject *d = NULL;
Barry Warsaw3155db32000-04-13 15:20:40 +000011593 size_t i;
Fred Drakebec628d1999-12-15 18:31:10 +000011594
11595 qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
11596 d = PyDict_New();
Barry Warsaw3155db32000-04-13 15:20:40 +000011597 if (d == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +000011598 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011599
Barry Warsaw3155db32000-04-13 15:20:40 +000011600 for (i=0; i < tablesize; ++i) {
Victor Stinner8c62be82010-05-06 00:08:46 +000011601 PyObject *o = PyLong_FromLong(table[i].value);
11602 if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
11603 Py_XDECREF(o);
11604 Py_DECREF(d);
11605 return -1;
11606 }
11607 Py_DECREF(o);
Fred Draked86ed291999-12-15 15:34:33 +000011608 }
Fred Drake4d1e64b2002-04-15 19:40:07 +000011609 return PyModule_AddObject(module, tablename, d);
Fred Draked86ed291999-12-15 15:34:33 +000011610}
11611
Fred Drakebec628d1999-12-15 18:31:10 +000011612/* Return -1 on failure, 0 on success. */
11613static int
Fred Drake4d1e64b2002-04-15 19:40:07 +000011614setup_confname_tables(PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011615{
11616#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
Fred Drakebec628d1999-12-15 18:31:10 +000011617 if (setup_confname_table(posix_constants_pathconf,
Fred Draked86ed291999-12-15 15:34:33 +000011618 sizeof(posix_constants_pathconf)
11619 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011620 "pathconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011621 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011622#endif
11623#ifdef HAVE_CONFSTR
Fred Drakebec628d1999-12-15 18:31:10 +000011624 if (setup_confname_table(posix_constants_confstr,
Fred Draked86ed291999-12-15 15:34:33 +000011625 sizeof(posix_constants_confstr)
11626 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011627 "confstr_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011628 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011629#endif
11630#ifdef HAVE_SYSCONF
Fred Drakebec628d1999-12-15 18:31:10 +000011631 if (setup_confname_table(posix_constants_sysconf,
Fred Draked86ed291999-12-15 15:34:33 +000011632 sizeof(posix_constants_sysconf)
11633 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011634 "sysconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011635 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011636#endif
Fred Drakebec628d1999-12-15 18:31:10 +000011637 return 0;
Fred Draked86ed291999-12-15 15:34:33 +000011638}
Fred Draked86ed291999-12-15 15:34:33 +000011639
11640
Larry Hastings2f936352014-08-05 14:04:04 +100011641/*[clinic input]
11642os.abort
11643
11644Abort the interpreter immediately.
11645
11646This function 'dumps core' or otherwise fails in the hardest way possible
11647on the hosting operating system. This function never returns.
11648[clinic start generated code]*/
11649
Larry Hastings2f936352014-08-05 14:04:04 +100011650static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011651os_abort_impl(PyObject *module)
11652/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011653{
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011654 abort();
11655 /*NOTREACHED*/
Victor Stinner9a2329f2016-12-05 17:56:36 +010011656#ifndef __clang__
11657 /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
11658 GCC emits a warning without "return NULL;" (compiler bug?), but Clang
11659 is smarter and emits a warning on the return. */
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011660 Py_FatalError("abort() called from Python code didn't abort!");
11661 return NULL;
Victor Stinner9a2329f2016-12-05 17:56:36 +010011662#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011663}
Fred Drakebec628d1999-12-15 18:31:10 +000011664
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011665#ifdef MS_WINDOWS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011666/* Grab ShellExecute dynamically from shell32 */
11667static int has_ShellExecute = -1;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011668static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
11669 LPCWSTR, INT);
11670static int
11671check_ShellExecute()
11672{
11673 HINSTANCE hShell32;
11674
11675 /* only recheck */
11676 if (-1 == has_ShellExecute) {
11677 Py_BEGIN_ALLOW_THREADS
Victor Stinnera9912152017-10-13 13:46:57 -070011678 /* Security note: this call is not vulnerable to "DLL hijacking".
11679 SHELL32 is part of "KnownDLLs" and so Windows always load
11680 the system SHELL32.DLL, even if there is another SHELL32.DLL
11681 in the DLL search path. */
Steve Dower7d0e0c92015-01-24 08:18:24 -080011682 hShell32 = LoadLibraryW(L"SHELL32");
Steve Dower7d0e0c92015-01-24 08:18:24 -080011683 if (hShell32) {
Steve Dower7d0e0c92015-01-24 08:18:24 -080011684 *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
11685 "ShellExecuteW");
Steve Dowercc16be82016-09-08 10:35:16 -070011686 has_ShellExecute = Py_ShellExecuteW != NULL;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011687 } else {
11688 has_ShellExecute = 0;
11689 }
Tony Roberts4860f012019-02-02 18:16:42 +010011690 Py_END_ALLOW_THREADS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011691 }
11692 return has_ShellExecute;
11693}
11694
11695
Steve Dowercc16be82016-09-08 10:35:16 -070011696/*[clinic input]
11697os.startfile
11698 filepath: path_t
11699 operation: Py_UNICODE = NULL
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +000011700
Steve Dowercc16be82016-09-08 10:35:16 -070011701Start a file with its associated application.
11702
11703When "operation" is not specified or "open", this acts like
11704double-clicking the file in Explorer, or giving the file name as an
11705argument to the DOS "start" command: the file is opened with whatever
11706application (if any) its extension is associated.
11707When another "operation" is given, it specifies what should be done with
11708the file. A typical operation is "print".
11709
11710startfile returns as soon as the associated application is launched.
11711There is no option to wait for the application to close, and no way
11712to retrieve the application's exit status.
11713
11714The filepath is relative to the current directory. If you want to use
11715an absolute path, make sure the first character is not a slash ("/");
11716the underlying Win32 ShellExecute function doesn't work if it is.
11717[clinic start generated code]*/
11718
11719static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +020011720os_startfile_impl(PyObject *module, path_t *filepath,
11721 const Py_UNICODE *operation)
Serhiy Storchaka279f4462019-09-14 12:24:05 +030011722/*[clinic end generated code: output=66dc311c94d50797 input=c940888a5390f039]*/
Steve Dowercc16be82016-09-08 10:35:16 -070011723{
11724 HINSTANCE rc;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011725
11726 if(!check_ShellExecute()) {
11727 /* If the OS doesn't have ShellExecute, return a
11728 NotImplementedError. */
11729 return PyErr_Format(PyExc_NotImplementedError,
11730 "startfile not available on this platform");
11731 }
11732
Saiyang Gou95f60012020-02-04 16:15:00 -080011733 if (PySys_Audit("os.startfile", "Ou",
11734 filepath->object ? filepath->object : Py_None,
11735 operation) < 0) {
11736 return NULL;
11737 }
11738
Victor Stinner8c62be82010-05-06 00:08:46 +000011739 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -070011740 rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
Steve Dower7d0e0c92015-01-24 08:18:24 -080011741 NULL, NULL, SW_SHOWNORMAL);
Victor Stinner8c62be82010-05-06 00:08:46 +000011742 Py_END_ALLOW_THREADS
11743
Victor Stinner8c62be82010-05-06 00:08:46 +000011744 if (rc <= (HINSTANCE)32) {
Steve Dowercc16be82016-09-08 10:35:16 -070011745 win32_error_object("startfile", filepath->object);
Victor Stinnereb5657a2011-09-30 01:44:27 +020011746 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000011747 }
Steve Dowercc16be82016-09-08 10:35:16 -070011748 Py_RETURN_NONE;
Tim Petersf58a7aa2000-09-22 10:05:54 +000011749}
Larry Hastings2f936352014-08-05 14:04:04 +100011750#endif /* MS_WINDOWS */
11751
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011752
Martin v. Löwis438b5342002-12-27 10:16:42 +000011753#ifdef HAVE_GETLOADAVG
Larry Hastings2f936352014-08-05 14:04:04 +100011754/*[clinic input]
11755os.getloadavg
11756
11757Return average recent system load information.
11758
11759Return the number of processes in the system run queue averaged over
11760the last 1, 5, and 15 minutes as a tuple of three floats.
11761Raises OSError if the load average was unobtainable.
11762[clinic start generated code]*/
11763
Larry Hastings2f936352014-08-05 14:04:04 +100011764static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011765os_getloadavg_impl(PyObject *module)
11766/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
Martin v. Löwis438b5342002-12-27 10:16:42 +000011767{
11768 double loadavg[3];
Martin v. Löwis438b5342002-12-27 10:16:42 +000011769 if (getloadavg(loadavg, 3)!=3) {
Stefan Krah0e803b32010-11-26 16:16:47 +000011770 PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
11771 return NULL;
Martin v. Löwis438b5342002-12-27 10:16:42 +000011772 } else
Stefan Krah0e803b32010-11-26 16:16:47 +000011773 return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
Martin v. Löwis438b5342002-12-27 10:16:42 +000011774}
Larry Hastings2f936352014-08-05 14:04:04 +100011775#endif /* HAVE_GETLOADAVG */
Martin v. Löwis438b5342002-12-27 10:16:42 +000011776
Larry Hastings2f936352014-08-05 14:04:04 +100011777
11778/*[clinic input]
11779os.device_encoding
11780 fd: int
11781
11782Return a string describing the encoding of a terminal's file descriptor.
11783
11784The file descriptor must be attached to a terminal.
11785If the device is not a terminal, return None.
11786[clinic start generated code]*/
11787
Larry Hastings2f936352014-08-05 14:04:04 +100011788static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011789os_device_encoding_impl(PyObject *module, int fd)
11790/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011791{
Brett Cannonefb00c02012-02-29 18:31:31 -050011792 return _Py_device_encoding(fd);
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +000011793}
11794
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011795
Larry Hastings2f936352014-08-05 14:04:04 +100011796#ifdef HAVE_SETRESUID
11797/*[clinic input]
11798os.setresuid
11799
11800 ruid: uid_t
11801 euid: uid_t
11802 suid: uid_t
11803 /
11804
11805Set the current process's real, effective, and saved user ids.
11806[clinic start generated code]*/
11807
Larry Hastings2f936352014-08-05 14:04:04 +100011808static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011809os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
11810/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011811{
Victor Stinner8c62be82010-05-06 00:08:46 +000011812 if (setresuid(ruid, euid, suid) < 0)
11813 return posix_error();
11814 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011815}
Larry Hastings2f936352014-08-05 14:04:04 +100011816#endif /* HAVE_SETRESUID */
11817
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011818
11819#ifdef HAVE_SETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011820/*[clinic input]
11821os.setresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011822
Larry Hastings2f936352014-08-05 14:04:04 +100011823 rgid: gid_t
11824 egid: gid_t
11825 sgid: gid_t
11826 /
11827
11828Set the current process's real, effective, and saved group ids.
11829[clinic start generated code]*/
11830
Larry Hastings2f936352014-08-05 14:04:04 +100011831static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011832os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
11833/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011834{
Victor Stinner8c62be82010-05-06 00:08:46 +000011835 if (setresgid(rgid, egid, sgid) < 0)
11836 return posix_error();
11837 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011838}
Larry Hastings2f936352014-08-05 14:04:04 +100011839#endif /* HAVE_SETRESGID */
11840
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011841
11842#ifdef HAVE_GETRESUID
Larry Hastings2f936352014-08-05 14:04:04 +100011843/*[clinic input]
11844os.getresuid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011845
Larry Hastings2f936352014-08-05 14:04:04 +100011846Return a tuple of the current process's real, effective, and saved user ids.
11847[clinic start generated code]*/
11848
Larry Hastings2f936352014-08-05 14:04:04 +100011849static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011850os_getresuid_impl(PyObject *module)
11851/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011852{
Victor Stinner8c62be82010-05-06 00:08:46 +000011853 uid_t ruid, euid, suid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011854 if (getresuid(&ruid, &euid, &suid) < 0)
11855 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011856 return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
11857 _PyLong_FromUid(euid),
11858 _PyLong_FromUid(suid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011859}
Larry Hastings2f936352014-08-05 14:04:04 +100011860#endif /* HAVE_GETRESUID */
11861
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011862
11863#ifdef HAVE_GETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011864/*[clinic input]
11865os.getresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011866
Larry Hastings2f936352014-08-05 14:04:04 +100011867Return a tuple of the current process's real, effective, and saved group ids.
11868[clinic start generated code]*/
11869
Larry Hastings2f936352014-08-05 14:04:04 +100011870static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011871os_getresgid_impl(PyObject *module)
11872/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011873{
11874 gid_t rgid, egid, sgid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011875 if (getresgid(&rgid, &egid, &sgid) < 0)
11876 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011877 return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
11878 _PyLong_FromGid(egid),
11879 _PyLong_FromGid(sgid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011880}
Larry Hastings2f936352014-08-05 14:04:04 +100011881#endif /* HAVE_GETRESGID */
11882
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011883
Benjamin Peterson9428d532011-09-14 11:45:52 -040011884#ifdef USE_XATTRS
Larry Hastings2f936352014-08-05 14:04:04 +100011885/*[clinic input]
11886os.getxattr
Benjamin Peterson799bd802011-08-31 22:15:17 -040011887
Larry Hastings2f936352014-08-05 14:04:04 +100011888 path: path_t(allow_fd=True)
11889 attribute: path_t
11890 *
11891 follow_symlinks: bool = True
11892
11893Return the value of extended attribute attribute on path.
11894
BNMetricsb9427072018-11-02 15:20:19 +000011895path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011896If follow_symlinks is False, and the last element of the path is a symbolic
11897 link, getxattr will examine the symbolic link itself instead of the file
11898 the link points to.
11899
11900[clinic start generated code]*/
11901
Larry Hastings2f936352014-08-05 14:04:04 +100011902static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011903os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011904 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011905/*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011906{
11907 Py_ssize_t i;
11908 PyObject *buffer = NULL;
11909
11910 if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
11911 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011912
Larry Hastings9cf065c2012-06-22 16:30:09 -070011913 for (i = 0; ; i++) {
11914 void *ptr;
11915 ssize_t result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020011916 static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
Larry Hastings9cf065c2012-06-22 16:30:09 -070011917 Py_ssize_t buffer_size = buffer_sizes[i];
11918 if (!buffer_size) {
Larry Hastings2f936352014-08-05 14:04:04 +100011919 path_error(path);
11920 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011921 }
11922 buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
11923 if (!buffer)
Larry Hastings2f936352014-08-05 14:04:04 +100011924 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011925 ptr = PyBytes_AS_STRING(buffer);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011926
Larry Hastings9cf065c2012-06-22 16:30:09 -070011927 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011928 if (path->fd >= 0)
11929 result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011930 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011931 result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011932 else
Larry Hastings2f936352014-08-05 14:04:04 +100011933 result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011934 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011935
Larry Hastings9cf065c2012-06-22 16:30:09 -070011936 if (result < 0) {
11937 Py_DECREF(buffer);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011938 if (errno == ERANGE)
11939 continue;
Larry Hastings2f936352014-08-05 14:04:04 +100011940 path_error(path);
11941 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011942 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011943
Larry Hastings9cf065c2012-06-22 16:30:09 -070011944 if (result != buffer_size) {
11945 /* Can only shrink. */
11946 _PyBytes_Resize(&buffer, result);
11947 }
11948 break;
11949 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011950
Larry Hastings9cf065c2012-06-22 16:30:09 -070011951 return buffer;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011952}
11953
Larry Hastings2f936352014-08-05 14:04:04 +100011954
11955/*[clinic input]
11956os.setxattr
11957
11958 path: path_t(allow_fd=True)
11959 attribute: path_t
11960 value: Py_buffer
11961 flags: int = 0
11962 *
11963 follow_symlinks: bool = True
11964
11965Set extended attribute attribute on path to value.
11966
BNMetricsb9427072018-11-02 15:20:19 +000011967path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011968If follow_symlinks is False, and the last element of the path is a symbolic
11969 link, setxattr will modify the symbolic link itself instead of the file
11970 the link points to.
11971
11972[clinic start generated code]*/
11973
Benjamin Peterson799bd802011-08-31 22:15:17 -040011974static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011975os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011976 Py_buffer *value, int flags, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011977/*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
Benjamin Peterson799bd802011-08-31 22:15:17 -040011978{
Larry Hastings2f936352014-08-05 14:04:04 +100011979 ssize_t result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011980
Larry Hastings2f936352014-08-05 14:04:04 +100011981 if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
Benjamin Peterson799bd802011-08-31 22:15:17 -040011982 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011983
Benjamin Peterson799bd802011-08-31 22:15:17 -040011984 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011985 if (path->fd > -1)
11986 result = fsetxattr(path->fd, attribute->narrow,
11987 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011988 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011989 result = setxattr(path->narrow, attribute->narrow,
11990 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011991 else
Larry Hastings2f936352014-08-05 14:04:04 +100011992 result = lsetxattr(path->narrow, attribute->narrow,
11993 value->buf, value->len, flags);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011994 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011995
Larry Hastings9cf065c2012-06-22 16:30:09 -070011996 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100011997 path_error(path);
11998 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011999 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012000
Larry Hastings2f936352014-08-05 14:04:04 +100012001 Py_RETURN_NONE;
12002}
12003
12004
12005/*[clinic input]
12006os.removexattr
12007
12008 path: path_t(allow_fd=True)
12009 attribute: path_t
12010 *
12011 follow_symlinks: bool = True
12012
12013Remove 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, removexattr will modify 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_removexattr_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=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012026{
12027 ssize_t result;
12028
12029 if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
12030 return NULL;
12031
12032 Py_BEGIN_ALLOW_THREADS;
12033 if (path->fd > -1)
12034 result = fremovexattr(path->fd, attribute->narrow);
12035 else if (follow_symlinks)
12036 result = removexattr(path->narrow, attribute->narrow);
12037 else
12038 result = lremovexattr(path->narrow, attribute->narrow);
12039 Py_END_ALLOW_THREADS;
12040
12041 if (result) {
12042 return path_error(path);
12043 }
12044
12045 Py_RETURN_NONE;
12046}
12047
12048
12049/*[clinic input]
12050os.listxattr
12051
12052 path: path_t(allow_fd=True, nullable=True) = None
12053 *
12054 follow_symlinks: bool = True
12055
12056Return a list of extended attributes on path.
12057
BNMetricsb9427072018-11-02 15:20:19 +000012058path may be either None, a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012059if path is None, listxattr will examine the current directory.
12060If follow_symlinks is False, and the last element of the path is a symbolic
12061 link, listxattr will examine the symbolic link itself instead of the file
12062 the link points to.
12063[clinic start generated code]*/
12064
Larry Hastings2f936352014-08-05 14:04:04 +100012065static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012066os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012067/*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012068{
Larry Hastings9cf065c2012-06-22 16:30:09 -070012069 Py_ssize_t i;
12070 PyObject *result = NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100012071 const char *name;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012072 char *buffer = NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012073
Larry Hastings2f936352014-08-05 14:04:04 +100012074 if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
Larry Hastings9cf065c2012-06-22 16:30:09 -070012075 goto exit;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012076
Larry Hastings2f936352014-08-05 14:04:04 +100012077 name = path->narrow ? path->narrow : ".";
12078
Larry Hastings9cf065c2012-06-22 16:30:09 -070012079 for (i = 0; ; i++) {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012080 const char *start, *trace, *end;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012081 ssize_t length;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012082 static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
Larry Hastings9cf065c2012-06-22 16:30:09 -070012083 Py_ssize_t buffer_size = buffer_sizes[i];
12084 if (!buffer_size) {
Christian Heimes3b9493b2012-09-23 16:11:15 +020012085 /* ERANGE */
Larry Hastings2f936352014-08-05 14:04:04 +100012086 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012087 break;
12088 }
12089 buffer = PyMem_MALLOC(buffer_size);
12090 if (!buffer) {
12091 PyErr_NoMemory();
12092 break;
12093 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012094
Larry Hastings9cf065c2012-06-22 16:30:09 -070012095 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012096 if (path->fd > -1)
12097 length = flistxattr(path->fd, buffer, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012098 else if (follow_symlinks)
12099 length = listxattr(name, buffer, buffer_size);
12100 else
12101 length = llistxattr(name, buffer, buffer_size);
12102 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012103
Larry Hastings9cf065c2012-06-22 16:30:09 -070012104 if (length < 0) {
Antoine Pitrou7f987392013-05-13 19:46:29 +020012105 if (errno == ERANGE) {
12106 PyMem_FREE(buffer);
Benjamin Petersondedac522013-05-13 19:55:40 -050012107 buffer = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012108 continue;
Antoine Pitrou7f987392013-05-13 19:46:29 +020012109 }
Larry Hastings2f936352014-08-05 14:04:04 +100012110 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012111 break;
12112 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012113
Larry Hastings9cf065c2012-06-22 16:30:09 -070012114 result = PyList_New(0);
12115 if (!result) {
12116 goto exit;
12117 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012118
Larry Hastings9cf065c2012-06-22 16:30:09 -070012119 end = buffer + length;
12120 for (trace = start = buffer; trace != end; trace++) {
12121 if (!*trace) {
12122 int error;
12123 PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
12124 trace - start);
12125 if (!attribute) {
12126 Py_DECREF(result);
12127 result = NULL;
12128 goto exit;
12129 }
12130 error = PyList_Append(result, attribute);
12131 Py_DECREF(attribute);
12132 if (error) {
12133 Py_DECREF(result);
12134 result = NULL;
12135 goto exit;
12136 }
12137 start = trace + 1;
12138 }
12139 }
12140 break;
12141 }
12142exit:
Larry Hastings9cf065c2012-06-22 16:30:09 -070012143 if (buffer)
12144 PyMem_FREE(buffer);
12145 return result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012146}
Benjamin Peterson9428d532011-09-14 11:45:52 -040012147#endif /* USE_XATTRS */
Benjamin Peterson799bd802011-08-31 22:15:17 -040012148
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012149
Larry Hastings2f936352014-08-05 14:04:04 +100012150/*[clinic input]
12151os.urandom
12152
12153 size: Py_ssize_t
12154 /
12155
12156Return a bytes object containing random bytes suitable for cryptographic use.
12157[clinic start generated code]*/
12158
Larry Hastings2f936352014-08-05 14:04:04 +100012159static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012160os_urandom_impl(PyObject *module, Py_ssize_t size)
12161/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012162{
12163 PyObject *bytes;
12164 int result;
12165
Georg Brandl2fb477c2012-02-21 00:33:36 +010012166 if (size < 0)
12167 return PyErr_Format(PyExc_ValueError,
12168 "negative argument not allowed");
Larry Hastings2f936352014-08-05 14:04:04 +100012169 bytes = PyBytes_FromStringAndSize(NULL, size);
12170 if (bytes == NULL)
Georg Brandl2fb477c2012-02-21 00:33:36 +010012171 return NULL;
12172
Victor Stinnere66987e2016-09-06 16:33:52 -070012173 result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
Larry Hastings2f936352014-08-05 14:04:04 +100012174 if (result == -1) {
12175 Py_DECREF(bytes);
Georg Brandl2fb477c2012-02-21 00:33:36 +010012176 return NULL;
12177 }
Larry Hastings2f936352014-08-05 14:04:04 +100012178 return bytes;
Georg Brandl2fb477c2012-02-21 00:33:36 +010012179}
12180
Zackery Spytz43fdbd22019-05-29 13:57:07 -060012181#ifdef HAVE_MEMFD_CREATE
12182/*[clinic input]
12183os.memfd_create
12184
12185 name: FSConverter
12186 flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
12187
12188[clinic start generated code]*/
12189
12190static PyObject *
12191os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
12192/*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
12193{
12194 int fd;
12195 const char *bytes = PyBytes_AS_STRING(name);
12196 Py_BEGIN_ALLOW_THREADS
12197 fd = memfd_create(bytes, flags);
12198 Py_END_ALLOW_THREADS
12199 if (fd == -1) {
12200 return PyErr_SetFromErrno(PyExc_OSError);
12201 }
12202 return PyLong_FromLong(fd);
12203}
12204#endif
12205
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012206/* Terminal size querying */
12207
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012208PyDoc_STRVAR(TerminalSize_docstring,
12209 "A tuple of (columns, lines) for holding terminal window size");
12210
12211static PyStructSequence_Field TerminalSize_fields[] = {
12212 {"columns", "width of the terminal window in characters"},
12213 {"lines", "height of the terminal window in characters"},
12214 {NULL, NULL}
12215};
12216
12217static PyStructSequence_Desc TerminalSize_desc = {
12218 "os.terminal_size",
12219 TerminalSize_docstring,
12220 TerminalSize_fields,
12221 2,
12222};
12223
12224#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
Larry Hastings2f936352014-08-05 14:04:04 +100012225/* AC 3.5: fd should accept None */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012226PyDoc_STRVAR(termsize__doc__,
12227 "Return the size of the terminal window as (columns, lines).\n" \
12228 "\n" \
12229 "The optional argument fd (default standard output) specifies\n" \
12230 "which file descriptor should be queried.\n" \
12231 "\n" \
12232 "If the file descriptor is not connected to a terminal, an OSError\n" \
12233 "is thrown.\n" \
12234 "\n" \
12235 "This function will only be defined if an implementation is\n" \
12236 "available for this system.\n" \
12237 "\n" \
oldkaa0735f2018-02-02 16:52:55 +080012238 "shutil.get_terminal_size is the high-level function which should\n" \
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012239 "normally be used, os.get_terminal_size is the low-level implementation.");
12240
12241static PyObject*
12242get_terminal_size(PyObject *self, PyObject *args)
12243{
12244 int columns, lines;
12245 PyObject *termsize;
12246
12247 int fd = fileno(stdout);
12248 /* Under some conditions stdout may not be connected and
12249 * fileno(stdout) may point to an invalid file descriptor. For example
12250 * GUI apps don't have valid standard streams by default.
12251 *
12252 * If this happens, and the optional fd argument is not present,
12253 * the ioctl below will fail returning EBADF. This is what we want.
12254 */
12255
12256 if (!PyArg_ParseTuple(args, "|i", &fd))
12257 return NULL;
12258
12259#ifdef TERMSIZE_USE_IOCTL
12260 {
12261 struct winsize w;
12262 if (ioctl(fd, TIOCGWINSZ, &w))
12263 return PyErr_SetFromErrno(PyExc_OSError);
12264 columns = w.ws_col;
12265 lines = w.ws_row;
12266 }
12267#endif /* TERMSIZE_USE_IOCTL */
12268
12269#ifdef TERMSIZE_USE_CONIO
12270 {
12271 DWORD nhandle;
12272 HANDLE handle;
12273 CONSOLE_SCREEN_BUFFER_INFO csbi;
12274 switch (fd) {
12275 case 0: nhandle = STD_INPUT_HANDLE;
12276 break;
12277 case 1: nhandle = STD_OUTPUT_HANDLE;
12278 break;
12279 case 2: nhandle = STD_ERROR_HANDLE;
12280 break;
12281 default:
12282 return PyErr_Format(PyExc_ValueError, "bad file descriptor");
12283 }
12284 handle = GetStdHandle(nhandle);
12285 if (handle == NULL)
12286 return PyErr_Format(PyExc_OSError, "handle cannot be retrieved");
12287 if (handle == INVALID_HANDLE_VALUE)
12288 return PyErr_SetFromWindowsErr(0);
12289
12290 if (!GetConsoleScreenBufferInfo(handle, &csbi))
12291 return PyErr_SetFromWindowsErr(0);
12292
12293 columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
12294 lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
12295 }
12296#endif /* TERMSIZE_USE_CONIO */
12297
Eddie Elizondob3966632019-11-05 07:16:14 -080012298 PyObject *TerminalSizeType = _posixstate(self)->TerminalSizeType;
12299 termsize = PyStructSequence_New((PyTypeObject *)TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012300 if (termsize == NULL)
12301 return NULL;
12302 PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
12303 PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
12304 if (PyErr_Occurred()) {
12305 Py_DECREF(termsize);
12306 return NULL;
12307 }
12308 return termsize;
12309}
12310#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
12311
Larry Hastings2f936352014-08-05 14:04:04 +100012312
12313/*[clinic input]
12314os.cpu_count
12315
Charles-François Natali80d62e62015-08-13 20:37:08 +010012316Return the number of CPUs in the system; return None if indeterminable.
12317
12318This number is not equivalent to the number of CPUs the current process can
12319use. The number of usable CPUs can be obtained with
12320``len(os.sched_getaffinity(0))``
Larry Hastings2f936352014-08-05 14:04:04 +100012321[clinic start generated code]*/
12322
Larry Hastings2f936352014-08-05 14:04:04 +100012323static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012324os_cpu_count_impl(PyObject *module)
Serhiy Storchaka2954f832016-07-07 18:20:03 +030012325/*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012326{
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012327 int ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012328#ifdef MS_WINDOWS
Steve Doweraa929272019-09-11 16:15:39 +010012329 ncpu = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012330#elif defined(__hpux)
12331 ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
12332#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
12333 ncpu = sysconf(_SC_NPROCESSORS_ONLN);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012334#elif defined(__DragonFly__) || \
12335 defined(__OpenBSD__) || \
12336 defined(__FreeBSD__) || \
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012337 defined(__NetBSD__) || \
12338 defined(__APPLE__)
Charles-Francois Natali7c4f8da2013-05-20 17:40:32 +020012339 int mib[2];
12340 size_t len = sizeof(ncpu);
12341 mib[0] = CTL_HW;
12342 mib[1] = HW_NCPU;
12343 if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
12344 ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012345#endif
12346 if (ncpu >= 1)
12347 return PyLong_FromLong(ncpu);
12348 else
12349 Py_RETURN_NONE;
12350}
12351
Victor Stinnerdaf45552013-08-28 00:53:59 +020012352
Larry Hastings2f936352014-08-05 14:04:04 +100012353/*[clinic input]
12354os.get_inheritable -> bool
12355
12356 fd: int
12357 /
12358
12359Get the close-on-exe flag of the specified file descriptor.
12360[clinic start generated code]*/
12361
Larry Hastings2f936352014-08-05 14:04:04 +100012362static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012363os_get_inheritable_impl(PyObject *module, int fd)
12364/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012365{
Steve Dower8fc89802015-04-12 00:26:27 -040012366 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -040012367 _Py_BEGIN_SUPPRESS_IPH
12368 return_value = _Py_get_inheritable(fd);
12369 _Py_END_SUPPRESS_IPH
12370 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +100012371}
12372
12373
12374/*[clinic input]
12375os.set_inheritable
12376 fd: int
12377 inheritable: int
12378 /
12379
12380Set the inheritable flag of the specified file descriptor.
12381[clinic start generated code]*/
12382
Larry Hastings2f936352014-08-05 14:04:04 +100012383static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012384os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
12385/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
Victor Stinnerdaf45552013-08-28 00:53:59 +020012386{
Steve Dower8fc89802015-04-12 00:26:27 -040012387 int result;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012388
Steve Dower8fc89802015-04-12 00:26:27 -040012389 _Py_BEGIN_SUPPRESS_IPH
12390 result = _Py_set_inheritable(fd, inheritable, NULL);
12391 _Py_END_SUPPRESS_IPH
12392 if (result < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +020012393 return NULL;
12394 Py_RETURN_NONE;
12395}
12396
12397
12398#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100012399/*[clinic input]
12400os.get_handle_inheritable -> bool
Benjamin Petersonca470632016-09-06 13:47:26 -070012401 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012402 /
Victor Stinnerdaf45552013-08-28 00:53:59 +020012403
Larry Hastings2f936352014-08-05 14:04:04 +100012404Get the close-on-exe flag of the specified file descriptor.
12405[clinic start generated code]*/
12406
Larry Hastings2f936352014-08-05 14:04:04 +100012407static int
Benjamin Petersonca470632016-09-06 13:47:26 -070012408os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
Victor Stinner581139c2016-09-06 15:54:20 -070012409/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012410{
12411 DWORD flags;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012412
12413 if (!GetHandleInformation((HANDLE)handle, &flags)) {
12414 PyErr_SetFromWindowsErr(0);
Larry Hastings2f936352014-08-05 14:04:04 +100012415 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012416 }
12417
Larry Hastings2f936352014-08-05 14:04:04 +100012418 return flags & HANDLE_FLAG_INHERIT;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012419}
12420
Victor Stinnerdaf45552013-08-28 00:53:59 +020012421
Larry Hastings2f936352014-08-05 14:04:04 +100012422/*[clinic input]
12423os.set_handle_inheritable
Benjamin Petersonca470632016-09-06 13:47:26 -070012424 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012425 inheritable: bool
12426 /
12427
12428Set the inheritable flag of the specified handle.
12429[clinic start generated code]*/
12430
Larry Hastings2f936352014-08-05 14:04:04 +100012431static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -070012432os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
Larry Hastings89964c42015-04-14 18:07:59 -040012433 int inheritable)
Victor Stinner581139c2016-09-06 15:54:20 -070012434/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012435{
12436 DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012437 if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
12438 PyErr_SetFromWindowsErr(0);
12439 return NULL;
12440 }
12441 Py_RETURN_NONE;
12442}
Larry Hastings2f936352014-08-05 14:04:04 +100012443#endif /* MS_WINDOWS */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012444
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012445#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012446/*[clinic input]
12447os.get_blocking -> bool
12448 fd: int
12449 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012450
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012451Get the blocking mode of the file descriptor.
12452
12453Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
12454[clinic start generated code]*/
12455
12456static int
12457os_get_blocking_impl(PyObject *module, int fd)
12458/*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012459{
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012460 int blocking;
12461
Steve Dower8fc89802015-04-12 00:26:27 -040012462 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012463 blocking = _Py_get_blocking(fd);
Steve Dower8fc89802015-04-12 00:26:27 -040012464 _Py_END_SUPPRESS_IPH
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012465 return blocking;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012466}
12467
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012468/*[clinic input]
12469os.set_blocking
12470 fd: int
12471 blocking: bool(accept={int})
12472 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012473
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012474Set the blocking mode of the specified file descriptor.
12475
12476Set the O_NONBLOCK flag if blocking is False,
12477clear the O_NONBLOCK flag otherwise.
12478[clinic start generated code]*/
12479
12480static PyObject *
12481os_set_blocking_impl(PyObject *module, int fd, int blocking)
12482/*[clinic end generated code: output=384eb43aa0762a9d input=bf5c8efdc5860ff3]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012483{
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012484 int result;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012485
Steve Dower8fc89802015-04-12 00:26:27 -040012486 _Py_BEGIN_SUPPRESS_IPH
12487 result = _Py_set_blocking(fd, blocking);
12488 _Py_END_SUPPRESS_IPH
12489 if (result < 0)
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012490 return NULL;
12491 Py_RETURN_NONE;
12492}
12493#endif /* !MS_WINDOWS */
12494
12495
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012496/*[clinic input]
Eddie Elizondob3966632019-11-05 07:16:14 -080012497class os.DirEntry "DirEntry *" "DirEntryType"
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012498[clinic start generated code]*/
Eddie Elizondob3966632019-11-05 07:16:14 -080012499/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3c18c7a448247980]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012500
12501typedef struct {
12502 PyObject_HEAD
12503 PyObject *name;
12504 PyObject *path;
12505 PyObject *stat;
12506 PyObject *lstat;
12507#ifdef MS_WINDOWS
12508 struct _Py_stat_struct win32_lstat;
Victor Stinner0f6d7332017-03-09 17:34:28 +010012509 uint64_t win32_file_index;
Victor Stinner6036e442015-03-08 01:58:04 +010012510 int got_file_index;
12511#else /* POSIX */
Victor Stinner35a97c02015-03-08 02:59:09 +010012512#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012513 unsigned char d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012514#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012515 ino_t d_ino;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012516 int dir_fd;
Victor Stinner6036e442015-03-08 01:58:04 +010012517#endif
12518} DirEntry;
12519
Eddie Elizondob3966632019-11-05 07:16:14 -080012520static PyObject *
12521_disabled_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
12522{
12523 PyErr_Format(PyExc_TypeError,
12524 "cannot create '%.100s' instances", _PyType_Name(type));
12525 return NULL;
12526}
12527
Victor Stinner6036e442015-03-08 01:58:04 +010012528static void
12529DirEntry_dealloc(DirEntry *entry)
12530{
Eddie Elizondob3966632019-11-05 07:16:14 -080012531 PyTypeObject *tp = Py_TYPE(entry);
Victor Stinner6036e442015-03-08 01:58:04 +010012532 Py_XDECREF(entry->name);
12533 Py_XDECREF(entry->path);
12534 Py_XDECREF(entry->stat);
12535 Py_XDECREF(entry->lstat);
Eddie Elizondob3966632019-11-05 07:16:14 -080012536 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
12537 free_func(entry);
12538 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010012539}
12540
12541/* Forward reference */
12542static int
12543DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits);
12544
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012545/*[clinic input]
12546os.DirEntry.is_symlink -> bool
12547
12548Return True if the entry is a symbolic link; cached per entry.
12549[clinic start generated code]*/
12550
Victor Stinner6036e442015-03-08 01:58:04 +010012551static int
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012552os_DirEntry_is_symlink_impl(DirEntry *self)
12553/*[clinic end generated code: output=42244667d7bcfc25 input=1605a1b4b96976c3]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012554{
12555#ifdef MS_WINDOWS
12556 return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
Victor Stinner35a97c02015-03-08 02:59:09 +010012557#elif defined(HAVE_DIRENT_D_TYPE)
12558 /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010012559 if (self->d_type != DT_UNKNOWN)
12560 return self->d_type == DT_LNK;
12561 else
12562 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner35a97c02015-03-08 02:59:09 +010012563#else
12564 /* POSIX without d_type */
12565 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner6036e442015-03-08 01:58:04 +010012566#endif
12567}
12568
12569static PyObject *
Victor Stinner6036e442015-03-08 01:58:04 +010012570DirEntry_fetch_stat(DirEntry *self, int follow_symlinks)
12571{
12572 int result;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012573 STRUCT_STAT st;
12574 PyObject *ub;
Victor Stinner6036e442015-03-08 01:58:04 +010012575
12576#ifdef MS_WINDOWS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012577 if (!PyUnicode_FSDecoder(self->path, &ub))
12578 return NULL;
12579 const wchar_t *path = PyUnicode_AsUnicode(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012580#else /* POSIX */
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012581 if (!PyUnicode_FSConverter(self->path, &ub))
12582 return NULL;
12583 const char *path = PyBytes_AS_STRING(ub);
12584 if (self->dir_fd != DEFAULT_DIR_FD) {
12585#ifdef HAVE_FSTATAT
12586 result = fstatat(self->dir_fd, path, &st,
12587 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
12588#else
12589 PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
12590 return NULL;
12591#endif /* HAVE_FSTATAT */
12592 }
12593 else
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012594#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012595 {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012596 if (follow_symlinks)
12597 result = STAT(path, &st);
12598 else
12599 result = LSTAT(path, &st);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012600 }
12601 Py_DECREF(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012602
12603 if (result != 0)
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012604 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012605
12606 return _pystat_fromstructstat(&st);
12607}
12608
12609static PyObject *
12610DirEntry_get_lstat(DirEntry *self)
12611{
12612 if (!self->lstat) {
12613#ifdef MS_WINDOWS
12614 self->lstat = _pystat_fromstructstat(&self->win32_lstat);
12615#else /* POSIX */
12616 self->lstat = DirEntry_fetch_stat(self, 0);
12617#endif
12618 }
12619 Py_XINCREF(self->lstat);
12620 return self->lstat;
12621}
12622
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012623/*[clinic input]
12624os.DirEntry.stat
12625 *
12626 follow_symlinks: bool = True
12627
12628Return stat_result object for the entry; cached per entry.
12629[clinic start generated code]*/
12630
Victor Stinner6036e442015-03-08 01:58:04 +010012631static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012632os_DirEntry_stat_impl(DirEntry *self, int follow_symlinks)
12633/*[clinic end generated code: output=008593b3a6d01305 input=280d14c1d6f1d00d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012634{
12635 if (!follow_symlinks)
12636 return DirEntry_get_lstat(self);
12637
12638 if (!self->stat) {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012639 int result = os_DirEntry_is_symlink_impl(self);
Victor Stinner6036e442015-03-08 01:58:04 +010012640 if (result == -1)
12641 return NULL;
12642 else if (result)
12643 self->stat = DirEntry_fetch_stat(self, 1);
12644 else
12645 self->stat = DirEntry_get_lstat(self);
12646 }
12647
12648 Py_XINCREF(self->stat);
12649 return self->stat;
12650}
12651
Victor Stinner6036e442015-03-08 01:58:04 +010012652/* Set exception and return -1 on error, 0 for False, 1 for True */
12653static int
12654DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
12655{
12656 PyObject *stat = NULL;
12657 PyObject *st_mode = NULL;
12658 long mode;
12659 int result;
Victor Stinner35a97c02015-03-08 02:59:09 +010012660#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012661 int is_symlink;
12662 int need_stat;
Victor Stinner35a97c02015-03-08 02:59:09 +010012663#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012664#ifdef MS_WINDOWS
12665 unsigned long dir_bits;
12666#endif
12667
12668#ifdef MS_WINDOWS
12669 is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
12670 need_stat = follow_symlinks && is_symlink;
Victor Stinner35a97c02015-03-08 02:59:09 +010012671#elif defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012672 is_symlink = self->d_type == DT_LNK;
12673 need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
12674#endif
12675
Victor Stinner35a97c02015-03-08 02:59:09 +010012676#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012677 if (need_stat) {
Victor Stinner35a97c02015-03-08 02:59:09 +010012678#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012679 stat = os_DirEntry_stat_impl(self, follow_symlinks);
Victor Stinner6036e442015-03-08 01:58:04 +010012680 if (!stat) {
12681 if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
12682 /* If file doesn't exist (anymore), then return False
12683 (i.e., say it's not a file/directory) */
12684 PyErr_Clear();
12685 return 0;
12686 }
12687 goto error;
12688 }
Eddie Elizondob3966632019-11-05 07:16:14 -080012689 st_mode = PyObject_GetAttr(stat, _posixstate_global->st_mode);
Victor Stinner6036e442015-03-08 01:58:04 +010012690 if (!st_mode)
12691 goto error;
12692
12693 mode = PyLong_AsLong(st_mode);
12694 if (mode == -1 && PyErr_Occurred())
12695 goto error;
12696 Py_CLEAR(st_mode);
12697 Py_CLEAR(stat);
12698 result = (mode & S_IFMT) == mode_bits;
Victor Stinner35a97c02015-03-08 02:59:09 +010012699#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012700 }
12701 else if (is_symlink) {
12702 assert(mode_bits != S_IFLNK);
12703 result = 0;
12704 }
12705 else {
12706 assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
12707#ifdef MS_WINDOWS
12708 dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
12709 if (mode_bits == S_IFDIR)
12710 result = dir_bits != 0;
12711 else
12712 result = dir_bits == 0;
12713#else /* POSIX */
12714 if (mode_bits == S_IFDIR)
12715 result = self->d_type == DT_DIR;
12716 else
12717 result = self->d_type == DT_REG;
12718#endif
12719 }
Victor Stinner35a97c02015-03-08 02:59:09 +010012720#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012721
12722 return result;
12723
12724error:
12725 Py_XDECREF(st_mode);
12726 Py_XDECREF(stat);
12727 return -1;
12728}
12729
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012730/*[clinic input]
12731os.DirEntry.is_dir -> bool
12732 *
12733 follow_symlinks: bool = True
Victor Stinner6036e442015-03-08 01:58:04 +010012734
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012735Return True if the entry is a directory; cached per entry.
12736[clinic start generated code]*/
12737
12738static int
12739os_DirEntry_is_dir_impl(DirEntry *self, int follow_symlinks)
12740/*[clinic end generated code: output=ad2e8d54365da287 input=0135232766f53f58]*/
12741{
12742 return DirEntry_test_mode(self, follow_symlinks, S_IFDIR);
Victor Stinner6036e442015-03-08 01:58:04 +010012743}
12744
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012745/*[clinic input]
12746os.DirEntry.is_file -> bool
12747 *
12748 follow_symlinks: bool = True
12749
12750Return True if the entry is a file; cached per entry.
12751[clinic start generated code]*/
12752
12753static int
12754os_DirEntry_is_file_impl(DirEntry *self, int follow_symlinks)
12755/*[clinic end generated code: output=8462ade481d8a476 input=0dc90be168b041ee]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012756{
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012757 return DirEntry_test_mode(self, follow_symlinks, S_IFREG);
Victor Stinner6036e442015-03-08 01:58:04 +010012758}
12759
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012760/*[clinic input]
12761os.DirEntry.inode
Victor Stinner6036e442015-03-08 01:58:04 +010012762
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012763Return inode of the entry; cached per entry.
12764[clinic start generated code]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012765
12766static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012767os_DirEntry_inode_impl(DirEntry *self)
12768/*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012769{
12770#ifdef MS_WINDOWS
12771 if (!self->got_file_index) {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012772 PyObject *unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012773 const wchar_t *path;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012774 STRUCT_STAT stat;
12775 int result;
Victor Stinner6036e442015-03-08 01:58:04 +010012776
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012777 if (!PyUnicode_FSDecoder(self->path, &unicode))
Victor Stinner6036e442015-03-08 01:58:04 +010012778 return NULL;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012779 path = PyUnicode_AsUnicode(unicode);
12780 result = LSTAT(path, &stat);
12781 Py_DECREF(unicode);
Victor Stinner6036e442015-03-08 01:58:04 +010012782
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012783 if (result != 0)
12784 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012785
12786 self->win32_file_index = stat.st_ino;
12787 self->got_file_index = 1;
12788 }
Victor Stinner0f6d7332017-03-09 17:34:28 +010012789 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->win32_file_index));
12790 return PyLong_FromUnsignedLongLong(self->win32_file_index);
Victor Stinner6036e442015-03-08 01:58:04 +010012791#else /* POSIX */
xdegaye50e86032017-05-22 11:15:08 +020012792 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->d_ino));
12793 return PyLong_FromUnsignedLongLong(self->d_ino);
Victor Stinner6036e442015-03-08 01:58:04 +010012794#endif
12795}
12796
12797static PyObject *
12798DirEntry_repr(DirEntry *self)
12799{
12800 return PyUnicode_FromFormat("<DirEntry %R>", self->name);
12801}
12802
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012803/*[clinic input]
12804os.DirEntry.__fspath__
12805
12806Returns the path for the entry.
12807[clinic start generated code]*/
12808
Brett Cannon96881cd2016-06-10 14:37:21 -070012809static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012810os_DirEntry___fspath___impl(DirEntry *self)
12811/*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
Brett Cannon96881cd2016-06-10 14:37:21 -070012812{
12813 Py_INCREF(self->path);
12814 return self->path;
12815}
12816
Victor Stinner6036e442015-03-08 01:58:04 +010012817static PyMemberDef DirEntry_members[] = {
12818 {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
12819 "the entry's base filename, relative to scandir() \"path\" argument"},
12820 {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
12821 "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
12822 {NULL}
12823};
12824
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012825#include "clinic/posixmodule.c.h"
12826
Victor Stinner6036e442015-03-08 01:58:04 +010012827static PyMethodDef DirEntry_methods[] = {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012828 OS_DIRENTRY_IS_DIR_METHODDEF
12829 OS_DIRENTRY_IS_FILE_METHODDEF
12830 OS_DIRENTRY_IS_SYMLINK_METHODDEF
12831 OS_DIRENTRY_STAT_METHODDEF
12832 OS_DIRENTRY_INODE_METHODDEF
12833 OS_DIRENTRY___FSPATH___METHODDEF
Victor Stinner6036e442015-03-08 01:58:04 +010012834 {NULL}
12835};
12836
Eddie Elizondob3966632019-11-05 07:16:14 -080012837static PyType_Slot DirEntryType_slots[] = {
12838 {Py_tp_new, _disabled_new},
12839 {Py_tp_dealloc, DirEntry_dealloc},
12840 {Py_tp_repr, DirEntry_repr},
12841 {Py_tp_methods, DirEntry_methods},
12842 {Py_tp_members, DirEntry_members},
12843 {0, 0},
Victor Stinner6036e442015-03-08 01:58:04 +010012844};
12845
Eddie Elizondob3966632019-11-05 07:16:14 -080012846static PyType_Spec DirEntryType_spec = {
12847 MODNAME ".DirEntry",
12848 sizeof(DirEntry),
12849 0,
12850 Py_TPFLAGS_DEFAULT,
12851 DirEntryType_slots
12852};
12853
12854
Victor Stinner6036e442015-03-08 01:58:04 +010012855#ifdef MS_WINDOWS
12856
12857static wchar_t *
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012858join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
Victor Stinner6036e442015-03-08 01:58:04 +010012859{
12860 Py_ssize_t path_len;
12861 Py_ssize_t size;
12862 wchar_t *result;
12863 wchar_t ch;
12864
12865 if (!path_wide) { /* Default arg: "." */
12866 path_wide = L".";
12867 path_len = 1;
12868 }
12869 else {
12870 path_len = wcslen(path_wide);
12871 }
12872
12873 /* The +1's are for the path separator and the NUL */
12874 size = path_len + 1 + wcslen(filename) + 1;
12875 result = PyMem_New(wchar_t, size);
12876 if (!result) {
12877 PyErr_NoMemory();
12878 return NULL;
12879 }
12880 wcscpy(result, path_wide);
12881 if (path_len > 0) {
12882 ch = result[path_len - 1];
12883 if (ch != SEP && ch != ALTSEP && ch != L':')
12884 result[path_len++] = SEP;
12885 wcscpy(result + path_len, filename);
12886 }
12887 return result;
12888}
12889
12890static PyObject *
12891DirEntry_from_find_data(path_t *path, WIN32_FIND_DATAW *dataW)
12892{
12893 DirEntry *entry;
12894 BY_HANDLE_FILE_INFORMATION file_info;
12895 ULONG reparse_tag;
12896 wchar_t *joined_path;
12897
Eddie Elizondob3966632019-11-05 07:16:14 -080012898 PyObject *DirEntryType = _posixstate_global->DirEntryType;
12899 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010012900 if (!entry)
12901 return NULL;
12902 entry->name = NULL;
12903 entry->path = NULL;
12904 entry->stat = NULL;
12905 entry->lstat = NULL;
12906 entry->got_file_index = 0;
12907
12908 entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
12909 if (!entry->name)
12910 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012911 if (path->narrow) {
12912 Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
12913 if (!entry->name)
12914 goto error;
12915 }
Victor Stinner6036e442015-03-08 01:58:04 +010012916
12917 joined_path = join_path_filenameW(path->wide, dataW->cFileName);
12918 if (!joined_path)
12919 goto error;
12920
12921 entry->path = PyUnicode_FromWideChar(joined_path, -1);
12922 PyMem_Free(joined_path);
12923 if (!entry->path)
12924 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012925 if (path->narrow) {
12926 Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
12927 if (!entry->path)
12928 goto error;
12929 }
Victor Stinner6036e442015-03-08 01:58:04 +010012930
Steve Dowercc16be82016-09-08 10:35:16 -070012931 find_data_to_file_info(dataW, &file_info, &reparse_tag);
Victor Stinner6036e442015-03-08 01:58:04 +010012932 _Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
12933
12934 return (PyObject *)entry;
12935
12936error:
12937 Py_DECREF(entry);
12938 return NULL;
12939}
12940
12941#else /* POSIX */
12942
12943static char *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012944join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
Victor Stinner6036e442015-03-08 01:58:04 +010012945{
12946 Py_ssize_t path_len;
12947 Py_ssize_t size;
12948 char *result;
12949
12950 if (!path_narrow) { /* Default arg: "." */
12951 path_narrow = ".";
12952 path_len = 1;
12953 }
12954 else {
12955 path_len = strlen(path_narrow);
12956 }
12957
12958 if (filename_len == -1)
12959 filename_len = strlen(filename);
12960
12961 /* The +1's are for the path separator and the NUL */
12962 size = path_len + 1 + filename_len + 1;
12963 result = PyMem_New(char, size);
12964 if (!result) {
12965 PyErr_NoMemory();
12966 return NULL;
12967 }
12968 strcpy(result, path_narrow);
12969 if (path_len > 0 && result[path_len - 1] != '/')
12970 result[path_len++] = '/';
12971 strcpy(result + path_len, filename);
12972 return result;
12973}
12974
12975static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012976DirEntry_from_posix_info(path_t *path, const char *name, Py_ssize_t name_len,
Victor Stinner35a97c02015-03-08 02:59:09 +010012977 ino_t d_ino
12978#ifdef HAVE_DIRENT_D_TYPE
12979 , unsigned char d_type
12980#endif
12981 )
Victor Stinner6036e442015-03-08 01:58:04 +010012982{
12983 DirEntry *entry;
12984 char *joined_path;
12985
Eddie Elizondob3966632019-11-05 07:16:14 -080012986 PyObject *DirEntryType = _posixstate_global->DirEntryType;
12987 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010012988 if (!entry)
12989 return NULL;
12990 entry->name = NULL;
12991 entry->path = NULL;
12992 entry->stat = NULL;
12993 entry->lstat = NULL;
12994
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012995 if (path->fd != -1) {
12996 entry->dir_fd = path->fd;
12997 joined_path = NULL;
12998 }
12999 else {
13000 entry->dir_fd = DEFAULT_DIR_FD;
13001 joined_path = join_path_filename(path->narrow, name, name_len);
13002 if (!joined_path)
13003 goto error;
13004 }
Victor Stinner6036e442015-03-08 01:58:04 +010013005
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +030013006 if (!path->narrow || !PyObject_CheckBuffer(path->object)) {
Victor Stinner6036e442015-03-08 01:58:04 +010013007 entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013008 if (joined_path)
13009 entry->path = PyUnicode_DecodeFSDefault(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013010 }
13011 else {
13012 entry->name = PyBytes_FromStringAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013013 if (joined_path)
13014 entry->path = PyBytes_FromString(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013015 }
13016 PyMem_Free(joined_path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013017 if (!entry->name)
13018 goto error;
13019
13020 if (path->fd != -1) {
13021 entry->path = entry->name;
13022 Py_INCREF(entry->path);
13023 }
13024 else if (!entry->path)
Victor Stinner6036e442015-03-08 01:58:04 +010013025 goto error;
13026
Victor Stinner35a97c02015-03-08 02:59:09 +010013027#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010013028 entry->d_type = d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010013029#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013030 entry->d_ino = d_ino;
13031
13032 return (PyObject *)entry;
13033
13034error:
13035 Py_XDECREF(entry);
13036 return NULL;
13037}
13038
13039#endif
13040
13041
13042typedef struct {
13043 PyObject_HEAD
13044 path_t path;
13045#ifdef MS_WINDOWS
13046 HANDLE handle;
13047 WIN32_FIND_DATAW file_data;
13048 int first_time;
13049#else /* POSIX */
13050 DIR *dirp;
13051#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013052#ifdef HAVE_FDOPENDIR
13053 int fd;
13054#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013055} ScandirIterator;
13056
13057#ifdef MS_WINDOWS
13058
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013059static int
13060ScandirIterator_is_closed(ScandirIterator *iterator)
13061{
13062 return iterator->handle == INVALID_HANDLE_VALUE;
13063}
13064
Victor Stinner6036e442015-03-08 01:58:04 +010013065static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013066ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013067{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013068 HANDLE handle = iterator->handle;
13069
13070 if (handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013071 return;
13072
Victor Stinner6036e442015-03-08 01:58:04 +010013073 iterator->handle = INVALID_HANDLE_VALUE;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013074 Py_BEGIN_ALLOW_THREADS
13075 FindClose(handle);
13076 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013077}
13078
13079static PyObject *
13080ScandirIterator_iternext(ScandirIterator *iterator)
13081{
13082 WIN32_FIND_DATAW *file_data = &iterator->file_data;
13083 BOOL success;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013084 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013085
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013086 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013087 if (iterator->handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013088 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013089
13090 while (1) {
13091 if (!iterator->first_time) {
13092 Py_BEGIN_ALLOW_THREADS
13093 success = FindNextFileW(iterator->handle, file_data);
13094 Py_END_ALLOW_THREADS
13095 if (!success) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013096 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013097 if (GetLastError() != ERROR_NO_MORE_FILES)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013098 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013099 break;
13100 }
13101 }
13102 iterator->first_time = 0;
13103
13104 /* Skip over . and .. */
13105 if (wcscmp(file_data->cFileName, L".") != 0 &&
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013106 wcscmp(file_data->cFileName, L"..") != 0) {
13107 entry = DirEntry_from_find_data(&iterator->path, file_data);
13108 if (!entry)
13109 break;
13110 return entry;
13111 }
Victor Stinner6036e442015-03-08 01:58:04 +010013112
13113 /* Loop till we get a non-dot directory or finish iterating */
13114 }
13115
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013116 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013117 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013118 return NULL;
13119}
13120
13121#else /* POSIX */
13122
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013123static int
13124ScandirIterator_is_closed(ScandirIterator *iterator)
13125{
13126 return !iterator->dirp;
13127}
13128
Victor Stinner6036e442015-03-08 01:58:04 +010013129static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013130ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013131{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013132 DIR *dirp = iterator->dirp;
13133
13134 if (!dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013135 return;
13136
Victor Stinner6036e442015-03-08 01:58:04 +010013137 iterator->dirp = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013138 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013139#ifdef HAVE_FDOPENDIR
13140 if (iterator->path.fd != -1)
13141 rewinddir(dirp);
13142#endif
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013143 closedir(dirp);
13144 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013145 return;
13146}
13147
13148static PyObject *
13149ScandirIterator_iternext(ScandirIterator *iterator)
13150{
13151 struct dirent *direntp;
13152 Py_ssize_t name_len;
13153 int is_dot;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013154 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013155
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013156 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013157 if (!iterator->dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013158 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013159
13160 while (1) {
13161 errno = 0;
13162 Py_BEGIN_ALLOW_THREADS
13163 direntp = readdir(iterator->dirp);
13164 Py_END_ALLOW_THREADS
13165
13166 if (!direntp) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013167 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013168 if (errno != 0)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013169 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013170 break;
13171 }
13172
13173 /* Skip over . and .. */
13174 name_len = NAMLEN(direntp);
13175 is_dot = direntp->d_name[0] == '.' &&
13176 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
13177 if (!is_dot) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013178 entry = DirEntry_from_posix_info(&iterator->path, direntp->d_name,
Victor Stinner35a97c02015-03-08 02:59:09 +010013179 name_len, direntp->d_ino
13180#ifdef HAVE_DIRENT_D_TYPE
13181 , direntp->d_type
13182#endif
13183 );
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013184 if (!entry)
13185 break;
13186 return entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013187 }
13188
13189 /* Loop till we get a non-dot directory or finish iterating */
13190 }
13191
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013192 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013193 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013194 return NULL;
13195}
13196
13197#endif
13198
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013199static PyObject *
13200ScandirIterator_close(ScandirIterator *self, PyObject *args)
13201{
13202 ScandirIterator_closedir(self);
13203 Py_RETURN_NONE;
13204}
13205
13206static PyObject *
13207ScandirIterator_enter(PyObject *self, PyObject *args)
13208{
13209 Py_INCREF(self);
13210 return self;
13211}
13212
13213static PyObject *
13214ScandirIterator_exit(ScandirIterator *self, PyObject *args)
13215{
13216 ScandirIterator_closedir(self);
13217 Py_RETURN_NONE;
13218}
13219
Victor Stinner6036e442015-03-08 01:58:04 +010013220static void
Victor Stinner7bfa4092016-03-23 00:43:54 +010013221ScandirIterator_finalize(ScandirIterator *iterator)
13222{
13223 PyObject *error_type, *error_value, *error_traceback;
13224
13225 /* Save the current exception, if any. */
13226 PyErr_Fetch(&error_type, &error_value, &error_traceback);
13227
13228 if (!ScandirIterator_is_closed(iterator)) {
13229 ScandirIterator_closedir(iterator);
13230
13231 if (PyErr_ResourceWarning((PyObject *)iterator, 1,
13232 "unclosed scandir iterator %R", iterator)) {
13233 /* Spurious errors can appear at shutdown */
13234 if (PyErr_ExceptionMatches(PyExc_Warning)) {
13235 PyErr_WriteUnraisable((PyObject *) iterator);
13236 }
13237 }
13238 }
13239
Victor Stinner7bfa4092016-03-23 00:43:54 +010013240 path_cleanup(&iterator->path);
13241
13242 /* Restore the saved exception. */
13243 PyErr_Restore(error_type, error_value, error_traceback);
13244}
13245
13246static void
Victor Stinner6036e442015-03-08 01:58:04 +010013247ScandirIterator_dealloc(ScandirIterator *iterator)
13248{
Eddie Elizondob3966632019-11-05 07:16:14 -080013249 PyTypeObject *tp = Py_TYPE(iterator);
Victor Stinner7bfa4092016-03-23 00:43:54 +010013250 if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
13251 return;
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013252
Eddie Elizondob3966632019-11-05 07:16:14 -080013253 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
13254 free_func(iterator);
13255 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010013256}
13257
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013258static PyMethodDef ScandirIterator_methods[] = {
13259 {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
13260 {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
13261 {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
13262 {NULL}
13263};
13264
Eddie Elizondob3966632019-11-05 07:16:14 -080013265static PyType_Slot ScandirIteratorType_slots[] = {
13266 {Py_tp_new, _disabled_new},
13267 {Py_tp_dealloc, ScandirIterator_dealloc},
13268 {Py_tp_finalize, ScandirIterator_finalize},
13269 {Py_tp_iter, PyObject_SelfIter},
13270 {Py_tp_iternext, ScandirIterator_iternext},
13271 {Py_tp_methods, ScandirIterator_methods},
13272 {0, 0},
13273};
13274
13275static PyType_Spec ScandirIteratorType_spec = {
13276 MODNAME ".ScandirIterator",
13277 sizeof(ScandirIterator),
13278 0,
13279 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE,
13280 ScandirIteratorType_slots
Victor Stinner6036e442015-03-08 01:58:04 +010013281};
13282
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013283/*[clinic input]
13284os.scandir
13285
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013286 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013287
13288Return an iterator of DirEntry objects for given path.
13289
BNMetricsb9427072018-11-02 15:20:19 +000013290path can be specified as either str, bytes, or a path-like object. If path
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013291is bytes, the names of yielded DirEntry objects will also be bytes; in
13292all other circumstances they will be str.
13293
13294If path is None, uses the path='.'.
13295[clinic start generated code]*/
13296
Victor Stinner6036e442015-03-08 01:58:04 +010013297static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013298os_scandir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +000013299/*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013300{
13301 ScandirIterator *iterator;
Victor Stinner6036e442015-03-08 01:58:04 +010013302#ifdef MS_WINDOWS
13303 wchar_t *path_strW;
13304#else
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013305 const char *path_str;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013306#ifdef HAVE_FDOPENDIR
13307 int fd = -1;
13308#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013309#endif
13310
Steve Dower60419a72019-06-24 08:42:54 -070013311 if (PySys_Audit("os.scandir", "O",
13312 path->object ? path->object : Py_None) < 0) {
13313 return NULL;
13314 }
13315
Eddie Elizondob3966632019-11-05 07:16:14 -080013316 PyObject *ScandirIteratorType = _posixstate(module)->ScandirIteratorType;
13317 iterator = PyObject_New(ScandirIterator, (PyTypeObject *)ScandirIteratorType);
Victor Stinner6036e442015-03-08 01:58:04 +010013318 if (!iterator)
13319 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013320
13321#ifdef MS_WINDOWS
13322 iterator->handle = INVALID_HANDLE_VALUE;
13323#else
13324 iterator->dirp = NULL;
13325#endif
13326
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013327 memcpy(&iterator->path, path, sizeof(path_t));
Serhiy Storchaka095ef732017-02-09 20:05:51 +020013328 /* Move the ownership to iterator->path */
13329 path->object = NULL;
13330 path->cleanup = NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013331
13332#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +010013333 iterator->first_time = 1;
13334
13335 path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
13336 if (!path_strW)
13337 goto error;
13338
13339 Py_BEGIN_ALLOW_THREADS
13340 iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
13341 Py_END_ALLOW_THREADS
13342
13343 PyMem_Free(path_strW);
13344
13345 if (iterator->handle == INVALID_HANDLE_VALUE) {
13346 path_error(&iterator->path);
13347 goto error;
13348 }
13349#else /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010013350 errno = 0;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013351#ifdef HAVE_FDOPENDIR
13352 if (path->fd != -1) {
13353 /* closedir() closes the FD, so we duplicate it */
13354 fd = _Py_dup(path->fd);
13355 if (fd == -1)
13356 goto error;
13357
13358 Py_BEGIN_ALLOW_THREADS
13359 iterator->dirp = fdopendir(fd);
13360 Py_END_ALLOW_THREADS
13361 }
13362 else
13363#endif
13364 {
13365 if (iterator->path.narrow)
13366 path_str = iterator->path.narrow;
13367 else
13368 path_str = ".";
13369
13370 Py_BEGIN_ALLOW_THREADS
13371 iterator->dirp = opendir(path_str);
13372 Py_END_ALLOW_THREADS
13373 }
Victor Stinner6036e442015-03-08 01:58:04 +010013374
13375 if (!iterator->dirp) {
13376 path_error(&iterator->path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013377#ifdef HAVE_FDOPENDIR
13378 if (fd != -1) {
13379 Py_BEGIN_ALLOW_THREADS
13380 close(fd);
13381 Py_END_ALLOW_THREADS
13382 }
13383#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013384 goto error;
13385 }
13386#endif
13387
13388 return (PyObject *)iterator;
13389
13390error:
13391 Py_DECREF(iterator);
13392 return NULL;
13393}
13394
Ethan Furman410ef8e2016-06-04 12:06:26 -070013395/*
13396 Return the file system path representation of the object.
13397
13398 If the object is str or bytes, then allow it to pass through with
13399 an incremented refcount. If the object defines __fspath__(), then
13400 return the result of that method. All other types raise a TypeError.
13401*/
13402PyObject *
13403PyOS_FSPath(PyObject *path)
13404{
Brett Cannon3f9183b2016-08-26 14:44:48 -070013405 /* For error message reasons, this function is manually inlined in
13406 path_converter(). */
Ethan Furman410ef8e2016-06-04 12:06:26 -070013407 PyObject *func = NULL;
13408 PyObject *path_repr = NULL;
13409
13410 if (PyUnicode_Check(path) || PyBytes_Check(path)) {
13411 Py_INCREF(path);
13412 return path;
13413 }
13414
13415 func = _PyObject_LookupSpecial(path, &PyId___fspath__);
13416 if (NULL == func) {
13417 return PyErr_Format(PyExc_TypeError,
13418 "expected str, bytes or os.PathLike object, "
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013419 "not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -080013420 _PyType_Name(Py_TYPE(path)));
Ethan Furman410ef8e2016-06-04 12:06:26 -070013421 }
13422
Victor Stinnerf17c3de2016-12-06 18:46:19 +010013423 path_repr = _PyObject_CallNoArg(func);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013424 Py_DECREF(func);
Brett Cannon044283a2016-07-15 10:41:49 -070013425 if (NULL == path_repr) {
13426 return NULL;
13427 }
13428
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013429 if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
13430 PyErr_Format(PyExc_TypeError,
13431 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -080013432 "not %.200s", _PyType_Name(Py_TYPE(path)),
13433 _PyType_Name(Py_TYPE(path_repr)));
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013434 Py_DECREF(path_repr);
13435 return NULL;
13436 }
13437
Ethan Furman410ef8e2016-06-04 12:06:26 -070013438 return path_repr;
13439}
13440
13441/*[clinic input]
13442os.fspath
13443
13444 path: object
13445
13446Return the file system path representation of the object.
13447
Brett Cannonb4f43e92016-06-09 14:32:08 -070013448If the object is str or bytes, then allow it to pass through as-is. If the
13449object defines __fspath__(), then return the result of that method. All other
13450types raise a TypeError.
Ethan Furman410ef8e2016-06-04 12:06:26 -070013451[clinic start generated code]*/
13452
13453static PyObject *
Serhiy Storchaka2954f832016-07-07 18:20:03 +030013454os_fspath_impl(PyObject *module, PyObject *path)
13455/*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
Ethan Furman410ef8e2016-06-04 12:06:26 -070013456{
13457 return PyOS_FSPath(path);
13458}
Victor Stinner6036e442015-03-08 01:58:04 +010013459
Victor Stinner9b1f4742016-09-06 16:18:52 -070013460#ifdef HAVE_GETRANDOM_SYSCALL
13461/*[clinic input]
13462os.getrandom
13463
13464 size: Py_ssize_t
13465 flags: int=0
13466
13467Obtain a series of random bytes.
13468[clinic start generated code]*/
13469
13470static PyObject *
13471os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
13472/*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
13473{
Victor Stinner9b1f4742016-09-06 16:18:52 -070013474 PyObject *bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013475 Py_ssize_t n;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013476
13477 if (size < 0) {
13478 errno = EINVAL;
13479 return posix_error();
13480 }
13481
Victor Stinnerec2319c2016-09-20 23:00:59 +020013482 bytes = PyBytes_FromStringAndSize(NULL, size);
13483 if (bytes == NULL) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013484 PyErr_NoMemory();
13485 return NULL;
13486 }
13487
13488 while (1) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013489 n = syscall(SYS_getrandom,
13490 PyBytes_AS_STRING(bytes),
13491 PyBytes_GET_SIZE(bytes),
13492 flags);
Victor Stinner9b1f4742016-09-06 16:18:52 -070013493 if (n < 0 && errno == EINTR) {
13494 if (PyErr_CheckSignals() < 0) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013495 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013496 }
Victor Stinnerec2319c2016-09-20 23:00:59 +020013497
13498 /* getrandom() was interrupted by a signal: retry */
Victor Stinner9b1f4742016-09-06 16:18:52 -070013499 continue;
13500 }
13501 break;
13502 }
13503
13504 if (n < 0) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013505 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerec2319c2016-09-20 23:00:59 +020013506 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013507 }
13508
Victor Stinnerec2319c2016-09-20 23:00:59 +020013509 if (n != size) {
13510 _PyBytes_Resize(&bytes, n);
13511 }
Victor Stinner9b1f4742016-09-06 16:18:52 -070013512
13513 return bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013514
13515error:
13516 Py_DECREF(bytes);
13517 return NULL;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013518}
13519#endif /* HAVE_GETRANDOM_SYSCALL */
13520
Steve Dower2438cdf2019-03-29 16:37:16 -070013521#ifdef MS_WINDOWS
13522/* bpo-36085: Helper functions for managing DLL search directories
13523 * on win32
13524 */
13525
13526typedef DLL_DIRECTORY_COOKIE (WINAPI *PAddDllDirectory)(PCWSTR newDirectory);
13527typedef BOOL (WINAPI *PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE cookie);
13528
13529/*[clinic input]
13530os._add_dll_directory
13531
13532 path: path_t
13533
13534Add a path to the DLL search path.
13535
13536This search path is used when resolving dependencies for imported
13537extension modules (the module itself is resolved through sys.path),
13538and also by ctypes.
13539
13540Returns an opaque value that may be passed to os.remove_dll_directory
13541to remove this directory from the search path.
13542[clinic start generated code]*/
13543
13544static PyObject *
13545os__add_dll_directory_impl(PyObject *module, path_t *path)
13546/*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
13547{
13548 HMODULE hKernel32;
13549 PAddDllDirectory AddDllDirectory;
13550 DLL_DIRECTORY_COOKIE cookie = 0;
13551 DWORD err = 0;
13552
13553 /* For Windows 7, we have to load this. As this will be a fairly
13554 infrequent operation, just do it each time. Kernel32 is always
13555 loaded. */
13556 Py_BEGIN_ALLOW_THREADS
13557 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13558 !(AddDllDirectory = (PAddDllDirectory)GetProcAddress(
13559 hKernel32, "AddDllDirectory")) ||
13560 !(cookie = (*AddDllDirectory)(path->wide))) {
13561 err = GetLastError();
13562 }
13563 Py_END_ALLOW_THREADS
13564
13565 if (err) {
13566 return win32_error_object_err("add_dll_directory",
13567 path->object, err);
13568 }
13569
13570 return PyCapsule_New(cookie, "DLL directory cookie", NULL);
13571}
13572
13573/*[clinic input]
13574os._remove_dll_directory
13575
13576 cookie: object
13577
13578Removes a path from the DLL search path.
13579
13580The parameter is an opaque value that was returned from
13581os.add_dll_directory. You can only remove directories that you added
13582yourself.
13583[clinic start generated code]*/
13584
13585static PyObject *
13586os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
13587/*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
13588{
13589 HMODULE hKernel32;
13590 PRemoveDllDirectory RemoveDllDirectory;
13591 DLL_DIRECTORY_COOKIE cookieValue;
13592 DWORD err = 0;
13593
13594 if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
13595 PyErr_SetString(PyExc_TypeError,
13596 "Provided cookie was not returned from os.add_dll_directory");
13597 return NULL;
13598 }
13599
13600 cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
13601 cookie, "DLL directory cookie");
13602
13603 /* For Windows 7, we have to load this. As this will be a fairly
13604 infrequent operation, just do it each time. Kernel32 is always
13605 loaded. */
13606 Py_BEGIN_ALLOW_THREADS
13607 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13608 !(RemoveDllDirectory = (PRemoveDllDirectory)GetProcAddress(
13609 hKernel32, "RemoveDllDirectory")) ||
13610 !(*RemoveDllDirectory)(cookieValue)) {
13611 err = GetLastError();
13612 }
13613 Py_END_ALLOW_THREADS
13614
13615 if (err) {
13616 return win32_error_object_err("remove_dll_directory",
13617 NULL, err);
13618 }
13619
13620 if (PyCapsule_SetName(cookie, NULL)) {
13621 return NULL;
13622 }
13623
13624 Py_RETURN_NONE;
13625}
13626
13627#endif
Larry Hastings31826802013-10-19 00:09:25 -070013628
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013629static PyMethodDef posix_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -070013630
13631 OS_STAT_METHODDEF
13632 OS_ACCESS_METHODDEF
13633 OS_TTYNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013634 OS_CHDIR_METHODDEF
13635 OS_CHFLAGS_METHODDEF
13636 OS_CHMOD_METHODDEF
13637 OS_FCHMOD_METHODDEF
13638 OS_LCHMOD_METHODDEF
13639 OS_CHOWN_METHODDEF
13640 OS_FCHOWN_METHODDEF
13641 OS_LCHOWN_METHODDEF
13642 OS_LCHFLAGS_METHODDEF
13643 OS_CHROOT_METHODDEF
13644 OS_CTERMID_METHODDEF
13645 OS_GETCWD_METHODDEF
13646 OS_GETCWDB_METHODDEF
13647 OS_LINK_METHODDEF
13648 OS_LISTDIR_METHODDEF
13649 OS_LSTAT_METHODDEF
13650 OS_MKDIR_METHODDEF
13651 OS_NICE_METHODDEF
13652 OS_GETPRIORITY_METHODDEF
13653 OS_SETPRIORITY_METHODDEF
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000013654 OS_POSIX_SPAWN_METHODDEF
Joannah Nanjekye92b83222019-01-16 16:29:26 +030013655 OS_POSIX_SPAWNP_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013656 OS_READLINK_METHODDEF
Pablo Galindoaac4d032019-05-31 19:39:47 +010013657 OS_COPY_FILE_RANGE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013658 OS_RENAME_METHODDEF
13659 OS_REPLACE_METHODDEF
13660 OS_RMDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013661 OS_SYMLINK_METHODDEF
13662 OS_SYSTEM_METHODDEF
13663 OS_UMASK_METHODDEF
13664 OS_UNAME_METHODDEF
13665 OS_UNLINK_METHODDEF
13666 OS_REMOVE_METHODDEF
13667 OS_UTIME_METHODDEF
13668 OS_TIMES_METHODDEF
13669 OS__EXIT_METHODDEF
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020013670 OS__FCOPYFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013671 OS_EXECV_METHODDEF
13672 OS_EXECVE_METHODDEF
13673 OS_SPAWNV_METHODDEF
13674 OS_SPAWNVE_METHODDEF
13675 OS_FORK1_METHODDEF
13676 OS_FORK_METHODDEF
Antoine Pitrou346cbd32017-05-27 17:50:54 +020013677 OS_REGISTER_AT_FORK_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013678 OS_SCHED_GET_PRIORITY_MAX_METHODDEF
13679 OS_SCHED_GET_PRIORITY_MIN_METHODDEF
13680 OS_SCHED_GETPARAM_METHODDEF
13681 OS_SCHED_GETSCHEDULER_METHODDEF
13682 OS_SCHED_RR_GET_INTERVAL_METHODDEF
13683 OS_SCHED_SETPARAM_METHODDEF
13684 OS_SCHED_SETSCHEDULER_METHODDEF
13685 OS_SCHED_YIELD_METHODDEF
13686 OS_SCHED_SETAFFINITY_METHODDEF
13687 OS_SCHED_GETAFFINITY_METHODDEF
13688 OS_OPENPTY_METHODDEF
13689 OS_FORKPTY_METHODDEF
13690 OS_GETEGID_METHODDEF
13691 OS_GETEUID_METHODDEF
13692 OS_GETGID_METHODDEF
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +020013693#ifdef HAVE_GETGROUPLIST
13694 {"getgrouplist", posix_getgrouplist, METH_VARARGS, posix_getgrouplist__doc__},
13695#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013696 OS_GETGROUPS_METHODDEF
13697 OS_GETPID_METHODDEF
13698 OS_GETPGRP_METHODDEF
13699 OS_GETPPID_METHODDEF
13700 OS_GETUID_METHODDEF
13701 OS_GETLOGIN_METHODDEF
13702 OS_KILL_METHODDEF
13703 OS_KILLPG_METHODDEF
13704 OS_PLOCK_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013705#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -070013706 OS_STARTFILE_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013707#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013708 OS_SETUID_METHODDEF
13709 OS_SETEUID_METHODDEF
13710 OS_SETREUID_METHODDEF
13711 OS_SETGID_METHODDEF
13712 OS_SETEGID_METHODDEF
13713 OS_SETREGID_METHODDEF
13714 OS_SETGROUPS_METHODDEF
Antoine Pitroub7572f02009-12-02 20:46:48 +000013715#ifdef HAVE_INITGROUPS
Victor Stinner8c62be82010-05-06 00:08:46 +000013716 {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__},
Antoine Pitroub7572f02009-12-02 20:46:48 +000013717#endif /* HAVE_INITGROUPS */
Larry Hastings2f936352014-08-05 14:04:04 +100013718 OS_GETPGID_METHODDEF
13719 OS_SETPGRP_METHODDEF
13720 OS_WAIT_METHODDEF
13721 OS_WAIT3_METHODDEF
13722 OS_WAIT4_METHODDEF
13723 OS_WAITID_METHODDEF
13724 OS_WAITPID_METHODDEF
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -080013725 OS_PIDFD_OPEN_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013726 OS_GETSID_METHODDEF
13727 OS_SETSID_METHODDEF
13728 OS_SETPGID_METHODDEF
13729 OS_TCGETPGRP_METHODDEF
13730 OS_TCSETPGRP_METHODDEF
13731 OS_OPEN_METHODDEF
13732 OS_CLOSE_METHODDEF
13733 OS_CLOSERANGE_METHODDEF
13734 OS_DEVICE_ENCODING_METHODDEF
13735 OS_DUP_METHODDEF
13736 OS_DUP2_METHODDEF
13737 OS_LOCKF_METHODDEF
13738 OS_LSEEK_METHODDEF
13739 OS_READ_METHODDEF
13740 OS_READV_METHODDEF
13741 OS_PREAD_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013742 OS_PREADV_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013743 OS_WRITE_METHODDEF
13744 OS_WRITEV_METHODDEF
13745 OS_PWRITE_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013746 OS_PWRITEV_METHODDEF
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013747#ifdef HAVE_SENDFILE
Serhiy Storchaka62be7422018-11-27 13:27:31 +020013748 {"sendfile", (PyCFunction)(void(*)(void))posix_sendfile, METH_VARARGS | METH_KEYWORDS,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013749 posix_sendfile__doc__},
13750#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013751 OS_FSTAT_METHODDEF
13752 OS_ISATTY_METHODDEF
13753 OS_PIPE_METHODDEF
13754 OS_PIPE2_METHODDEF
13755 OS_MKFIFO_METHODDEF
13756 OS_MKNOD_METHODDEF
13757 OS_MAJOR_METHODDEF
13758 OS_MINOR_METHODDEF
13759 OS_MAKEDEV_METHODDEF
13760 OS_FTRUNCATE_METHODDEF
13761 OS_TRUNCATE_METHODDEF
13762 OS_POSIX_FALLOCATE_METHODDEF
13763 OS_POSIX_FADVISE_METHODDEF
13764 OS_PUTENV_METHODDEF
13765 OS_UNSETENV_METHODDEF
13766 OS_STRERROR_METHODDEF
13767 OS_FCHDIR_METHODDEF
13768 OS_FSYNC_METHODDEF
13769 OS_SYNC_METHODDEF
13770 OS_FDATASYNC_METHODDEF
13771 OS_WCOREDUMP_METHODDEF
13772 OS_WIFCONTINUED_METHODDEF
13773 OS_WIFSTOPPED_METHODDEF
13774 OS_WIFSIGNALED_METHODDEF
13775 OS_WIFEXITED_METHODDEF
13776 OS_WEXITSTATUS_METHODDEF
13777 OS_WTERMSIG_METHODDEF
13778 OS_WSTOPSIG_METHODDEF
13779 OS_FSTATVFS_METHODDEF
13780 OS_STATVFS_METHODDEF
13781 OS_CONFSTR_METHODDEF
13782 OS_SYSCONF_METHODDEF
13783 OS_FPATHCONF_METHODDEF
13784 OS_PATHCONF_METHODDEF
13785 OS_ABORT_METHODDEF
Serhiy Storchakaf0b50152015-05-13 00:52:39 +030013786 OS__GETFULLPATHNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013787 OS__GETDISKUSAGE_METHODDEF
13788 OS__GETFINALPATHNAME_METHODDEF
13789 OS__GETVOLUMEPATHNAME_METHODDEF
13790 OS_GETLOADAVG_METHODDEF
13791 OS_URANDOM_METHODDEF
13792 OS_SETRESUID_METHODDEF
13793 OS_SETRESGID_METHODDEF
13794 OS_GETRESUID_METHODDEF
13795 OS_GETRESGID_METHODDEF
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000013796
Larry Hastings2f936352014-08-05 14:04:04 +100013797 OS_GETXATTR_METHODDEF
13798 OS_SETXATTR_METHODDEF
13799 OS_REMOVEXATTR_METHODDEF
13800 OS_LISTXATTR_METHODDEF
13801
Antoine Pitroubcf2b592012-02-08 23:28:36 +010013802#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
13803 {"get_terminal_size", get_terminal_size, METH_VARARGS, termsize__doc__},
13804#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013805 OS_CPU_COUNT_METHODDEF
13806 OS_GET_INHERITABLE_METHODDEF
13807 OS_SET_INHERITABLE_METHODDEF
13808 OS_GET_HANDLE_INHERITABLE_METHODDEF
13809 OS_SET_HANDLE_INHERITABLE_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013810#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013811 OS_GET_BLOCKING_METHODDEF
13812 OS_SET_BLOCKING_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013813#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013814 OS_SCANDIR_METHODDEF
Ethan Furman410ef8e2016-06-04 12:06:26 -070013815 OS_FSPATH_METHODDEF
Victor Stinner9b1f4742016-09-06 16:18:52 -070013816 OS_GETRANDOM_METHODDEF
Zackery Spytz43fdbd22019-05-29 13:57:07 -060013817 OS_MEMFD_CREATE_METHODDEF
Steve Dower2438cdf2019-03-29 16:37:16 -070013818#ifdef MS_WINDOWS
13819 OS__ADD_DLL_DIRECTORY_METHODDEF
13820 OS__REMOVE_DLL_DIRECTORY_METHODDEF
13821#endif
Victor Stinner8c62be82010-05-06 00:08:46 +000013822 {NULL, NULL} /* Sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013823};
13824
Barry Warsaw4a342091996-12-19 23:50:02 +000013825static int
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013826all_ins(PyObject *m)
Barry Warsaw4a342091996-12-19 23:50:02 +000013827{
Guido van Rossum94f6f721999-01-06 18:42:14 +000013828#ifdef F_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013829 if (PyModule_AddIntMacro(m, F_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013830#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013831#ifdef R_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013832 if (PyModule_AddIntMacro(m, R_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013833#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013834#ifdef W_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013835 if (PyModule_AddIntMacro(m, W_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013836#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013837#ifdef X_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013838 if (PyModule_AddIntMacro(m, X_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013839#endif
Fred Drakec9680921999-12-13 16:37:25 +000013840#ifdef NGROUPS_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013841 if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
Fred Drakec9680921999-12-13 16:37:25 +000013842#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013843#ifdef TMP_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013844 if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013845#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013846#ifdef WCONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013847 if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013848#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013849#ifdef WNOHANG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013850 if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013851#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013852#ifdef WUNTRACED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013853 if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013854#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013855#ifdef O_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013856 if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013857#endif
13858#ifdef O_WRONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013859 if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013860#endif
13861#ifdef O_RDWR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013862 if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013863#endif
13864#ifdef O_NDELAY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013865 if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013866#endif
13867#ifdef O_NONBLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013868 if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013869#endif
13870#ifdef O_APPEND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013871 if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013872#endif
13873#ifdef O_DSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013874 if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013875#endif
13876#ifdef O_RSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013877 if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013878#endif
13879#ifdef O_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013880 if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013881#endif
13882#ifdef O_NOCTTY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013883 if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013884#endif
13885#ifdef O_CREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013886 if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013887#endif
13888#ifdef O_EXCL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013889 if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013890#endif
13891#ifdef O_TRUNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013892 if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013893#endif
Guido van Rossum98d9d091997-08-08 21:48:51 +000013894#ifdef O_BINARY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013895 if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013896#endif
13897#ifdef O_TEXT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013898 if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013899#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013900#ifdef O_XATTR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013901 if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013902#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013903#ifdef O_LARGEFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013904 if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013905#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013906#ifndef __GNU__
Skip Montanaro5ff14922005-05-16 02:42:22 +000013907#ifdef O_SHLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013908 if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013909#endif
13910#ifdef O_EXLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013911 if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013912#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013913#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013914#ifdef O_EXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013915 if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013916#endif
13917#ifdef O_SEARCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013918 if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013919#endif
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013920#ifdef O_PATH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013921 if (PyModule_AddIntMacro(m, O_PATH)) return -1;
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013922#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013923#ifdef O_TTY_INIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013924 if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013925#endif
Christian Heimes177b3f92013-08-16 14:35:09 +020013926#ifdef O_TMPFILE
13927 if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
13928#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013929#ifdef PRIO_PROCESS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013930 if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013931#endif
13932#ifdef PRIO_PGRP
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013933 if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013934#endif
13935#ifdef PRIO_USER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013936 if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013937#endif
Charles-François Natali1e045b12011-05-22 20:42:32 +020013938#ifdef O_CLOEXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013939 if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
Charles-François Natali1e045b12011-05-22 20:42:32 +020013940#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013941#ifdef O_ACCMODE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013942 if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013943#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013944
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013945
Jesus Cea94363612012-06-22 18:32:07 +020013946#ifdef SEEK_HOLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013947 if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013948#endif
13949#ifdef SEEK_DATA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013950 if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013951#endif
13952
Tim Peters5aa91602002-01-30 05:46:57 +000013953/* MS Windows */
13954#ifdef O_NOINHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000013955 /* Don't inherit in child processes. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013956 if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013957#endif
13958#ifdef _O_SHORT_LIVED
Victor Stinner8c62be82010-05-06 00:08:46 +000013959 /* Optimize for short life (keep in memory). */
13960 /* MS forgot to define this one with a non-underscore form too. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013961 if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013962#endif
13963#ifdef O_TEMPORARY
Victor Stinner8c62be82010-05-06 00:08:46 +000013964 /* Automatically delete when last handle is closed. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013965 if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013966#endif
13967#ifdef O_RANDOM
Victor Stinner8c62be82010-05-06 00:08:46 +000013968 /* Optimize for random access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013969 if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013970#endif
13971#ifdef O_SEQUENTIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000013972 /* Optimize for sequential access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013973 if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013974#endif
13975
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013976/* GNU extensions. */
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013977#ifdef O_ASYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000013978 /* Send a SIGIO signal whenever input or output
13979 becomes available on file descriptor */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013980 if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013981#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013982#ifdef O_DIRECT
Victor Stinner8c62be82010-05-06 00:08:46 +000013983 /* Direct disk access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013984 if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013985#endif
13986#ifdef O_DIRECTORY
Victor Stinner8c62be82010-05-06 00:08:46 +000013987 /* Must be a directory. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013988 if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013989#endif
13990#ifdef O_NOFOLLOW
Victor Stinner8c62be82010-05-06 00:08:46 +000013991 /* Do not follow links. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013992 if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013993#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013994#ifdef O_NOLINKS
13995 /* Fails if link count of the named file is greater than 1 */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013996 if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013997#endif
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000013998#ifdef O_NOATIME
Victor Stinner8c62be82010-05-06 00:08:46 +000013999 /* Do not update the access time. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014000 if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000014001#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +000014002
Victor Stinner8c62be82010-05-06 00:08:46 +000014003 /* These come from sysexits.h */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014004#ifdef EX_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014005 if (PyModule_AddIntMacro(m, EX_OK)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014006#endif /* EX_OK */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014007#ifdef EX_USAGE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014008 if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014009#endif /* EX_USAGE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014010#ifdef EX_DATAERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014011 if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014012#endif /* EX_DATAERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014013#ifdef EX_NOINPUT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014014 if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014015#endif /* EX_NOINPUT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014016#ifdef EX_NOUSER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014017 if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014018#endif /* EX_NOUSER */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014019#ifdef EX_NOHOST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014020 if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014021#endif /* EX_NOHOST */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014022#ifdef EX_UNAVAILABLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014023 if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014024#endif /* EX_UNAVAILABLE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014025#ifdef EX_SOFTWARE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014026 if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014027#endif /* EX_SOFTWARE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014028#ifdef EX_OSERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014029 if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014030#endif /* EX_OSERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014031#ifdef EX_OSFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014032 if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014033#endif /* EX_OSFILE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014034#ifdef EX_CANTCREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014035 if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014036#endif /* EX_CANTCREAT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014037#ifdef EX_IOERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014038 if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014039#endif /* EX_IOERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014040#ifdef EX_TEMPFAIL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014041 if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014042#endif /* EX_TEMPFAIL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014043#ifdef EX_PROTOCOL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014044 if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014045#endif /* EX_PROTOCOL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014046#ifdef EX_NOPERM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014047 if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014048#endif /* EX_NOPERM */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014049#ifdef EX_CONFIG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014050 if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014051#endif /* EX_CONFIG */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014052#ifdef EX_NOTFOUND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014053 if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014054#endif /* EX_NOTFOUND */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014055
Amaury Forgeot d'Arc66d00ad2010-09-10 18:11:45 +000014056 /* statvfs */
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014057#ifdef ST_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014058 if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014059#endif /* ST_RDONLY */
14060#ifdef ST_NOSUID
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014061 if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014062#endif /* ST_NOSUID */
14063
doko@ubuntu.comca616a22013-12-08 15:23:07 +010014064 /* GNU extensions */
14065#ifdef ST_NODEV
14066 if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
14067#endif /* ST_NODEV */
14068#ifdef ST_NOEXEC
14069 if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
14070#endif /* ST_NOEXEC */
14071#ifdef ST_SYNCHRONOUS
14072 if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
14073#endif /* ST_SYNCHRONOUS */
14074#ifdef ST_MANDLOCK
14075 if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
14076#endif /* ST_MANDLOCK */
14077#ifdef ST_WRITE
14078 if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
14079#endif /* ST_WRITE */
14080#ifdef ST_APPEND
14081 if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
14082#endif /* ST_APPEND */
14083#ifdef ST_NOATIME
14084 if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
14085#endif /* ST_NOATIME */
14086#ifdef ST_NODIRATIME
14087 if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
14088#endif /* ST_NODIRATIME */
14089#ifdef ST_RELATIME
14090 if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
14091#endif /* ST_RELATIME */
14092
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014093 /* FreeBSD sendfile() constants */
14094#ifdef SF_NODISKIO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014095 if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014096#endif
14097#ifdef SF_MNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014098 if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014099#endif
14100#ifdef SF_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014101 if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014102#endif
14103
Ross Lagerwall7807c352011-03-17 20:20:30 +020014104 /* constants for posix_fadvise */
14105#ifdef POSIX_FADV_NORMAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014106 if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014107#endif
14108#ifdef POSIX_FADV_SEQUENTIAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014109 if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014110#endif
14111#ifdef POSIX_FADV_RANDOM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014112 if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014113#endif
14114#ifdef POSIX_FADV_NOREUSE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014115 if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014116#endif
14117#ifdef POSIX_FADV_WILLNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014118 if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014119#endif
14120#ifdef POSIX_FADV_DONTNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014121 if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014122#endif
14123
14124 /* constants for waitid */
14125#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014126 if (PyModule_AddIntMacro(m, P_PID)) return -1;
14127 if (PyModule_AddIntMacro(m, P_PGID)) return -1;
14128 if (PyModule_AddIntMacro(m, P_ALL)) return -1;
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080014129#ifdef P_PIDFD
14130 if (PyModule_AddIntMacro(m, P_PIDFD)) return -1;
14131#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014132#endif
14133#ifdef WEXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014134 if (PyModule_AddIntMacro(m, WEXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014135#endif
14136#ifdef WNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014137 if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014138#endif
14139#ifdef WSTOPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014140 if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014141#endif
14142#ifdef CLD_EXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014143 if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014144#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014145#ifdef CLD_KILLED
14146 if (PyModule_AddIntMacro(m, CLD_KILLED)) return -1;
14147#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014148#ifdef CLD_DUMPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014149 if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014150#endif
14151#ifdef CLD_TRAPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014152 if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014153#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014154#ifdef CLD_STOPPED
14155 if (PyModule_AddIntMacro(m, CLD_STOPPED)) return -1;
14156#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014157#ifdef CLD_CONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014158 if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014159#endif
14160
14161 /* constants for lockf */
14162#ifdef F_LOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014163 if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014164#endif
14165#ifdef F_TLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014166 if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014167#endif
14168#ifdef F_ULOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014169 if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014170#endif
14171#ifdef F_TEST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014172 if (PyModule_AddIntMacro(m, F_TEST)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014173#endif
14174
Pablo Galindo4defba32018-01-27 16:16:37 +000014175#ifdef RWF_DSYNC
14176 if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
14177#endif
14178#ifdef RWF_HIPRI
14179 if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
14180#endif
14181#ifdef RWF_SYNC
14182 if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
14183#endif
14184#ifdef RWF_NOWAIT
14185 if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
14186#endif
14187
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000014188/* constants for posix_spawn */
14189#ifdef HAVE_POSIX_SPAWN
14190 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
14191 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
14192 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
14193#endif
14194
pxinwrf2d7ac72019-05-21 18:46:37 +080014195#if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014196 if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
14197 if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014198 if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
pxinwrf2d7ac72019-05-21 18:46:37 +080014199#endif
14200#ifdef HAVE_SPAWNV
14201 if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014202 if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
Guido van Rossum246bc171999-02-01 23:54:31 +000014203#endif
14204
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014205#ifdef HAVE_SCHED_H
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014206#ifdef SCHED_OTHER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014207 if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014208#endif
14209#ifdef SCHED_FIFO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014210 if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014211#endif
14212#ifdef SCHED_RR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014213 if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014214#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014215#ifdef SCHED_SPORADIC
messi Liao0d322182017-06-13 22:30:43 +080014216 if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014217#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014218#ifdef SCHED_BATCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014219 if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014220#endif
14221#ifdef SCHED_IDLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014222 if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014223#endif
14224#ifdef SCHED_RESET_ON_FORK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014225 if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014226#endif
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014227#ifdef SCHED_SYS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014228 if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014229#endif
14230#ifdef SCHED_IA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014231 if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014232#endif
14233#ifdef SCHED_FSS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014234 if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014235#endif
14236#ifdef SCHED_FX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014237 if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014238#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014239#endif
14240
Benjamin Peterson9428d532011-09-14 11:45:52 -040014241#ifdef USE_XATTRS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014242 if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
14243 if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
14244 if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
Benjamin Peterson799bd802011-08-31 22:15:17 -040014245#endif
14246
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014247#if HAVE_DECL_RTLD_LAZY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014248 if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014249#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014250#if HAVE_DECL_RTLD_NOW
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014251 if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014252#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014253#if HAVE_DECL_RTLD_GLOBAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014254 if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014255#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014256#if HAVE_DECL_RTLD_LOCAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014257 if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014258#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014259#if HAVE_DECL_RTLD_NODELETE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014260 if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014261#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014262#if HAVE_DECL_RTLD_NOLOAD
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014263 if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014264#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014265#if HAVE_DECL_RTLD_DEEPBIND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014266 if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014267#endif
Michael Feltc5ae1692017-12-19 13:58:49 +010014268#if HAVE_DECL_RTLD_MEMBER
14269 if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
14270#endif
Victor Stinner8b905bd2011-10-25 13:34:04 +020014271
Victor Stinner9b1f4742016-09-06 16:18:52 -070014272#ifdef HAVE_GETRANDOM_SYSCALL
14273 if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
14274 if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
14275#endif
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014276#ifdef HAVE_MEMFD_CREATE
14277 if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
14278 if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
14279#ifdef MFD_HUGETLB
14280 if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014281#endif
14282#ifdef MFD_HUGE_SHIFT
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014283 if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014284#endif
14285#ifdef MFD_HUGE_MASK
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014286 if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014287#endif
14288#ifdef MFD_HUGE_64KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014289 if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014290#endif
14291#ifdef MFD_HUGE_512KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014292 if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014293#endif
14294#ifdef MFD_HUGE_1MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014295 if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014296#endif
14297#ifdef MFD_HUGE_2MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014298 if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014299#endif
14300#ifdef MFD_HUGE_8MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014301 if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014302#endif
14303#ifdef MFD_HUGE_16MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014304 if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014305#endif
14306#ifdef MFD_HUGE_32MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014307 if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014308#endif
14309#ifdef MFD_HUGE_256MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014310 if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014311#endif
14312#ifdef MFD_HUGE_512MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014313 if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014314#endif
14315#ifdef MFD_HUGE_1GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014316 if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014317#endif
14318#ifdef MFD_HUGE_2GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014319 if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014320#endif
14321#ifdef MFD_HUGE_16GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014322 if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
14323#endif
14324#endif
Victor Stinner9b1f4742016-09-06 16:18:52 -070014325
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020014326#if defined(__APPLE__)
14327 if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
14328#endif
14329
Steve Dower2438cdf2019-03-29 16:37:16 -070014330#ifdef MS_WINDOWS
14331 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
14332 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
14333 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
14334 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
14335 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
14336#endif
14337
Victor Stinner8c62be82010-05-06 00:08:46 +000014338 return 0;
Barry Warsaw4a342091996-12-19 23:50:02 +000014339}
14340
14341
Martin v. Löwis1a214512008-06-11 05:26:20 +000014342static struct PyModuleDef posixmodule = {
Victor Stinner8c62be82010-05-06 00:08:46 +000014343 PyModuleDef_HEAD_INIT,
14344 MODNAME,
14345 posix__doc__,
Eddie Elizondob3966632019-11-05 07:16:14 -080014346 sizeof(_posixstate),
Victor Stinner8c62be82010-05-06 00:08:46 +000014347 posix_methods,
14348 NULL,
Eddie Elizondob3966632019-11-05 07:16:14 -080014349 _posix_traverse,
14350 _posix_clear,
14351 _posix_free,
Martin v. Löwis1a214512008-06-11 05:26:20 +000014352};
14353
14354
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014355static const char * const have_functions[] = {
Larry Hastings9cf065c2012-06-22 16:30:09 -070014356
14357#ifdef HAVE_FACCESSAT
14358 "HAVE_FACCESSAT",
14359#endif
14360
14361#ifdef HAVE_FCHDIR
14362 "HAVE_FCHDIR",
14363#endif
14364
14365#ifdef HAVE_FCHMOD
14366 "HAVE_FCHMOD",
14367#endif
14368
14369#ifdef HAVE_FCHMODAT
14370 "HAVE_FCHMODAT",
14371#endif
14372
14373#ifdef HAVE_FCHOWN
14374 "HAVE_FCHOWN",
14375#endif
14376
Larry Hastings00964ed2013-08-12 13:49:30 -040014377#ifdef HAVE_FCHOWNAT
14378 "HAVE_FCHOWNAT",
14379#endif
14380
Larry Hastings9cf065c2012-06-22 16:30:09 -070014381#ifdef HAVE_FEXECVE
14382 "HAVE_FEXECVE",
14383#endif
14384
14385#ifdef HAVE_FDOPENDIR
14386 "HAVE_FDOPENDIR",
14387#endif
14388
Georg Brandl306336b2012-06-24 12:55:33 +020014389#ifdef HAVE_FPATHCONF
14390 "HAVE_FPATHCONF",
14391#endif
14392
Larry Hastings9cf065c2012-06-22 16:30:09 -070014393#ifdef HAVE_FSTATAT
14394 "HAVE_FSTATAT",
14395#endif
14396
14397#ifdef HAVE_FSTATVFS
14398 "HAVE_FSTATVFS",
14399#endif
14400
Steve Dowerfe0a41a2015-03-20 19:50:46 -070014401#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Georg Brandl306336b2012-06-24 12:55:33 +020014402 "HAVE_FTRUNCATE",
14403#endif
14404
Larry Hastings9cf065c2012-06-22 16:30:09 -070014405#ifdef HAVE_FUTIMENS
14406 "HAVE_FUTIMENS",
14407#endif
14408
14409#ifdef HAVE_FUTIMES
14410 "HAVE_FUTIMES",
14411#endif
14412
14413#ifdef HAVE_FUTIMESAT
14414 "HAVE_FUTIMESAT",
14415#endif
14416
14417#ifdef HAVE_LINKAT
14418 "HAVE_LINKAT",
14419#endif
14420
14421#ifdef HAVE_LCHFLAGS
14422 "HAVE_LCHFLAGS",
14423#endif
14424
14425#ifdef HAVE_LCHMOD
14426 "HAVE_LCHMOD",
14427#endif
14428
14429#ifdef HAVE_LCHOWN
14430 "HAVE_LCHOWN",
14431#endif
14432
14433#ifdef HAVE_LSTAT
14434 "HAVE_LSTAT",
14435#endif
14436
14437#ifdef HAVE_LUTIMES
14438 "HAVE_LUTIMES",
14439#endif
14440
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014441#ifdef HAVE_MEMFD_CREATE
14442 "HAVE_MEMFD_CREATE",
14443#endif
14444
Larry Hastings9cf065c2012-06-22 16:30:09 -070014445#ifdef HAVE_MKDIRAT
14446 "HAVE_MKDIRAT",
14447#endif
14448
14449#ifdef HAVE_MKFIFOAT
14450 "HAVE_MKFIFOAT",
14451#endif
14452
14453#ifdef HAVE_MKNODAT
14454 "HAVE_MKNODAT",
14455#endif
14456
14457#ifdef HAVE_OPENAT
14458 "HAVE_OPENAT",
14459#endif
14460
14461#ifdef HAVE_READLINKAT
14462 "HAVE_READLINKAT",
14463#endif
14464
14465#ifdef HAVE_RENAMEAT
14466 "HAVE_RENAMEAT",
14467#endif
14468
14469#ifdef HAVE_SYMLINKAT
14470 "HAVE_SYMLINKAT",
14471#endif
14472
14473#ifdef HAVE_UNLINKAT
14474 "HAVE_UNLINKAT",
14475#endif
14476
14477#ifdef HAVE_UTIMENSAT
14478 "HAVE_UTIMENSAT",
14479#endif
14480
14481#ifdef MS_WINDOWS
14482 "MS_WINDOWS",
14483#endif
14484
14485 NULL
14486};
14487
14488
Mark Hammondfe51c6d2002-08-02 02:27:13 +000014489PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +000014490INITFUNC(void)
Guido van Rossumb6775db1994-08-01 11:34:53 +000014491{
Victor Stinner8c62be82010-05-06 00:08:46 +000014492 PyObject *m, *v;
Larry Hastings9cf065c2012-06-22 16:30:09 -070014493 PyObject *list;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014494 const char * const *trace;
Tim Peters5aa91602002-01-30 05:46:57 +000014495
Eddie Elizondob3966632019-11-05 07:16:14 -080014496 m = PyState_FindModule(&posixmodule);
14497 if (m != NULL) {
14498 Py_INCREF(m);
14499 return m;
14500 }
14501
Victor Stinner8c62be82010-05-06 00:08:46 +000014502 m = PyModule_Create(&posixmodule);
14503 if (m == NULL)
14504 return NULL;
Tim Peters5aa91602002-01-30 05:46:57 +000014505
Victor Stinner8c62be82010-05-06 00:08:46 +000014506 /* Initialize environ dictionary */
14507 v = convertenviron();
14508 Py_XINCREF(v);
14509 if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
14510 return NULL;
14511 Py_DECREF(v);
Fred Drakec9680921999-12-13 16:37:25 +000014512
Victor Stinner8c62be82010-05-06 00:08:46 +000014513 if (all_ins(m))
14514 return NULL;
Barry Warsaw4a342091996-12-19 23:50:02 +000014515
Victor Stinner8c62be82010-05-06 00:08:46 +000014516 if (setup_confname_tables(m))
14517 return NULL;
Fred Drakebec628d1999-12-15 18:31:10 +000014518
Victor Stinner8c62be82010-05-06 00:08:46 +000014519 Py_INCREF(PyExc_OSError);
14520 PyModule_AddObject(m, "error", PyExc_OSError);
Fred Drake762e2061999-08-26 17:23:54 +000014521
Ross Lagerwall7807c352011-03-17 20:20:30 +020014522#if defined(HAVE_WAITID) && !defined(__APPLE__)
Eddie Elizondob3966632019-11-05 07:16:14 -080014523 waitid_result_desc.name = MODNAME ".waitid_result";
14524 PyObject *WaitidResultType = (PyObject *)PyStructSequence_NewType(&waitid_result_desc);
14525 if (WaitidResultType == NULL) {
14526 return NULL;
14527 }
14528 Py_INCREF(WaitidResultType);
14529 PyModule_AddObject(m, "waitid_result", WaitidResultType);
14530 _posixstate(m)->WaitidResultType = WaitidResultType;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014531#endif
14532
Eddie Elizondob3966632019-11-05 07:16:14 -080014533 stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
14534 stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
14535 stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
14536 stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
14537 PyObject *StatResultType = (PyObject *)PyStructSequence_NewType(&stat_result_desc);
14538 if (StatResultType == NULL) {
14539 return NULL;
14540 }
14541 Py_INCREF(StatResultType);
14542 PyModule_AddObject(m, "stat_result", StatResultType);
14543 _posixstate(m)->StatResultType = StatResultType;
14544 structseq_new = ((PyTypeObject *)StatResultType)->tp_new;
14545 ((PyTypeObject *)StatResultType)->tp_new = statresult_new;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014546
Eddie Elizondob3966632019-11-05 07:16:14 -080014547 statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
14548 PyObject *StatVFSResultType = (PyObject *)PyStructSequence_NewType(&statvfs_result_desc);
14549 if (StatVFSResultType == NULL) {
14550 return NULL;
14551 }
14552 Py_INCREF(StatVFSResultType);
14553 PyModule_AddObject(m, "statvfs_result", StatVFSResultType);
14554 _posixstate(m)->StatVFSResultType = StatVFSResultType;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014555#ifdef NEED_TICKS_PER_SECOND
14556# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Eddie Elizondob3966632019-11-05 07:16:14 -080014557 ticks_per_second = sysconf(_SC_CLK_TCK);
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014558# elif defined(HZ)
Eddie Elizondob3966632019-11-05 07:16:14 -080014559 ticks_per_second = HZ;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014560# else
Eddie Elizondob3966632019-11-05 07:16:14 -080014561 ticks_per_second = 60; /* magic fallback value; may be bogus */
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014562# endif
14563#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014564
William Orr81574b82018-10-01 22:19:56 -070014565#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Eddie Elizondob3966632019-11-05 07:16:14 -080014566 sched_param_desc.name = MODNAME ".sched_param";
14567 PyObject *SchedParamType = (PyObject *)PyStructSequence_NewType(&sched_param_desc);
14568 if (SchedParamType == NULL) {
14569 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000014570 }
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014571 Py_INCREF(SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -080014572 PyModule_AddObject(m, "sched_param", SchedParamType);
14573 _posixstate(m)->SchedParamType = SchedParamType;
14574 ((PyTypeObject *)SchedParamType)->tp_new = os_sched_param;
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014575#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +000014576
Eddie Elizondob3966632019-11-05 07:16:14 -080014577 /* initialize TerminalSize_info */
14578 PyObject *TerminalSizeType = (PyObject *)PyStructSequence_NewType(&TerminalSize_desc);
14579 if (TerminalSizeType == NULL) {
14580 return NULL;
14581 }
14582 Py_INCREF(TerminalSizeType);
14583 PyModule_AddObject(m, "terminal_size", TerminalSizeType);
14584 _posixstate(m)->TerminalSizeType = TerminalSizeType;
14585
14586 /* initialize scandir types */
14587 PyObject *ScandirIteratorType = PyType_FromSpec(&ScandirIteratorType_spec);
14588 if (ScandirIteratorType == NULL) {
14589 return NULL;
14590 }
14591 _posixstate(m)->ScandirIteratorType = ScandirIteratorType;
14592
14593 PyObject *DirEntryType = PyType_FromSpec(&DirEntryType_spec);
14594 if (DirEntryType == NULL) {
14595 return NULL;
14596 }
14597 Py_INCREF(DirEntryType);
14598 PyModule_AddObject(m, "DirEntry", DirEntryType);
14599 _posixstate(m)->DirEntryType = DirEntryType;
14600
Larry Hastings605a62d2012-06-24 04:33:36 -070014601 times_result_desc.name = MODNAME ".times_result";
Eddie Elizondob3966632019-11-05 07:16:14 -080014602 PyObject *TimesResultType = (PyObject *)PyStructSequence_NewType(&times_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014603 if (TimesResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014604 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014605 }
Eddie Elizondob3966632019-11-05 07:16:14 -080014606 Py_INCREF(TimesResultType);
14607 PyModule_AddObject(m, "times_result", TimesResultType);
14608 _posixstate(m)->TimesResultType = TimesResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070014609
Eddie Elizondob3966632019-11-05 07:16:14 -080014610 PyTypeObject *UnameResultType = PyStructSequence_NewType(&uname_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014611 if (UnameResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014612 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014613 }
Eddie Elizondob3966632019-11-05 07:16:14 -080014614 Py_INCREF(UnameResultType);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014615 PyModule_AddObject(m, "uname_result", (PyObject *)UnameResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -080014616 _posixstate(m)->UnameResultType = (PyObject *)UnameResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070014617
Thomas Wouters477c8d52006-05-27 19:21:47 +000014618#ifdef __APPLE__
Victor Stinner8c62be82010-05-06 00:08:46 +000014619 /*
14620 * Step 2 of weak-linking support on Mac OS X.
14621 *
14622 * The code below removes functions that are not available on the
14623 * currently active platform.
14624 *
14625 * This block allow one to use a python binary that was build on
Larry Hastings9cf065c2012-06-22 16:30:09 -070014626 * OSX 10.4 on OSX 10.3, without losing access to new APIs on
Victor Stinner8c62be82010-05-06 00:08:46 +000014627 * OSX 10.4.
14628 */
Thomas Wouters477c8d52006-05-27 19:21:47 +000014629#ifdef HAVE_FSTATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014630 if (fstatvfs == NULL) {
14631 if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
14632 return NULL;
14633 }
14634 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014635#endif /* HAVE_FSTATVFS */
14636
14637#ifdef HAVE_STATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014638 if (statvfs == NULL) {
14639 if (PyObject_DelAttrString(m, "statvfs") == -1) {
14640 return NULL;
14641 }
14642 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014643#endif /* HAVE_STATVFS */
14644
14645# ifdef HAVE_LCHOWN
Victor Stinner8c62be82010-05-06 00:08:46 +000014646 if (lchown == NULL) {
14647 if (PyObject_DelAttrString(m, "lchown") == -1) {
14648 return NULL;
14649 }
14650 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014651#endif /* HAVE_LCHOWN */
14652
14653
14654#endif /* __APPLE__ */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014655
Eddie Elizondob3966632019-11-05 07:16:14 -080014656 if ((_posixstate(m)->billion = PyLong_FromLong(1000000000)) == NULL)
14657 return NULL;
14658#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
14659 _posixstate(m)->struct_rusage = PyUnicode_InternFromString("struct_rusage");
14660 if (_posixstate(m)->struct_rusage == NULL)
14661 return NULL;
14662#endif
14663 _posixstate(m)->st_mode = PyUnicode_InternFromString("st_mode");
14664 if (_posixstate(m)->st_mode == NULL)
Larry Hastings6fe20b32012-04-19 15:07:49 -070014665 return NULL;
14666
Larry Hastings9cf065c2012-06-22 16:30:09 -070014667 /* suppress "function not used" warnings */
14668 {
14669 int ignored;
14670 fd_specified("", -1);
14671 follow_symlinks_specified("", 1);
14672 dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
14673 dir_fd_converter(Py_None, &ignored);
14674 dir_fd_unavailable(Py_None, &ignored);
14675 }
14676
14677 /*
14678 * provide list of locally available functions
14679 * so os.py can populate support_* lists
14680 */
14681 list = PyList_New(0);
14682 if (!list)
14683 return NULL;
14684 for (trace = have_functions; *trace; trace++) {
14685 PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
14686 if (!unicode)
14687 return NULL;
14688 if (PyList_Append(list, unicode))
14689 return NULL;
14690 Py_DECREF(unicode);
14691 }
14692 PyModule_AddObject(m, "_have_functions", list);
Ned Deilyeb3be662016-08-15 14:40:38 -040014693
Victor Stinner8c62be82010-05-06 00:08:46 +000014694 return m;
Guido van Rossumb6775db1994-08-01 11:34:53 +000014695}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014696
14697#ifdef __cplusplus
14698}
14699#endif