blob: 6a687529df0c085a055e5f9034d54b729f7bdb25 [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
Victor Stinnerb477d192020-01-22 22:48:16 +0100822/* Windows _wputenv() and setenv() copy the arguments and so don't require
823 the caller to manage the variable memory. Only Unix putenv() requires
824 putenv_dict. */
825#if defined(HAVE_PUTENV) && !defined(MS_WINDOWS) && !defined(HAVE_SETENV)
Victor Stinner623ed612020-01-21 19:25:32 +0100826# define PY_PUTENV_DICT
827#endif
828
Eddie Elizondob3966632019-11-05 07:16:14 -0800829typedef struct {
830 PyObject *billion;
Victor Stinner623ed612020-01-21 19:25:32 +0100831#ifdef PY_PUTENV_DICT
Victor Stinnerb477d192020-01-22 22:48:16 +0100832 /* putenv() requires that the caller manages the environment variable
833 memory. Use a Python dictionary for that: name => env, where env is a
834 string like "name=value". On Windows, dict keys and values are Unicode
835 strings. On Unix, they are bytes strings. */
Victor Stinner623ed612020-01-21 19:25:32 +0100836 PyObject *putenv_dict;
837#endif
Eddie Elizondob3966632019-11-05 07:16:14 -0800838 PyObject *DirEntryType;
839 PyObject *ScandirIteratorType;
840#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
841 PyObject *SchedParamType;
842#endif
843 PyObject *StatResultType;
844 PyObject *StatVFSResultType;
845 PyObject *TerminalSizeType;
846 PyObject *TimesResultType;
847 PyObject *UnameResultType;
848#if defined(HAVE_WAITID) && !defined(__APPLE__)
849 PyObject *WaitidResultType;
850#endif
851#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
852 PyObject *struct_rusage;
853#endif
854 PyObject *st_mode;
855} _posixstate;
856
857static struct PyModuleDef posixmodule;
858
859#define _posixstate(o) ((_posixstate *)PyModule_GetState(o))
860#define _posixstate_global ((_posixstate *)PyModule_GetState(PyState_FindModule(&posixmodule)))
Larry Hastings9cf065c2012-06-22 16:30:09 -0700861
Larry Hastings9cf065c2012-06-22 16:30:09 -0700862/*
863 * A PyArg_ParseTuple "converter" function
864 * that handles filesystem paths in the manner
865 * preferred by the os module.
866 *
867 * path_converter accepts (Unicode) strings and their
868 * subclasses, and bytes and their subclasses. What
869 * it does with the argument depends on the platform:
870 *
871 * * On Windows, if we get a (Unicode) string we
872 * extract the wchar_t * and return it; if we get
Steve Dowercc16be82016-09-08 10:35:16 -0700873 * bytes we decode to wchar_t * and return that.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700874 *
875 * * On all other platforms, strings are encoded
876 * to bytes using PyUnicode_FSConverter, then we
877 * extract the char * from the bytes object and
878 * return that.
879 *
880 * path_converter also optionally accepts signed
881 * integers (representing open file descriptors) instead
882 * of path strings.
883 *
884 * Input fields:
885 * path.nullable
886 * If nonzero, the path is permitted to be None.
887 * path.allow_fd
888 * If nonzero, the path is permitted to be a file handle
889 * (a signed int) instead of a string.
890 * path.function_name
891 * If non-NULL, path_converter will use that as the name
892 * of the function in error messages.
Larry Hastings31826802013-10-19 00:09:25 -0700893 * (If path.function_name is NULL it omits the function name.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700894 * path.argument_name
895 * If non-NULL, path_converter will use that as the name
896 * of the parameter in error messages.
897 * (If path.argument_name is NULL it uses "path".)
898 *
899 * Output fields:
900 * path.wide
901 * Points to the path if it was expressed as Unicode
902 * and was not encoded. (Only used on Windows.)
903 * path.narrow
904 * Points to the path if it was expressed as bytes,
Steve Dowercc16be82016-09-08 10:35:16 -0700905 * or it was Unicode and was encoded to bytes. (On Windows,
Martin Panterb1321fb2016-10-10 00:38:21 +0000906 * is a non-zero integer if the path was expressed as bytes.
Steve Dowercc16be82016-09-08 10:35:16 -0700907 * The type is deliberately incompatible to prevent misuse.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700908 * path.fd
909 * Contains a file descriptor if path.accept_fd was true
910 * and the caller provided a signed integer instead of any
911 * sort of string.
912 *
913 * WARNING: if your "path" parameter is optional, and is
914 * unspecified, path_converter will never get called.
915 * So if you set allow_fd, you *MUST* initialize path.fd = -1
916 * yourself!
917 * path.length
918 * The length of the path in characters, if specified as
919 * a string.
920 * path.object
Xiang Zhang04316c42017-01-08 23:26:57 +0800921 * The original object passed in (if get a PathLike object,
922 * the result of PyOS_FSPath() is treated as the original object).
923 * Own a reference to the object.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700924 * path.cleanup
925 * For internal use only. May point to a temporary object.
926 * (Pay no attention to the man behind the curtain.)
927 *
928 * At most one of path.wide or path.narrow will be non-NULL.
929 * If path was None and path.nullable was set,
930 * or if path was an integer and path.allow_fd was set,
931 * both path.wide and path.narrow will be NULL
932 * and path.length will be 0.
Georg Brandlf7875592012-06-24 13:58:31 +0200933 *
Larry Hastings9cf065c2012-06-22 16:30:09 -0700934 * path_converter takes care to not write to the path_t
935 * unless it's successful. However it must reset the
936 * "cleanup" field each time it's called.
937 *
938 * Use as follows:
939 * path_t path;
940 * memset(&path, 0, sizeof(path));
941 * PyArg_ParseTuple(args, "O&", path_converter, &path);
942 * // ... use values from path ...
943 * path_cleanup(&path);
944 *
945 * (Note that if PyArg_Parse fails you don't need to call
946 * path_cleanup(). However it is safe to do so.)
947 */
948typedef struct {
Victor Stinner292c8352012-10-30 02:17:38 +0100949 const char *function_name;
950 const char *argument_name;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700951 int nullable;
952 int allow_fd;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300953 const wchar_t *wide;
Steve Dowercc16be82016-09-08 10:35:16 -0700954#ifdef MS_WINDOWS
955 BOOL narrow;
956#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300957 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700958#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700959 int fd;
960 Py_ssize_t length;
961 PyObject *object;
962 PyObject *cleanup;
963} path_t;
964
Steve Dowercc16be82016-09-08 10:35:16 -0700965#ifdef MS_WINDOWS
966#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
967 {function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
968#else
Larry Hastings2f936352014-08-05 14:04:04 +1000969#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
970 {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
Steve Dowercc16be82016-09-08 10:35:16 -0700971#endif
Larry Hastings31826802013-10-19 00:09:25 -0700972
Larry Hastings9cf065c2012-06-22 16:30:09 -0700973static void
Xiang Zhang04316c42017-01-08 23:26:57 +0800974path_cleanup(path_t *path)
975{
976 Py_CLEAR(path->object);
977 Py_CLEAR(path->cleanup);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700978}
979
980static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300981path_converter(PyObject *o, void *p)
982{
Larry Hastings9cf065c2012-06-22 16:30:09 -0700983 path_t *path = (path_t *)p;
Xiang Zhang04316c42017-01-08 23:26:57 +0800984 PyObject *bytes = NULL;
985 Py_ssize_t length = 0;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700986 int is_index, is_buffer, is_bytes, is_unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300987 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700988#ifdef MS_WINDOWS
Xiang Zhang04316c42017-01-08 23:26:57 +0800989 PyObject *wo = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700990 const wchar_t *wide;
991#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700992
993#define FORMAT_EXCEPTION(exc, fmt) \
994 PyErr_Format(exc, "%s%s" fmt, \
995 path->function_name ? path->function_name : "", \
996 path->function_name ? ": " : "", \
997 path->argument_name ? path->argument_name : "path")
998
999 /* Py_CLEANUP_SUPPORTED support */
1000 if (o == NULL) {
1001 path_cleanup(path);
1002 return 1;
1003 }
1004
Brett Cannon3f9183b2016-08-26 14:44:48 -07001005 /* Ensure it's always safe to call path_cleanup(). */
Xiang Zhang04316c42017-01-08 23:26:57 +08001006 path->object = path->cleanup = NULL;
1007 /* path->object owns a reference to the original object */
1008 Py_INCREF(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001009
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001010 if ((o == Py_None) && path->nullable) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001011 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001012#ifdef MS_WINDOWS
1013 path->narrow = FALSE;
1014#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001015 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001016#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07001017 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001018 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001019 }
1020
Brett Cannon3f9183b2016-08-26 14:44:48 -07001021 /* Only call this here so that we don't treat the return value of
1022 os.fspath() as an fd or buffer. */
1023 is_index = path->allow_fd && PyIndex_Check(o);
1024 is_buffer = PyObject_CheckBuffer(o);
1025 is_bytes = PyBytes_Check(o);
1026 is_unicode = PyUnicode_Check(o);
1027
1028 if (!is_index && !is_buffer && !is_unicode && !is_bytes) {
1029 /* Inline PyOS_FSPath() for better error messages. */
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001030 PyObject *func, *res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001031
1032 func = _PyObject_LookupSpecial(o, &PyId___fspath__);
1033 if (NULL == func) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001034 goto error_format;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001035 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001036 res = _PyObject_CallNoArg(func);
Brett Cannon3f9183b2016-08-26 14:44:48 -07001037 Py_DECREF(func);
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001038 if (NULL == res) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001039 goto error_exit;
1040 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001041 else if (PyUnicode_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001042 is_unicode = 1;
1043 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001044 else if (PyBytes_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001045 is_bytes = 1;
1046 }
1047 else {
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001048 PyErr_Format(PyExc_TypeError,
1049 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -08001050 "not %.200s", _PyType_Name(Py_TYPE(o)),
1051 _PyType_Name(Py_TYPE(res)));
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001052 Py_DECREF(res);
1053 goto error_exit;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001054 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001055
1056 /* still owns a reference to the original object */
1057 Py_DECREF(o);
1058 o = res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001059 }
1060
1061 if (is_unicode) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001062#ifdef MS_WINDOWS
Victor Stinner26c03bd2016-09-19 11:55:44 +02001063 wide = PyUnicode_AsUnicodeAndSize(o, &length);
Victor Stinner59799a82013-11-13 14:17:30 +01001064 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001065 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001066 }
Victor Stinner59799a82013-11-13 14:17:30 +01001067 if (length > 32767) {
1068 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001069 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001070 }
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001071 if (wcslen(wide) != length) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001072 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001073 goto error_exit;
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001074 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001075
1076 path->wide = wide;
Xiang Zhang04316c42017-01-08 23:26:57 +08001077 path->narrow = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001078 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001079 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001080#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001081 if (!PyUnicode_FSConverter(o, &bytes)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001082 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001083 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001084#endif
1085 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001086 else if (is_bytes) {
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001087 bytes = o;
1088 Py_INCREF(bytes);
1089 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001090 else if (is_buffer) {
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03001091 /* XXX Replace PyObject_CheckBuffer with PyBytes_Check in other code
Ville Skyttä49b27342017-08-03 09:00:59 +03001092 after removing support of non-bytes buffer objects. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001093 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1094 "%s%s%s should be %s, not %.200s",
1095 path->function_name ? path->function_name : "",
1096 path->function_name ? ": " : "",
1097 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001098 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1099 "integer or None" :
1100 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1101 path->nullable ? "string, bytes, os.PathLike or None" :
1102 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001103 _PyType_Name(Py_TYPE(o)))) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001104 goto error_exit;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001105 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001106 bytes = PyBytes_FromObject(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001107 if (!bytes) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001108 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001109 }
1110 }
Steve Dowercc16be82016-09-08 10:35:16 -07001111 else if (is_index) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001112 if (!_fd_converter(o, &path->fd)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001113 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001114 }
1115 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001116#ifdef MS_WINDOWS
1117 path->narrow = FALSE;
1118#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001119 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001120#endif
Xiang Zhang04316c42017-01-08 23:26:57 +08001121 goto success_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001122 }
1123 else {
Xiang Zhang04316c42017-01-08 23:26:57 +08001124 error_format:
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001125 PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
1126 path->function_name ? path->function_name : "",
1127 path->function_name ? ": " : "",
1128 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001129 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1130 "integer or None" :
1131 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1132 path->nullable ? "string, bytes, os.PathLike or None" :
1133 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001134 _PyType_Name(Py_TYPE(o)));
Xiang Zhang04316c42017-01-08 23:26:57 +08001135 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001136 }
1137
Larry Hastings9cf065c2012-06-22 16:30:09 -07001138 length = PyBytes_GET_SIZE(bytes);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001139 narrow = PyBytes_AS_STRING(bytes);
Victor Stinner706768c2014-08-16 01:03:39 +02001140 if ((size_t)length != strlen(narrow)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03001141 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001142 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001143 }
1144
Steve Dowercc16be82016-09-08 10:35:16 -07001145#ifdef MS_WINDOWS
1146 wo = PyUnicode_DecodeFSDefaultAndSize(
1147 narrow,
1148 length
1149 );
1150 if (!wo) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001151 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001152 }
1153
Xiang Zhang04316c42017-01-08 23:26:57 +08001154 wide = PyUnicode_AsUnicodeAndSize(wo, &length);
Steve Dowercc16be82016-09-08 10:35:16 -07001155 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001156 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001157 }
1158 if (length > 32767) {
1159 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001160 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001161 }
1162 if (wcslen(wide) != length) {
1163 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001164 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001165 }
1166 path->wide = wide;
1167 path->narrow = TRUE;
Xiang Zhang04316c42017-01-08 23:26:57 +08001168 path->cleanup = wo;
1169 Py_DECREF(bytes);
Steve Dowercc16be82016-09-08 10:35:16 -07001170#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001171 path->wide = NULL;
1172 path->narrow = narrow;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001173 if (bytes == o) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001174 /* Still a reference owned by path->object, don't have to
1175 worry about path->narrow is used after free. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001176 Py_DECREF(bytes);
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001177 }
1178 else {
1179 path->cleanup = bytes;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001180 }
Xiang Zhang04316c42017-01-08 23:26:57 +08001181#endif
1182 path->fd = -1;
1183
1184 success_exit:
1185 path->length = length;
1186 path->object = o;
1187 return Py_CLEANUP_SUPPORTED;
1188
1189 error_exit:
1190 Py_XDECREF(o);
1191 Py_XDECREF(bytes);
1192#ifdef MS_WINDOWS
1193 Py_XDECREF(wo);
1194#endif
1195 return 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001196}
1197
1198static void
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001199argument_unavailable_error(const char *function_name, const char *argument_name)
1200{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001201 PyErr_Format(PyExc_NotImplementedError,
1202 "%s%s%s unavailable on this platform",
1203 (function_name != NULL) ? function_name : "",
1204 (function_name != NULL) ? ": ": "",
1205 argument_name);
1206}
1207
1208static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001209dir_fd_unavailable(PyObject *o, void *p)
1210{
1211 int dir_fd;
1212 if (!dir_fd_converter(o, &dir_fd))
Larry Hastings9cf065c2012-06-22 16:30:09 -07001213 return 0;
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001214 if (dir_fd != DEFAULT_DIR_FD) {
1215 argument_unavailable_error(NULL, "dir_fd");
1216 return 0;
1217 }
1218 *(int *)p = dir_fd;
1219 return 1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001220}
1221
1222static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001223fd_specified(const char *function_name, int fd)
1224{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001225 if (fd == -1)
1226 return 0;
1227
1228 argument_unavailable_error(function_name, "fd");
1229 return 1;
1230}
1231
1232static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001233follow_symlinks_specified(const char *function_name, int follow_symlinks)
1234{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001235 if (follow_symlinks)
1236 return 0;
1237
1238 argument_unavailable_error(function_name, "follow_symlinks");
1239 return 1;
1240}
1241
1242static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001243path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
1244{
Steve Dowercc16be82016-09-08 10:35:16 -07001245 if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
1246#ifndef MS_WINDOWS
1247 && !path->narrow
1248#endif
1249 ) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001250 PyErr_Format(PyExc_ValueError,
1251 "%s: can't specify dir_fd without matching path",
1252 function_name);
1253 return 1;
1254 }
1255 return 0;
1256}
1257
1258static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001259dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
1260{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001261 if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
1262 PyErr_Format(PyExc_ValueError,
1263 "%s: can't specify both dir_fd and fd",
1264 function_name);
1265 return 1;
1266 }
1267 return 0;
1268}
1269
1270static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001271fd_and_follow_symlinks_invalid(const char *function_name, int fd,
1272 int follow_symlinks)
1273{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001274 if ((fd > 0) && (!follow_symlinks)) {
1275 PyErr_Format(PyExc_ValueError,
1276 "%s: cannot use fd and follow_symlinks together",
1277 function_name);
1278 return 1;
1279 }
1280 return 0;
1281}
1282
1283static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001284dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
1285 int follow_symlinks)
1286{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001287 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
1288 PyErr_Format(PyExc_ValueError,
1289 "%s: cannot use dir_fd and follow_symlinks together",
1290 function_name);
1291 return 1;
1292 }
1293 return 0;
1294}
1295
Larry Hastings2f936352014-08-05 14:04:04 +10001296#ifdef MS_WINDOWS
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001297 typedef long long Py_off_t;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001298#else
Larry Hastings2f936352014-08-05 14:04:04 +10001299 typedef off_t Py_off_t;
1300#endif
1301
1302static int
1303Py_off_t_converter(PyObject *arg, void *addr)
1304{
1305#ifdef HAVE_LARGEFILE_SUPPORT
1306 *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
1307#else
1308 *((Py_off_t *)addr) = PyLong_AsLong(arg);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001309#endif
1310 if (PyErr_Occurred())
1311 return 0;
1312 return 1;
1313}
Larry Hastings2f936352014-08-05 14:04:04 +10001314
1315static PyObject *
1316PyLong_FromPy_off_t(Py_off_t offset)
1317{
1318#ifdef HAVE_LARGEFILE_SUPPORT
1319 return PyLong_FromLongLong(offset);
1320#else
1321 return PyLong_FromLong(offset);
Ross Lagerwallb1e5d592011-09-19 08:30:43 +02001322#endif
Larry Hastings2f936352014-08-05 14:04:04 +10001323}
1324
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001325#ifdef HAVE_SIGSET_T
1326/* Convert an iterable of integers to a sigset.
1327 Return 1 on success, return 0 and raise an exception on error. */
1328int
1329_Py_Sigset_Converter(PyObject *obj, void *addr)
1330{
1331 sigset_t *mask = (sigset_t *)addr;
1332 PyObject *iterator, *item;
1333 long signum;
1334 int overflow;
1335
Rémi Lapeyref0900192019-05-04 01:30:53 +02001336 // The extra parens suppress the unreachable-code warning with clang on MacOS
1337 if (sigemptyset(mask) < (0)) {
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001338 /* Probably only if mask == NULL. */
1339 PyErr_SetFromErrno(PyExc_OSError);
1340 return 0;
1341 }
1342
1343 iterator = PyObject_GetIter(obj);
1344 if (iterator == NULL) {
1345 return 0;
1346 }
1347
1348 while ((item = PyIter_Next(iterator)) != NULL) {
1349 signum = PyLong_AsLongAndOverflow(item, &overflow);
1350 Py_DECREF(item);
1351 if (signum <= 0 || signum >= NSIG) {
1352 if (overflow || signum != -1 || !PyErr_Occurred()) {
1353 PyErr_Format(PyExc_ValueError,
1354 "signal number %ld out of range", signum);
1355 }
1356 goto error;
1357 }
1358 if (sigaddset(mask, (int)signum)) {
1359 if (errno != EINVAL) {
1360 /* Probably impossible */
1361 PyErr_SetFromErrno(PyExc_OSError);
1362 goto error;
1363 }
1364 /* For backwards compatibility, allow idioms such as
1365 * `range(1, NSIG)` but warn about invalid signal numbers
1366 */
1367 const char msg[] =
1368 "invalid signal number %ld, please use valid_signals()";
1369 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
1370 goto error;
1371 }
1372 }
1373 }
1374 if (!PyErr_Occurred()) {
1375 Py_DECREF(iterator);
1376 return 1;
1377 }
1378
1379error:
1380 Py_DECREF(iterator);
1381 return 0;
1382}
1383#endif /* HAVE_SIGSET_T */
1384
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001385#ifdef MS_WINDOWS
Brian Curtinf5e76d02010-11-24 13:14:05 +00001386
1387static int
Brian Curtind25aef52011-06-13 15:16:04 -05001388win32_get_reparse_tag(HANDLE reparse_point_handle, ULONG *reparse_tag)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001389{
Martin Panter70214ad2016-08-04 02:38:59 +00001390 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1391 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001392 DWORD n_bytes_returned;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001393
1394 if (0 == DeviceIoControl(
1395 reparse_point_handle,
1396 FSCTL_GET_REPARSE_POINT,
1397 NULL, 0, /* in buffer */
1398 target_buffer, sizeof(target_buffer),
1399 &n_bytes_returned,
1400 NULL)) /* we're not using OVERLAPPED_IO */
Brian Curtind25aef52011-06-13 15:16:04 -05001401 return FALSE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001402
1403 if (reparse_tag)
1404 *reparse_tag = rdb->ReparseTag;
1405
Brian Curtind25aef52011-06-13 15:16:04 -05001406 return TRUE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001407}
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001408
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001409#endif /* MS_WINDOWS */
Brian Curtinf5e76d02010-11-24 13:14:05 +00001410
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001411/* Return a dictionary corresponding to the POSIX environment table */
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001412#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Jack Jansenea0c3822002-08-01 21:57:49 +00001413/* On Darwin/MacOSX a shared library or framework has no access to
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001414** environ directly, we must obtain it with _NSGetEnviron(). See also
1415** man environ(7).
Jack Jansenea0c3822002-08-01 21:57:49 +00001416*/
1417#include <crt_externs.h>
pxinwrf2d7ac72019-05-21 18:46:37 +08001418#elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001419extern char **environ;
Guido van Rossuma4916fa1996-05-23 22:58:55 +00001420#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001421
Barry Warsaw53699e91996-12-10 23:23:01 +00001422static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001423convertenviron(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001424{
Victor Stinner8c62be82010-05-06 00:08:46 +00001425 PyObject *d;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001426#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00001427 wchar_t **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001428#else
Victor Stinner8c62be82010-05-06 00:08:46 +00001429 char **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001430#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +00001431
Victor Stinner8c62be82010-05-06 00:08:46 +00001432 d = PyDict_New();
1433 if (d == NULL)
1434 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001435#ifdef MS_WINDOWS
1436 /* _wenviron must be initialized in this way if the program is started
1437 through main() instead of wmain(). */
1438 _wgetenv(L"");
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001439 e = _wenviron;
Benoit Hudson723f71a2019-12-06 14:15:03 -05001440#elif defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
1441 /* environ is not accessible as an extern in a shared object on OSX; use
1442 _NSGetEnviron to resolve it. The value changes if you add environment
1443 variables between calls to Py_Initialize, so don't cache the value. */
1444 e = *_NSGetEnviron();
Victor Stinner8c62be82010-05-06 00:08:46 +00001445#else
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001446 e = environ;
1447#endif
1448 if (e == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +00001449 return d;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001450 for (; *e != NULL; e++) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001451 PyObject *k;
1452 PyObject *v;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001453#ifdef MS_WINDOWS
1454 const wchar_t *p = wcschr(*e, L'=');
1455#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03001456 const char *p = strchr(*e, '=');
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001457#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001458 if (p == NULL)
1459 continue;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001460#ifdef MS_WINDOWS
1461 k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
1462#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001463 k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001464#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001465 if (k == NULL) {
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001466 Py_DECREF(d);
1467 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001468 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001469#ifdef MS_WINDOWS
1470 v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
1471#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001472 v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001473#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001474 if (v == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001475 Py_DECREF(k);
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001476 Py_DECREF(d);
1477 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001478 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001479 if (PyDict_GetItemWithError(d, k) == NULL) {
1480 if (PyErr_Occurred() || PyDict_SetItem(d, k, v) != 0) {
1481 Py_DECREF(v);
1482 Py_DECREF(k);
1483 Py_DECREF(d);
1484 return NULL;
1485 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001486 }
1487 Py_DECREF(k);
1488 Py_DECREF(v);
Guido van Rossumd48f2521997-12-05 22:19:34 +00001489 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001490 return d;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001491}
1492
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001493/* Set a POSIX-specific error from errno, and return NULL */
1494
Barry Warsawd58d7641998-07-23 16:14:40 +00001495static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001496posix_error(void)
Guido van Rossumad0ee831995-03-01 10:34:45 +00001497{
Victor Stinner8c62be82010-05-06 00:08:46 +00001498 return PyErr_SetFromErrno(PyExc_OSError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001499}
Mark Hammondef8b6542001-05-13 08:04:26 +00001500
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001501#ifdef MS_WINDOWS
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001502static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001503win32_error(const char* function, const char* filename)
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001504{
Victor Stinner8c62be82010-05-06 00:08:46 +00001505 /* XXX We should pass the function name along in the future.
1506 (winreg.c also wants to pass the function name.)
1507 This would however require an additional param to the
1508 Windows error object, which is non-trivial.
1509 */
1510 errno = GetLastError();
1511 if (filename)
1512 return PyErr_SetFromWindowsErrWithFilename(errno, filename);
1513 else
1514 return PyErr_SetFromWindowsErr(errno);
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001515}
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001516
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001517static PyObject *
Steve Dower2438cdf2019-03-29 16:37:16 -07001518win32_error_object_err(const char* function, PyObject* filename, DWORD err)
Victor Stinnereb5657a2011-09-30 01:44:27 +02001519{
1520 /* XXX - see win32_error for comments on 'function' */
Victor Stinnereb5657a2011-09-30 01:44:27 +02001521 if (filename)
1522 return PyErr_SetExcFromWindowsErrWithFilenameObject(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001523 PyExc_OSError,
Steve Dower2438cdf2019-03-29 16:37:16 -07001524 err,
Victor Stinnereb5657a2011-09-30 01:44:27 +02001525 filename);
1526 else
Steve Dower2438cdf2019-03-29 16:37:16 -07001527 return PyErr_SetFromWindowsErr(err);
1528}
1529
1530static PyObject *
1531win32_error_object(const char* function, PyObject* filename)
1532{
1533 errno = GetLastError();
1534 return win32_error_object_err(function, filename, errno);
Victor Stinnereb5657a2011-09-30 01:44:27 +02001535}
1536
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001537#endif /* MS_WINDOWS */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001538
Larry Hastings9cf065c2012-06-22 16:30:09 -07001539static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001540posix_path_object_error(PyObject *path)
1541{
1542 return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
1543}
1544
1545static PyObject *
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001546path_object_error(PyObject *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001547{
1548#ifdef MS_WINDOWS
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001549 return PyErr_SetExcFromWindowsErrWithFilenameObject(
1550 PyExc_OSError, 0, path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001551#else
Alexey Izbyshev83460312018-10-20 03:28:22 +03001552 return posix_path_object_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001553#endif
1554}
1555
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001556static PyObject *
1557path_object_error2(PyObject *path, PyObject *path2)
1558{
1559#ifdef MS_WINDOWS
1560 return PyErr_SetExcFromWindowsErrWithFilenameObjects(
1561 PyExc_OSError, 0, path, path2);
1562#else
1563 return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
1564#endif
1565}
1566
1567static PyObject *
1568path_error(path_t *path)
1569{
1570 return path_object_error(path->object);
1571}
Larry Hastings31826802013-10-19 00:09:25 -07001572
Larry Hastingsb0827312014-02-09 22:05:19 -08001573static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001574posix_path_error(path_t *path)
1575{
1576 return posix_path_object_error(path->object);
1577}
1578
1579static PyObject *
Larry Hastingsb0827312014-02-09 22:05:19 -08001580path_error2(path_t *path, path_t *path2)
1581{
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001582 return path_object_error2(path->object, path2->object);
Larry Hastingsb0827312014-02-09 22:05:19 -08001583}
1584
1585
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001586/* POSIX generic methods */
1587
Larry Hastings2f936352014-08-05 14:04:04 +10001588static int
1589fildes_converter(PyObject *o, void *p)
Fred Drake4d1e64b2002-04-15 19:40:07 +00001590{
Victor Stinner8c62be82010-05-06 00:08:46 +00001591 int fd;
Larry Hastings2f936352014-08-05 14:04:04 +10001592 int *pointer = (int *)p;
1593 fd = PyObject_AsFileDescriptor(o);
Victor Stinner8c62be82010-05-06 00:08:46 +00001594 if (fd < 0)
Larry Hastings2f936352014-08-05 14:04:04 +10001595 return 0;
Larry Hastings2f936352014-08-05 14:04:04 +10001596 *pointer = fd;
1597 return 1;
1598}
1599
1600static PyObject *
1601posix_fildes_fd(int fd, int (*func)(int))
1602{
1603 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001604 int async_err = 0;
1605
1606 do {
1607 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001608 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001609 res = (*func)(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001610 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001611 Py_END_ALLOW_THREADS
1612 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1613 if (res != 0)
1614 return (!async_err) ? posix_error() : NULL;
1615 Py_RETURN_NONE;
Fred Drake4d1e64b2002-04-15 19:40:07 +00001616}
Guido van Rossum21142a01999-01-08 21:05:37 +00001617
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001618
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001619#ifdef MS_WINDOWS
Thomas Wouters477c8d52006-05-27 19:21:47 +00001620/* This is a reimplementation of the C library's chdir function,
1621 but one that produces Win32 errors instead of DOS error codes.
1622 chdir is essentially a wrapper around SetCurrentDirectory; however,
1623 it also needs to set "magic" environment variables indicating
1624 the per-drive current directory, which are of the form =<drive>: */
Benjamin Peterson206e3072008-10-19 14:07:49 +00001625static BOOL __stdcall
Thomas Wouters477c8d52006-05-27 19:21:47 +00001626win32_wchdir(LPCWSTR path)
1627{
Victor Stinnered537822015-12-13 21:40:26 +01001628 wchar_t path_buf[MAX_PATH], *new_path = path_buf;
Victor Stinner8c62be82010-05-06 00:08:46 +00001629 int result;
1630 wchar_t env[4] = L"=x:";
Thomas Wouters477c8d52006-05-27 19:21:47 +00001631
Victor Stinner8c62be82010-05-06 00:08:46 +00001632 if(!SetCurrentDirectoryW(path))
1633 return FALSE;
Victor Stinnered537822015-12-13 21:40:26 +01001634 result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001635 if (!result)
1636 return FALSE;
Victor Stinnere847d712015-12-14 00:21:50 +01001637 if (result > Py_ARRAY_LENGTH(path_buf)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001638 new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00001639 if (!new_path) {
1640 SetLastError(ERROR_OUTOFMEMORY);
1641 return FALSE;
1642 }
1643 result = GetCurrentDirectoryW(result, new_path);
1644 if (!result) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001645 PyMem_RawFree(new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001646 return FALSE;
1647 }
1648 }
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001649 int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
1650 wcsncmp(new_path, L"//", 2) == 0);
1651 if (!is_unc_like_path) {
1652 env[1] = new_path[0];
1653 result = SetEnvironmentVariableW(env, new_path);
1654 }
Victor Stinnered537822015-12-13 21:40:26 +01001655 if (new_path != path_buf)
Victor Stinnerb6404912013-07-07 16:21:41 +02001656 PyMem_RawFree(new_path);
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001657 return result ? TRUE : FALSE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001658}
1659#endif
1660
Martin v. Löwis14694662006-02-03 12:54:16 +00001661#ifdef MS_WINDOWS
1662/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
1663 - time stamps are restricted to second resolution
1664 - file modification times suffer from forth-and-back conversions between
1665 UTC and local time
1666 Therefore, we implement our own stat, based on the Win32 API directly.
1667*/
Victor Stinner8c62be82010-05-06 00:08:46 +00001668#define HAVE_STAT_NSEC 1
Zachary Ware63f277b2014-06-19 09:46:37 -05001669#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001670#define HAVE_STRUCT_STAT_ST_REPARSE_TAG 1
Martin v. Löwis14694662006-02-03 12:54:16 +00001671
Victor Stinner6036e442015-03-08 01:58:04 +01001672static void
Steve Dowercc16be82016-09-08 10:35:16 -07001673find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
1674 BY_HANDLE_FILE_INFORMATION *info,
1675 ULONG *reparse_tag)
Victor Stinner6036e442015-03-08 01:58:04 +01001676{
1677 memset(info, 0, sizeof(*info));
1678 info->dwFileAttributes = pFileData->dwFileAttributes;
1679 info->ftCreationTime = pFileData->ftCreationTime;
1680 info->ftLastAccessTime = pFileData->ftLastAccessTime;
1681 info->ftLastWriteTime = pFileData->ftLastWriteTime;
1682 info->nFileSizeHigh = pFileData->nFileSizeHigh;
1683 info->nFileSizeLow = pFileData->nFileSizeLow;
1684/* info->nNumberOfLinks = 1; */
1685 if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
1686 *reparse_tag = pFileData->dwReserved0;
1687 else
1688 *reparse_tag = 0;
1689}
1690
Guido van Rossumd8faa362007-04-27 19:54:29 +00001691static BOOL
Steve Dowercc16be82016-09-08 10:35:16 -07001692attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001693{
Victor Stinner8c62be82010-05-06 00:08:46 +00001694 HANDLE hFindFile;
1695 WIN32_FIND_DATAW FileData;
1696 hFindFile = FindFirstFileW(pszFile, &FileData);
1697 if (hFindFile == INVALID_HANDLE_VALUE)
1698 return FALSE;
1699 FindClose(hFindFile);
Steve Dowercc16be82016-09-08 10:35:16 -07001700 find_data_to_file_info(&FileData, info, reparse_tag);
Victor Stinner8c62be82010-05-06 00:08:46 +00001701 return TRUE;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001702}
1703
Brian Curtind25aef52011-06-13 15:16:04 -05001704static int
Steve Dowercc16be82016-09-08 10:35:16 -07001705win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
Brian Curtind25aef52011-06-13 15:16:04 -05001706 BOOL traverse)
1707{
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001708 HANDLE hFile;
1709 BY_HANDLE_FILE_INFORMATION fileInfo;
1710 FILE_ATTRIBUTE_TAG_INFO tagInfo = { 0 };
1711 DWORD fileType, error;
1712 BOOL isUnhandledTag = FALSE;
1713 int retval = 0;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001714
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001715 DWORD access = FILE_READ_ATTRIBUTES;
1716 DWORD flags = FILE_FLAG_BACKUP_SEMANTICS; /* Allow opening directories. */
1717 if (!traverse) {
1718 flags |= FILE_FLAG_OPEN_REPARSE_POINT;
1719 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001720
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001721 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING, flags, NULL);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001722 if (hFile == INVALID_HANDLE_VALUE) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001723 /* Either the path doesn't exist, or the caller lacks access. */
1724 error = GetLastError();
1725 switch (error) {
1726 case ERROR_ACCESS_DENIED: /* Cannot sync or read attributes. */
1727 case ERROR_SHARING_VIOLATION: /* It's a paging file. */
1728 /* Try reading the parent directory. */
1729 if (!attributes_from_dir(path, &fileInfo, &tagInfo.ReparseTag)) {
1730 /* Cannot read the parent directory. */
1731 SetLastError(error);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001732 return -1;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001733 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001734 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1735 if (traverse ||
1736 !IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1737 /* The stat call has to traverse but cannot, so fail. */
1738 SetLastError(error);
Brian Curtind25aef52011-06-13 15:16:04 -05001739 return -1;
Mark Becwarb82bfac2019-02-02 16:08:23 -05001740 }
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001741 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001742 break;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001743
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001744 case ERROR_INVALID_PARAMETER:
1745 /* \\.\con requires read or write access. */
1746 hFile = CreateFileW(path, access | GENERIC_READ,
1747 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1748 OPEN_EXISTING, flags, NULL);
1749 if (hFile == INVALID_HANDLE_VALUE) {
1750 SetLastError(error);
1751 return -1;
1752 }
1753 break;
1754
1755 case ERROR_CANT_ACCESS_FILE:
1756 /* bpo37834: open unhandled reparse points if traverse fails. */
1757 if (traverse) {
1758 traverse = FALSE;
1759 isUnhandledTag = TRUE;
1760 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING,
1761 flags | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
1762 }
1763 if (hFile == INVALID_HANDLE_VALUE) {
1764 SetLastError(error);
1765 return -1;
1766 }
1767 break;
1768
1769 default:
1770 return -1;
1771 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001772 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001773
1774 if (hFile != INVALID_HANDLE_VALUE) {
1775 /* Handle types other than files on disk. */
1776 fileType = GetFileType(hFile);
1777 if (fileType != FILE_TYPE_DISK) {
1778 if (fileType == FILE_TYPE_UNKNOWN && GetLastError() != 0) {
1779 retval = -1;
1780 goto cleanup;
1781 }
1782 DWORD fileAttributes = GetFileAttributesW(path);
1783 memset(result, 0, sizeof(*result));
1784 if (fileAttributes != INVALID_FILE_ATTRIBUTES &&
1785 fileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1786 /* \\.\pipe\ or \\.\mailslot\ */
1787 result->st_mode = _S_IFDIR;
1788 } else if (fileType == FILE_TYPE_CHAR) {
1789 /* \\.\nul */
1790 result->st_mode = _S_IFCHR;
1791 } else if (fileType == FILE_TYPE_PIPE) {
1792 /* \\.\pipe\spam */
1793 result->st_mode = _S_IFIFO;
1794 }
1795 /* FILE_TYPE_UNKNOWN, e.g. \\.\mailslot\waitfor.exe\spam */
1796 goto cleanup;
1797 }
1798
1799 /* Query the reparse tag, and traverse a non-link. */
1800 if (!traverse) {
1801 if (!GetFileInformationByHandleEx(hFile, FileAttributeTagInfo,
1802 &tagInfo, sizeof(tagInfo))) {
1803 /* Allow devices that do not support FileAttributeTagInfo. */
1804 switch (GetLastError()) {
1805 case ERROR_INVALID_PARAMETER:
1806 case ERROR_INVALID_FUNCTION:
1807 case ERROR_NOT_SUPPORTED:
1808 tagInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1809 tagInfo.ReparseTag = 0;
1810 break;
1811 default:
1812 retval = -1;
1813 goto cleanup;
1814 }
1815 } else if (tagInfo.FileAttributes &
1816 FILE_ATTRIBUTE_REPARSE_POINT) {
1817 if (IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1818 if (isUnhandledTag) {
1819 /* Traversing previously failed for either this link
1820 or its target. */
1821 SetLastError(ERROR_CANT_ACCESS_FILE);
1822 retval = -1;
1823 goto cleanup;
1824 }
1825 /* Traverse a non-link, but not if traversing already failed
1826 for an unhandled tag. */
1827 } else if (!isUnhandledTag) {
1828 CloseHandle(hFile);
1829 return win32_xstat_impl(path, result, TRUE);
1830 }
1831 }
1832 }
1833
1834 if (!GetFileInformationByHandle(hFile, &fileInfo)) {
1835 switch (GetLastError()) {
1836 case ERROR_INVALID_PARAMETER:
1837 case ERROR_INVALID_FUNCTION:
1838 case ERROR_NOT_SUPPORTED:
Steve Dower772ec0f2019-09-04 14:42:54 -07001839 /* Volumes and physical disks are block devices, e.g.
1840 \\.\C: and \\.\PhysicalDrive0. */
1841 memset(result, 0, sizeof(*result));
1842 result->st_mode = 0x6000; /* S_IFBLK */
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001843 goto cleanup;
1844 }
Steve Dower772ec0f2019-09-04 14:42:54 -07001845 retval = -1;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001846 goto cleanup;
1847 }
1848 }
1849
1850 _Py_attribute_data_to_stat(&fileInfo, tagInfo.ReparseTag, result);
1851
1852 if (!(fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
1853 /* Fix the file execute permissions. This hack sets S_IEXEC if
1854 the filename has an extension that is commonly used by files
1855 that CreateProcessW can execute. A real implementation calls
1856 GetSecurityInfo, OpenThreadToken/OpenProcessToken, and
1857 AccessCheck to check for generic read, write, and execute
1858 access. */
1859 const wchar_t *fileExtension = wcsrchr(path, '.');
1860 if (fileExtension) {
1861 if (_wcsicmp(fileExtension, L".exe") == 0 ||
1862 _wcsicmp(fileExtension, L".bat") == 0 ||
1863 _wcsicmp(fileExtension, L".cmd") == 0 ||
1864 _wcsicmp(fileExtension, L".com") == 0) {
1865 result->st_mode |= 0111;
1866 }
1867 }
1868 }
1869
1870cleanup:
1871 if (hFile != INVALID_HANDLE_VALUE) {
Steve Dower772ec0f2019-09-04 14:42:54 -07001872 /* Preserve last error if we are failing */
1873 error = retval ? GetLastError() : 0;
1874 if (!CloseHandle(hFile)) {
1875 retval = -1;
1876 } else if (retval) {
1877 /* Restore last error */
1878 SetLastError(error);
1879 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001880 }
1881
1882 return retval;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001883}
1884
1885static int
Steve Dowercc16be82016-09-08 10:35:16 -07001886win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001887{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001888 /* Protocol violation: we explicitly clear errno, instead of
1889 setting it to a POSIX error. Callers should use GetLastError. */
Brian Curtind25aef52011-06-13 15:16:04 -05001890 int code = win32_xstat_impl(path, result, traverse);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001891 errno = 0;
1892 return code;
1893}
Brian Curtind25aef52011-06-13 15:16:04 -05001894/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
Brian Curtind40e6f72010-07-08 21:39:08 +00001895
1896 In Posix, stat automatically traverses symlinks and returns the stat
1897 structure for the target. In Windows, the equivalent GetFileAttributes by
1898 default does not traverse symlinks and instead returns attributes for
1899 the symlink.
1900
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001901 Instead, we will open the file (which *does* traverse symlinks by default)
1902 and GetFileInformationByHandle(). */
Brian Curtind40e6f72010-07-08 21:39:08 +00001903
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001904static int
Steve Dowercc16be82016-09-08 10:35:16 -07001905win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
Martin v. Löwis14694662006-02-03 12:54:16 +00001906{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001907 return win32_xstat(path, result, FALSE);
Martin v. Löwis14694662006-02-03 12:54:16 +00001908}
1909
Victor Stinner8c62be82010-05-06 00:08:46 +00001910static int
Steve Dowercc16be82016-09-08 10:35:16 -07001911win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
Brian Curtind40e6f72010-07-08 21:39:08 +00001912{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001913 return win32_xstat(path, result, TRUE);
Brian Curtind40e6f72010-07-08 21:39:08 +00001914}
1915
Martin v. Löwis14694662006-02-03 12:54:16 +00001916#endif /* MS_WINDOWS */
1917
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001918PyDoc_STRVAR(stat_result__doc__,
Larry Hastings9cf065c2012-06-22 16:30:09 -07001919"stat_result: Result from stat, fstat, or lstat.\n\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001920This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001921 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001922or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1923\n\
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001924Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1925or st_flags, they are available as attributes only.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001926\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001927See os.stat for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001928
1929static PyStructSequence_Field stat_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001930 {"st_mode", "protection bits"},
1931 {"st_ino", "inode"},
1932 {"st_dev", "device"},
1933 {"st_nlink", "number of hard links"},
1934 {"st_uid", "user ID of owner"},
1935 {"st_gid", "group ID of owner"},
1936 {"st_size", "total size, in bytes"},
1937 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1938 {NULL, "integer time of last access"},
1939 {NULL, "integer time of last modification"},
1940 {NULL, "integer time of last change"},
1941 {"st_atime", "time of last access"},
1942 {"st_mtime", "time of last modification"},
1943 {"st_ctime", "time of last change"},
Larry Hastings6fe20b32012-04-19 15:07:49 -07001944 {"st_atime_ns", "time of last access in nanoseconds"},
1945 {"st_mtime_ns", "time of last modification in nanoseconds"},
1946 {"st_ctime_ns", "time of last change in nanoseconds"},
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001947#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00001948 {"st_blksize", "blocksize for filesystem I/O"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001949#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001950#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00001951 {"st_blocks", "number of blocks allocated"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001952#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001953#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00001954 {"st_rdev", "device type (if inode device)"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001955#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001956#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00001957 {"st_flags", "user defined flags for file"},
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001958#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001959#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00001960 {"st_gen", "generation number"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001961#endif
1962#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00001963 {"st_birthtime", "time of creation"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001964#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05001965#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1966 {"st_file_attributes", "Windows file attribute bits"},
1967#endif
jcea6c51d512018-01-28 14:00:08 +01001968#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1969 {"st_fstype", "Type of filesystem"},
1970#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001971#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
1972 {"st_reparse_tag", "Windows reparse tag"},
1973#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001974 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001975};
1976
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001977#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Larry Hastings6fe20b32012-04-19 15:07:49 -07001978#define ST_BLKSIZE_IDX 16
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001979#else
Larry Hastings6fe20b32012-04-19 15:07:49 -07001980#define ST_BLKSIZE_IDX 15
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001981#endif
1982
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001983#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001984#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
1985#else
1986#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
1987#endif
1988
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001989#ifdef HAVE_STRUCT_STAT_ST_RDEV
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001990#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
1991#else
1992#define ST_RDEV_IDX ST_BLOCKS_IDX
1993#endif
1994
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001995#ifdef HAVE_STRUCT_STAT_ST_FLAGS
1996#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
1997#else
1998#define ST_FLAGS_IDX ST_RDEV_IDX
1999#endif
2000
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002001#ifdef HAVE_STRUCT_STAT_ST_GEN
Martin v. Löwisf09582e2005-08-14 21:42:34 +00002002#define ST_GEN_IDX (ST_FLAGS_IDX+1)
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002003#else
Martin v. Löwisf09582e2005-08-14 21:42:34 +00002004#define ST_GEN_IDX ST_FLAGS_IDX
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002005#endif
2006
2007#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
2008#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
2009#else
2010#define ST_BIRTHTIME_IDX ST_GEN_IDX
2011#endif
2012
Zachary Ware63f277b2014-06-19 09:46:37 -05002013#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2014#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_IDX+1)
2015#else
2016#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_IDX
2017#endif
2018
jcea6c51d512018-01-28 14:00:08 +01002019#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2020#define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
2021#else
2022#define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
2023#endif
2024
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002025#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2026#define ST_REPARSE_TAG_IDX (ST_FSTYPE_IDX+1)
2027#else
2028#define ST_REPARSE_TAG_IDX ST_FSTYPE_IDX
2029#endif
2030
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002031static PyStructSequence_Desc stat_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002032 "stat_result", /* name */
2033 stat_result__doc__, /* doc */
2034 stat_result_fields,
2035 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002036};
2037
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002038PyDoc_STRVAR(statvfs_result__doc__,
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002039"statvfs_result: Result from statvfs or fstatvfs.\n\n\
2040This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00002041 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
Guido van Rossuma4dc73e2001-10-18 20:53:15 +00002042or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002043\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002044See os.statvfs for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002045
2046static PyStructSequence_Field statvfs_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002047 {"f_bsize", },
2048 {"f_frsize", },
2049 {"f_blocks", },
2050 {"f_bfree", },
2051 {"f_bavail", },
2052 {"f_files", },
2053 {"f_ffree", },
2054 {"f_favail", },
2055 {"f_flag", },
2056 {"f_namemax",},
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +01002057 {"f_fsid", },
Victor Stinner8c62be82010-05-06 00:08:46 +00002058 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002059};
2060
2061static PyStructSequence_Desc statvfs_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002062 "statvfs_result", /* name */
2063 statvfs_result__doc__, /* doc */
2064 statvfs_result_fields,
2065 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002066};
2067
Ross Lagerwall7807c352011-03-17 20:20:30 +02002068#if defined(HAVE_WAITID) && !defined(__APPLE__)
2069PyDoc_STRVAR(waitid_result__doc__,
2070"waitid_result: Result from waitid.\n\n\
2071This object may be accessed either as a tuple of\n\
2072 (si_pid, si_uid, si_signo, si_status, si_code),\n\
2073or via the attributes si_pid, si_uid, and so on.\n\
2074\n\
2075See os.waitid for more information.");
2076
2077static PyStructSequence_Field waitid_result_fields[] = {
2078 {"si_pid", },
2079 {"si_uid", },
2080 {"si_signo", },
2081 {"si_status", },
2082 {"si_code", },
2083 {0}
2084};
2085
2086static PyStructSequence_Desc waitid_result_desc = {
2087 "waitid_result", /* name */
2088 waitid_result__doc__, /* doc */
2089 waitid_result_fields,
2090 5
2091};
Benjamin Petersonbad9c2f2011-08-02 18:42:14 -05002092#endif
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002093static newfunc structseq_new;
2094
2095static PyObject *
2096statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2097{
Victor Stinner8c62be82010-05-06 00:08:46 +00002098 PyStructSequence *result;
2099 int i;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002100
Victor Stinner8c62be82010-05-06 00:08:46 +00002101 result = (PyStructSequence*)structseq_new(type, args, kwds);
2102 if (!result)
2103 return NULL;
2104 /* If we have been initialized from a tuple,
2105 st_?time might be set to None. Initialize it
2106 from the int slots. */
2107 for (i = 7; i <= 9; i++) {
2108 if (result->ob_item[i+3] == Py_None) {
2109 Py_DECREF(Py_None);
2110 Py_INCREF(result->ob_item[i]);
2111 result->ob_item[i+3] = result->ob_item[i];
2112 }
2113 }
2114 return (PyObject*)result;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002115}
2116
Eddie Elizondob3966632019-11-05 07:16:14 -08002117static int
2118_posix_clear(PyObject *module)
2119{
2120 Py_CLEAR(_posixstate(module)->billion);
Victor Stinner623ed612020-01-21 19:25:32 +01002121#ifdef PY_PUTENV_DICT
2122 Py_CLEAR(_posixstate(module)->putenv_dict);
2123#endif
Eddie Elizondob3966632019-11-05 07:16:14 -08002124 Py_CLEAR(_posixstate(module)->DirEntryType);
2125 Py_CLEAR(_posixstate(module)->ScandirIteratorType);
2126#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
2127 Py_CLEAR(_posixstate(module)->SchedParamType);
2128#endif
2129 Py_CLEAR(_posixstate(module)->StatResultType);
2130 Py_CLEAR(_posixstate(module)->StatVFSResultType);
2131 Py_CLEAR(_posixstate(module)->TerminalSizeType);
2132 Py_CLEAR(_posixstate(module)->TimesResultType);
2133 Py_CLEAR(_posixstate(module)->UnameResultType);
2134#if defined(HAVE_WAITID) && !defined(__APPLE__)
2135 Py_CLEAR(_posixstate(module)->WaitidResultType);
2136#endif
2137#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
2138 Py_CLEAR(_posixstate(module)->struct_rusage);
2139#endif
2140 Py_CLEAR(_posixstate(module)->st_mode);
2141 return 0;
2142}
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002143
Eddie Elizondob3966632019-11-05 07:16:14 -08002144static int
2145_posix_traverse(PyObject *module, visitproc visit, void *arg)
2146{
2147 Py_VISIT(_posixstate(module)->billion);
Victor Stinner623ed612020-01-21 19:25:32 +01002148#ifdef PY_PUTENV_DICT
2149 Py_VISIT(_posixstate(module)->putenv_dict);
2150#endif
Eddie Elizondob3966632019-11-05 07:16:14 -08002151 Py_VISIT(_posixstate(module)->DirEntryType);
2152 Py_VISIT(_posixstate(module)->ScandirIteratorType);
2153#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
2154 Py_VISIT(_posixstate(module)->SchedParamType);
2155#endif
2156 Py_VISIT(_posixstate(module)->StatResultType);
2157 Py_VISIT(_posixstate(module)->StatVFSResultType);
2158 Py_VISIT(_posixstate(module)->TerminalSizeType);
2159 Py_VISIT(_posixstate(module)->TimesResultType);
2160 Py_VISIT(_posixstate(module)->UnameResultType);
2161#if defined(HAVE_WAITID) && !defined(__APPLE__)
2162 Py_VISIT(_posixstate(module)->WaitidResultType);
2163#endif
2164#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
2165 Py_VISIT(_posixstate(module)->struct_rusage);
2166#endif
2167 Py_VISIT(_posixstate(module)->st_mode);
2168 return 0;
2169}
2170
2171static void
2172_posix_free(void *module)
2173{
2174 _posix_clear((PyObject *)module);
2175}
Larry Hastings6fe20b32012-04-19 15:07:49 -07002176
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002177static void
Victor Stinner4195b5c2012-02-08 23:03:19 +01002178fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002179{
Larry Hastings6fe20b32012-04-19 15:07:49 -07002180 PyObject *s = _PyLong_FromTime_t(sec);
2181 PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
2182 PyObject *s_in_ns = NULL;
2183 PyObject *ns_total = NULL;
2184 PyObject *float_s = NULL;
2185
2186 if (!(s && ns_fractional))
2187 goto exit;
2188
Eddie Elizondob3966632019-11-05 07:16:14 -08002189 s_in_ns = PyNumber_Multiply(s, _posixstate_global->billion);
Larry Hastings6fe20b32012-04-19 15:07:49 -07002190 if (!s_in_ns)
2191 goto exit;
2192
2193 ns_total = PyNumber_Add(s_in_ns, ns_fractional);
2194 if (!ns_total)
2195 goto exit;
2196
Victor Stinner01b5aab2017-10-24 02:02:00 -07002197 float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
2198 if (!float_s) {
2199 goto exit;
Larry Hastings6fe20b32012-04-19 15:07:49 -07002200 }
2201
2202 PyStructSequence_SET_ITEM(v, index, s);
2203 PyStructSequence_SET_ITEM(v, index+3, float_s);
2204 PyStructSequence_SET_ITEM(v, index+6, ns_total);
2205 s = NULL;
2206 float_s = NULL;
2207 ns_total = NULL;
2208exit:
2209 Py_XDECREF(s);
2210 Py_XDECREF(ns_fractional);
2211 Py_XDECREF(s_in_ns);
2212 Py_XDECREF(ns_total);
2213 Py_XDECREF(float_s);
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002214}
2215
Tim Peters5aa91602002-01-30 05:46:57 +00002216/* pack a system stat C structure into the Python stat tuple
Fred Drake699f3522000-06-29 21:12:41 +00002217 (used by posix_stat() and posix_fstat()) */
2218static PyObject*
Victor Stinner4195b5c2012-02-08 23:03:19 +01002219_pystat_fromstructstat(STRUCT_STAT *st)
Fred Drake699f3522000-06-29 21:12:41 +00002220{
Victor Stinner8c62be82010-05-06 00:08:46 +00002221 unsigned long ansec, mnsec, cnsec;
Eddie Elizondob3966632019-11-05 07:16:14 -08002222 PyObject *StatResultType = _posixstate_global->StatResultType;
2223 PyObject *v = PyStructSequence_New((PyTypeObject *)StatResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +00002224 if (v == NULL)
2225 return NULL;
Fred Drake699f3522000-06-29 21:12:41 +00002226
Victor Stinner8c62be82010-05-06 00:08:46 +00002227 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode));
Victor Stinner0f6d7332017-03-09 17:34:28 +01002228 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(st->st_ino));
xdegaye50e86032017-05-22 11:15:08 +02002229 PyStructSequence_SET_ITEM(v, 1, PyLong_FromUnsignedLongLong(st->st_ino));
Serhiy Storchaka404fa922013-01-02 18:22:23 +02002230#ifdef MS_WINDOWS
2231 PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002232#else
Serhiy Storchakab2653b32015-01-18 11:12:11 +02002233 PyStructSequence_SET_ITEM(v, 2, _PyLong_FromDev(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002234#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002235 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02002236#if defined(MS_WINDOWS)
2237 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong(0));
2238 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong(0));
2239#else
2240 PyStructSequence_SET_ITEM(v, 4, _PyLong_FromUid(st->st_uid));
2241 PyStructSequence_SET_ITEM(v, 5, _PyLong_FromGid(st->st_gid));
2242#endif
xdegaye50e86032017-05-22 11:15:08 +02002243 Py_BUILD_ASSERT(sizeof(long long) >= sizeof(st->st_size));
2244 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLongLong(st->st_size));
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002245
Martin v. Löwis14694662006-02-03 12:54:16 +00002246#if defined(HAVE_STAT_TV_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002247 ansec = st->st_atim.tv_nsec;
2248 mnsec = st->st_mtim.tv_nsec;
2249 cnsec = st->st_ctim.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002250#elif defined(HAVE_STAT_TV_NSEC2)
Victor Stinner8c62be82010-05-06 00:08:46 +00002251 ansec = st->st_atimespec.tv_nsec;
2252 mnsec = st->st_mtimespec.tv_nsec;
2253 cnsec = st->st_ctimespec.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002254#elif defined(HAVE_STAT_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002255 ansec = st->st_atime_nsec;
2256 mnsec = st->st_mtime_nsec;
2257 cnsec = st->st_ctime_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002258#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002259 ansec = mnsec = cnsec = 0;
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002260#endif
Victor Stinner4195b5c2012-02-08 23:03:19 +01002261 fill_time(v, 7, st->st_atime, ansec);
2262 fill_time(v, 8, st->st_mtime, mnsec);
2263 fill_time(v, 9, st->st_ctime, cnsec);
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002264
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002265#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00002266 PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
2267 PyLong_FromLong((long)st->st_blksize));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002268#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002269#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00002270 PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
2271 PyLong_FromLong((long)st->st_blocks));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002272#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002273#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00002274 PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
2275 PyLong_FromLong((long)st->st_rdev));
Fred Drake699f3522000-06-29 21:12:41 +00002276#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002277#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00002278 PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
2279 PyLong_FromLong((long)st->st_gen));
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002280#endif
2281#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00002282 {
Victor Stinner4195b5c2012-02-08 23:03:19 +01002283 PyObject *val;
2284 unsigned long bsec,bnsec;
2285 bsec = (long)st->st_birthtime;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002286#ifdef HAVE_STAT_TV_NSEC2
Victor Stinner4195b5c2012-02-08 23:03:19 +01002287 bnsec = st->st_birthtimespec.tv_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002288#else
Victor Stinner4195b5c2012-02-08 23:03:19 +01002289 bnsec = 0;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002290#endif
Victor Stinner01b5aab2017-10-24 02:02:00 -07002291 val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
Victor Stinner4195b5c2012-02-08 23:03:19 +01002292 PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
2293 val);
Victor Stinner8c62be82010-05-06 00:08:46 +00002294 }
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002295#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002296#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00002297 PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
2298 PyLong_FromLong((long)st->st_flags));
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002299#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05002300#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2301 PyStructSequence_SET_ITEM(v, ST_FILE_ATTRIBUTES_IDX,
2302 PyLong_FromUnsignedLong(st->st_file_attributes));
2303#endif
jcea6c51d512018-01-28 14:00:08 +01002304#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2305 PyStructSequence_SET_ITEM(v, ST_FSTYPE_IDX,
2306 PyUnicode_FromString(st->st_fstype));
2307#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002308#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2309 PyStructSequence_SET_ITEM(v, ST_REPARSE_TAG_IDX,
2310 PyLong_FromUnsignedLong(st->st_reparse_tag));
2311#endif
Fred Drake699f3522000-06-29 21:12:41 +00002312
Victor Stinner8c62be82010-05-06 00:08:46 +00002313 if (PyErr_Occurred()) {
2314 Py_DECREF(v);
2315 return NULL;
2316 }
Fred Drake699f3522000-06-29 21:12:41 +00002317
Victor Stinner8c62be82010-05-06 00:08:46 +00002318 return v;
Fred Drake699f3522000-06-29 21:12:41 +00002319}
2320
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002321/* POSIX methods */
2322
Guido van Rossum94f6f721999-01-06 18:42:14 +00002323
2324static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002325posix_do_stat(const char *function_name, path_t *path,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002326 int dir_fd, int follow_symlinks)
Guido van Rossum94f6f721999-01-06 18:42:14 +00002327{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002328 STRUCT_STAT st;
2329 int result;
2330
2331#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
2332 if (follow_symlinks_specified(function_name, follow_symlinks))
2333 return NULL;
2334#endif
2335
2336 if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
2337 dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
2338 fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
2339 return NULL;
2340
2341 Py_BEGIN_ALLOW_THREADS
2342 if (path->fd != -1)
2343 result = FSTAT(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002344#ifdef MS_WINDOWS
Steve Dower513d7472016-09-08 10:41:50 -07002345 else if (follow_symlinks)
Steve Dowercc16be82016-09-08 10:35:16 -07002346 result = win32_stat(path->wide, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002347 else
Steve Dowercc16be82016-09-08 10:35:16 -07002348 result = win32_lstat(path->wide, &st);
2349#else
2350 else
2351#if defined(HAVE_LSTAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002352 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
2353 result = LSTAT(path->narrow, &st);
2354 else
Steve Dowercc16be82016-09-08 10:35:16 -07002355#endif /* HAVE_LSTAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002356#ifdef HAVE_FSTATAT
2357 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks)
2358 result = fstatat(dir_fd, path->narrow, &st,
2359 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2360 else
Steve Dowercc16be82016-09-08 10:35:16 -07002361#endif /* HAVE_FSTATAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002362 result = STAT(path->narrow, &st);
Steve Dowercc16be82016-09-08 10:35:16 -07002363#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002364 Py_END_ALLOW_THREADS
2365
Victor Stinner292c8352012-10-30 02:17:38 +01002366 if (result != 0) {
2367 return path_error(path);
2368 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07002369
2370 return _pystat_fromstructstat(&st);
2371}
2372
Larry Hastings2f936352014-08-05 14:04:04 +10002373/*[python input]
2374
2375for s in """
2376
2377FACCESSAT
2378FCHMODAT
2379FCHOWNAT
2380FSTATAT
2381LINKAT
2382MKDIRAT
2383MKFIFOAT
2384MKNODAT
2385OPENAT
2386READLINKAT
2387SYMLINKAT
2388UNLINKAT
2389
2390""".strip().split():
2391 s = s.strip()
2392 print("""
2393#ifdef HAVE_{s}
2394 #define {s}_DIR_FD_CONVERTER dir_fd_converter
Larry Hastings31826802013-10-19 00:09:25 -07002395#else
Larry Hastings2f936352014-08-05 14:04:04 +10002396 #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings31826802013-10-19 00:09:25 -07002397#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002398""".rstrip().format(s=s))
2399
2400for s in """
2401
2402FCHDIR
2403FCHMOD
2404FCHOWN
2405FDOPENDIR
2406FEXECVE
2407FPATHCONF
2408FSTATVFS
2409FTRUNCATE
2410
2411""".strip().split():
2412 s = s.strip()
2413 print("""
2414#ifdef HAVE_{s}
2415 #define PATH_HAVE_{s} 1
2416#else
2417 #define PATH_HAVE_{s} 0
2418#endif
2419
2420""".rstrip().format(s=s))
2421[python start generated code]*/
2422
2423#ifdef HAVE_FACCESSAT
2424 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
2425#else
2426 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
2427#endif
2428
2429#ifdef HAVE_FCHMODAT
2430 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
2431#else
2432 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
2433#endif
2434
2435#ifdef HAVE_FCHOWNAT
2436 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
2437#else
2438 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
2439#endif
2440
2441#ifdef HAVE_FSTATAT
2442 #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
2443#else
2444 #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
2445#endif
2446
2447#ifdef HAVE_LINKAT
2448 #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
2449#else
2450 #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2451#endif
2452
2453#ifdef HAVE_MKDIRAT
2454 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
2455#else
2456 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
2457#endif
2458
2459#ifdef HAVE_MKFIFOAT
2460 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
2461#else
2462 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
2463#endif
2464
2465#ifdef HAVE_MKNODAT
2466 #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
2467#else
2468 #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
2469#endif
2470
2471#ifdef HAVE_OPENAT
2472 #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
2473#else
2474 #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
2475#endif
2476
2477#ifdef HAVE_READLINKAT
2478 #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
2479#else
2480 #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2481#endif
2482
2483#ifdef HAVE_SYMLINKAT
2484 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
2485#else
2486 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2487#endif
2488
2489#ifdef HAVE_UNLINKAT
2490 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
2491#else
2492 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2493#endif
2494
2495#ifdef HAVE_FCHDIR
2496 #define PATH_HAVE_FCHDIR 1
2497#else
2498 #define PATH_HAVE_FCHDIR 0
2499#endif
2500
2501#ifdef HAVE_FCHMOD
2502 #define PATH_HAVE_FCHMOD 1
2503#else
2504 #define PATH_HAVE_FCHMOD 0
2505#endif
2506
2507#ifdef HAVE_FCHOWN
2508 #define PATH_HAVE_FCHOWN 1
2509#else
2510 #define PATH_HAVE_FCHOWN 0
2511#endif
2512
2513#ifdef HAVE_FDOPENDIR
2514 #define PATH_HAVE_FDOPENDIR 1
2515#else
2516 #define PATH_HAVE_FDOPENDIR 0
2517#endif
2518
2519#ifdef HAVE_FEXECVE
2520 #define PATH_HAVE_FEXECVE 1
2521#else
2522 #define PATH_HAVE_FEXECVE 0
2523#endif
2524
2525#ifdef HAVE_FPATHCONF
2526 #define PATH_HAVE_FPATHCONF 1
2527#else
2528 #define PATH_HAVE_FPATHCONF 0
2529#endif
2530
2531#ifdef HAVE_FSTATVFS
2532 #define PATH_HAVE_FSTATVFS 1
2533#else
2534 #define PATH_HAVE_FSTATVFS 0
2535#endif
2536
2537#ifdef HAVE_FTRUNCATE
2538 #define PATH_HAVE_FTRUNCATE 1
2539#else
2540 #define PATH_HAVE_FTRUNCATE 0
2541#endif
2542/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
Larry Hastings31826802013-10-19 00:09:25 -07002543
Steve Dowerfe0a41a2015-03-20 19:50:46 -07002544#ifdef MS_WINDOWS
2545 #undef PATH_HAVE_FTRUNCATE
2546 #define PATH_HAVE_FTRUNCATE 1
2547#endif
Larry Hastings31826802013-10-19 00:09:25 -07002548
Larry Hastings61272b72014-01-07 12:41:53 -08002549/*[python input]
Larry Hastings31826802013-10-19 00:09:25 -07002550
2551class path_t_converter(CConverter):
2552
2553 type = "path_t"
2554 impl_by_reference = True
2555 parse_by_reference = True
2556
2557 converter = 'path_converter'
2558
2559 def converter_init(self, *, allow_fd=False, nullable=False):
Larry Hastings31826802013-10-19 00:09:25 -07002560 # right now path_t doesn't support default values.
2561 # to support a default value, you'll need to override initialize().
Larry Hastings2f936352014-08-05 14:04:04 +10002562 if self.default not in (unspecified, None):
Larry Hastings7726ac92014-01-31 22:03:12 -08002563 fail("Can't specify a default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002564
Larry Hastings2f936352014-08-05 14:04:04 +10002565 if self.c_default not in (None, 'Py_None'):
2566 raise RuntimeError("Can't specify a c_default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002567
2568 self.nullable = nullable
2569 self.allow_fd = allow_fd
2570
Larry Hastings7726ac92014-01-31 22:03:12 -08002571 def pre_render(self):
2572 def strify(value):
Larry Hastings2f936352014-08-05 14:04:04 +10002573 if isinstance(value, str):
2574 return value
Larry Hastings7726ac92014-01-31 22:03:12 -08002575 return str(int(bool(value)))
2576
2577 # add self.py_name here when merging with posixmodule conversion
Larry Hastings2f936352014-08-05 14:04:04 +10002578 self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
Larry Hastings31826802013-10-19 00:09:25 -07002579 self.function.name,
Larry Hastings2f936352014-08-05 14:04:04 +10002580 self.name,
Larry Hastings7726ac92014-01-31 22:03:12 -08002581 strify(self.nullable),
2582 strify(self.allow_fd),
Larry Hastings31826802013-10-19 00:09:25 -07002583 )
2584
2585 def cleanup(self):
2586 return "path_cleanup(&" + self.name + ");\n"
2587
2588
2589class dir_fd_converter(CConverter):
2590 type = 'int'
Larry Hastings31826802013-10-19 00:09:25 -07002591
Larry Hastings2f936352014-08-05 14:04:04 +10002592 def converter_init(self, requires=None):
Larry Hastings31826802013-10-19 00:09:25 -07002593 if self.default in (unspecified, None):
2594 self.c_default = 'DEFAULT_DIR_FD'
Larry Hastings2f936352014-08-05 14:04:04 +10002595 if isinstance(requires, str):
2596 self.converter = requires.upper() + '_DIR_FD_CONVERTER'
2597 else:
2598 self.converter = 'dir_fd_converter'
Larry Hastings31826802013-10-19 00:09:25 -07002599
Larry Hastings2f936352014-08-05 14:04:04 +10002600class fildes_converter(CConverter):
2601 type = 'int'
2602 converter = 'fildes_converter'
2603
2604class uid_t_converter(CConverter):
2605 type = "uid_t"
2606 converter = '_Py_Uid_Converter'
2607
2608class gid_t_converter(CConverter):
2609 type = "gid_t"
2610 converter = '_Py_Gid_Converter'
2611
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02002612class dev_t_converter(CConverter):
2613 type = 'dev_t'
2614 converter = '_Py_Dev_Converter'
2615
2616class dev_t_return_converter(unsigned_long_return_converter):
2617 type = 'dev_t'
2618 conversion_fn = '_PyLong_FromDev'
2619 unsigned_cast = '(dev_t)'
2620
Larry Hastings2f936352014-08-05 14:04:04 +10002621class FSConverter_converter(CConverter):
2622 type = 'PyObject *'
2623 converter = 'PyUnicode_FSConverter'
2624 def converter_init(self):
2625 if self.default is not unspecified:
2626 fail("FSConverter_converter does not support default values")
2627 self.c_default = 'NULL'
2628
2629 def cleanup(self):
2630 return "Py_XDECREF(" + self.name + ");\n"
2631
2632class pid_t_converter(CConverter):
2633 type = 'pid_t'
2634 format_unit = '" _Py_PARSE_PID "'
2635
2636class idtype_t_converter(int_converter):
2637 type = 'idtype_t'
2638
2639class id_t_converter(CConverter):
2640 type = 'id_t'
2641 format_unit = '" _Py_PARSE_PID "'
2642
Benjamin Petersonca470632016-09-06 13:47:26 -07002643class intptr_t_converter(CConverter):
2644 type = 'intptr_t'
Larry Hastings2f936352014-08-05 14:04:04 +10002645 format_unit = '" _Py_PARSE_INTPTR "'
2646
2647class Py_off_t_converter(CConverter):
2648 type = 'Py_off_t'
2649 converter = 'Py_off_t_converter'
2650
2651class Py_off_t_return_converter(long_return_converter):
2652 type = 'Py_off_t'
2653 conversion_fn = 'PyLong_FromPy_off_t'
2654
2655class path_confname_converter(CConverter):
2656 type="int"
2657 converter="conv_path_confname"
2658
2659class confstr_confname_converter(path_confname_converter):
2660 converter='conv_confstr_confname'
2661
2662class sysconf_confname_converter(path_confname_converter):
2663 converter="conv_sysconf_confname"
2664
2665class sched_param_converter(CConverter):
2666 type = 'struct sched_param'
2667 converter = 'convert_sched_param'
2668 impl_by_reference = True;
Larry Hastings31826802013-10-19 00:09:25 -07002669
Larry Hastings61272b72014-01-07 12:41:53 -08002670[python start generated code]*/
Victor Stinner581139c2016-09-06 15:54:20 -07002671/*[python end generated code: output=da39a3ee5e6b4b0d input=418fce0e01144461]*/
Larry Hastings31826802013-10-19 00:09:25 -07002672
Larry Hastings61272b72014-01-07 12:41:53 -08002673/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002674
Larry Hastings2a727912014-01-16 11:32:01 -08002675os.stat
Larry Hastings31826802013-10-19 00:09:25 -07002676
2677 path : path_t(allow_fd=True)
BNMetricsb9427072018-11-02 15:20:19 +00002678 Path to be examined; can be string, bytes, a path-like object or
Xiang Zhang4459e002017-01-22 13:04:17 +08002679 open-file-descriptor int.
Larry Hastings31826802013-10-19 00:09:25 -07002680
2681 *
2682
Larry Hastings2f936352014-08-05 14:04:04 +10002683 dir_fd : dir_fd(requires='fstatat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002684 If not None, it should be a file descriptor open to a directory,
2685 and path should be a relative string; path will then be relative to
2686 that directory.
2687
2688 follow_symlinks: bool = True
2689 If False, and the last element of the path is a symbolic link,
2690 stat will examine the symbolic link itself instead of the file
2691 the link points to.
2692
2693Perform a stat system call on the given path.
2694
2695dir_fd and follow_symlinks may not be implemented
2696 on your platform. If they are unavailable, using them will raise a
2697 NotImplementedError.
2698
2699It's an error to use dir_fd or follow_symlinks when specifying path as
2700 an open file descriptor.
2701
Larry Hastings61272b72014-01-07 12:41:53 -08002702[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002703
Larry Hastings31826802013-10-19 00:09:25 -07002704static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002705os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002706/*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
Larry Hastings31826802013-10-19 00:09:25 -07002707{
2708 return posix_do_stat("stat", path, dir_fd, follow_symlinks);
2709}
2710
Larry Hastings2f936352014-08-05 14:04:04 +10002711
2712/*[clinic input]
2713os.lstat
2714
2715 path : path_t
2716
2717 *
2718
2719 dir_fd : dir_fd(requires='fstatat') = None
2720
2721Perform a stat system call on the given path, without following symbolic links.
2722
2723Like stat(), but do not follow symbolic links.
2724Equivalent to stat(path, follow_symlinks=False).
2725[clinic start generated code]*/
2726
Larry Hastings2f936352014-08-05 14:04:04 +10002727static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002728os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
2729/*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002730{
2731 int follow_symlinks = 0;
2732 return posix_do_stat("lstat", path, dir_fd, follow_symlinks);
2733}
Larry Hastings31826802013-10-19 00:09:25 -07002734
Larry Hastings2f936352014-08-05 14:04:04 +10002735
Larry Hastings61272b72014-01-07 12:41:53 -08002736/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10002737os.access -> bool
Larry Hastings31826802013-10-19 00:09:25 -07002738
Benjamin Peterson768f3b42016-09-05 15:29:33 -07002739 path: path_t
BNMetricsb9427072018-11-02 15:20:19 +00002740 Path to be tested; can be string, bytes, or a path-like object.
Larry Hastings31826802013-10-19 00:09:25 -07002741
2742 mode: int
2743 Operating-system mode bitfield. Can be F_OK to test existence,
2744 or the inclusive-OR of R_OK, W_OK, and X_OK.
2745
2746 *
2747
Larry Hastings2f936352014-08-05 14:04:04 +10002748 dir_fd : dir_fd(requires='faccessat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002749 If not None, it should be a file descriptor open to a directory,
2750 and path should be relative; path will then be relative to that
2751 directory.
2752
2753 effective_ids: bool = False
2754 If True, access will use the effective uid/gid instead of
2755 the real uid/gid.
2756
2757 follow_symlinks: bool = True
2758 If False, and the last element of the path is a symbolic link,
2759 access will examine the symbolic link itself instead of the file
2760 the link points to.
2761
2762Use the real uid/gid to test for access to a path.
2763
2764{parameters}
2765dir_fd, effective_ids, and follow_symlinks may not be implemented
2766 on your platform. If they are unavailable, using them will raise a
2767 NotImplementedError.
2768
2769Note that most operations will use the effective uid/gid, therefore this
2770 routine can be used in a suid/sgid environment to test if the invoking user
2771 has the specified access to the path.
2772
Larry Hastings61272b72014-01-07 12:41:53 -08002773[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002774
Larry Hastings2f936352014-08-05 14:04:04 +10002775static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002776os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002777 int effective_ids, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002778/*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
Larry Hastings31826802013-10-19 00:09:25 -07002779{
Larry Hastings2f936352014-08-05 14:04:04 +10002780 int return_value;
Victor Stinner8c62be82010-05-06 00:08:46 +00002781
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002782#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002783 DWORD attr;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002784#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07002785 int result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002786#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07002787
Larry Hastings9cf065c2012-06-22 16:30:09 -07002788#ifndef HAVE_FACCESSAT
2789 if (follow_symlinks_specified("access", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002790 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002791
2792 if (effective_ids) {
2793 argument_unavailable_error("access", "effective_ids");
Larry Hastings2f936352014-08-05 14:04:04 +10002794 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002795 }
2796#endif
2797
2798#ifdef MS_WINDOWS
2799 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002800 attr = GetFileAttributesW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002801 Py_END_ALLOW_THREADS
2802
2803 /*
Georg Brandlf7875592012-06-24 13:58:31 +02002804 * Access is possible if
Larry Hastings9cf065c2012-06-22 16:30:09 -07002805 * * we didn't get a -1, and
2806 * * write access wasn't requested,
2807 * * or the file isn't read-only,
2808 * * or it's a directory.
2809 * (Directories cannot be read-only on Windows.)
2810 */
Larry Hastings2f936352014-08-05 14:04:04 +10002811 return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
Georg Brandl5bb7aa92012-06-23 12:48:40 +02002812 (!(mode & 2) ||
Larry Hastings9cf065c2012-06-22 16:30:09 -07002813 !(attr & FILE_ATTRIBUTE_READONLY) ||
Larry Hastings2f936352014-08-05 14:04:04 +10002814 (attr & FILE_ATTRIBUTE_DIRECTORY));
Larry Hastings9cf065c2012-06-22 16:30:09 -07002815#else
2816
2817 Py_BEGIN_ALLOW_THREADS
2818#ifdef HAVE_FACCESSAT
2819 if ((dir_fd != DEFAULT_DIR_FD) ||
2820 effective_ids ||
2821 !follow_symlinks) {
2822 int flags = 0;
2823 if (!follow_symlinks)
2824 flags |= AT_SYMLINK_NOFOLLOW;
2825 if (effective_ids)
2826 flags |= AT_EACCESS;
Larry Hastings31826802013-10-19 00:09:25 -07002827 result = faccessat(dir_fd, path->narrow, mode, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002828 }
2829 else
2830#endif
Larry Hastings31826802013-10-19 00:09:25 -07002831 result = access(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002832 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10002833 return_value = !result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002834#endif
2835
Larry Hastings9cf065c2012-06-22 16:30:09 -07002836 return return_value;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002837}
2838
Guido van Rossumd371ff11999-01-25 16:12:23 +00002839#ifndef F_OK
2840#define F_OK 0
2841#endif
2842#ifndef R_OK
2843#define R_OK 4
2844#endif
2845#ifndef W_OK
2846#define W_OK 2
2847#endif
2848#ifndef X_OK
2849#define X_OK 1
2850#endif
2851
Larry Hastings31826802013-10-19 00:09:25 -07002852
Guido van Rossumd371ff11999-01-25 16:12:23 +00002853#ifdef HAVE_TTYNAME
Larry Hastings61272b72014-01-07 12:41:53 -08002854/*[clinic input]
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002855os.ttyname
Larry Hastings31826802013-10-19 00:09:25 -07002856
2857 fd: int
2858 Integer file descriptor handle.
2859
2860 /
2861
2862Return the name of the terminal device connected to 'fd'.
Larry Hastings61272b72014-01-07 12:41:53 -08002863[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002864
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002865static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002866os_ttyname_impl(PyObject *module, int fd)
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002867/*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
Larry Hastings31826802013-10-19 00:09:25 -07002868{
Guido van Rossum94f6f721999-01-06 18:42:14 +00002869
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002870 long size = sysconf(_SC_TTY_NAME_MAX);
2871 if (size == -1) {
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002872 return posix_error();
2873 }
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002874 char *buffer = (char *)PyMem_RawMalloc(size);
2875 if (buffer == NULL) {
2876 return PyErr_NoMemory();
2877 }
2878 int ret = ttyname_r(fd, buffer, size);
2879 if (ret != 0) {
2880 PyMem_RawFree(buffer);
2881 errno = ret;
2882 return posix_error();
2883 }
2884 PyObject *res = PyUnicode_DecodeFSDefault(buffer);
2885 PyMem_RawFree(buffer);
2886 return res;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002887}
Guido van Rossumd371ff11999-01-25 16:12:23 +00002888#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +00002889
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002890#ifdef HAVE_CTERMID
Larry Hastings2f936352014-08-05 14:04:04 +10002891/*[clinic input]
2892os.ctermid
2893
2894Return the name of the controlling terminal for this process.
2895[clinic start generated code]*/
2896
Larry Hastings2f936352014-08-05 14:04:04 +10002897static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002898os_ctermid_impl(PyObject *module)
2899/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002900{
Victor Stinner8c62be82010-05-06 00:08:46 +00002901 char *ret;
2902 char buffer[L_ctermid];
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002903
Greg Wardb48bc172000-03-01 21:51:56 +00002904#ifdef USE_CTERMID_R
Victor Stinner8c62be82010-05-06 00:08:46 +00002905 ret = ctermid_r(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002906#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002907 ret = ctermid(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002908#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002909 if (ret == NULL)
2910 return posix_error();
Victor Stinner5fe6de82010-08-15 09:12:51 +00002911 return PyUnicode_DecodeFSDefault(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002912}
Larry Hastings2f936352014-08-05 14:04:04 +10002913#endif /* HAVE_CTERMID */
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002914
Larry Hastings2f936352014-08-05 14:04:04 +10002915
2916/*[clinic input]
2917os.chdir
2918
2919 path: path_t(allow_fd='PATH_HAVE_FCHDIR')
2920
2921Change the current working directory to the specified path.
2922
2923path may always be specified as a string.
2924On some platforms, path may also be specified as an open file descriptor.
2925 If this functionality is unavailable, using it raises an exception.
2926[clinic start generated code]*/
2927
Larry Hastings2f936352014-08-05 14:04:04 +10002928static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002929os_chdir_impl(PyObject *module, path_t *path)
2930/*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002931{
2932 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002933
2934 Py_BEGIN_ALLOW_THREADS
2935#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07002936 /* on unix, success = 0, on windows, success = !0 */
2937 result = !win32_wchdir(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002938#else
2939#ifdef HAVE_FCHDIR
Larry Hastings2f936352014-08-05 14:04:04 +10002940 if (path->fd != -1)
2941 result = fchdir(path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002942 else
2943#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002944 result = chdir(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002945#endif
2946 Py_END_ALLOW_THREADS
2947
2948 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002949 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002950 }
2951
Larry Hastings2f936352014-08-05 14:04:04 +10002952 Py_RETURN_NONE;
2953}
2954
2955
2956#ifdef HAVE_FCHDIR
2957/*[clinic input]
2958os.fchdir
2959
2960 fd: fildes
2961
2962Change to the directory of the given file descriptor.
2963
2964fd must be opened on a directory, not a file.
2965Equivalent to os.chdir(fd).
2966
2967[clinic start generated code]*/
2968
Fred Drake4d1e64b2002-04-15 19:40:07 +00002969static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002970os_fchdir_impl(PyObject *module, int fd)
2971/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
Fred Drake4d1e64b2002-04-15 19:40:07 +00002972{
Larry Hastings2f936352014-08-05 14:04:04 +10002973 return posix_fildes_fd(fd, fchdir);
Fred Drake4d1e64b2002-04-15 19:40:07 +00002974}
2975#endif /* HAVE_FCHDIR */
2976
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00002977
Larry Hastings2f936352014-08-05 14:04:04 +10002978/*[clinic input]
2979os.chmod
2980
2981 path: path_t(allow_fd='PATH_HAVE_FCHMOD')
BNMetricsb9427072018-11-02 15:20:19 +00002982 Path to be modified. May always be specified as a str, bytes, or a path-like object.
Larry Hastings2f936352014-08-05 14:04:04 +10002983 On some platforms, path may also be specified as an open file descriptor.
2984 If this functionality is unavailable, using it raises an exception.
2985
2986 mode: int
2987 Operating-system mode bitfield.
2988
2989 *
2990
2991 dir_fd : dir_fd(requires='fchmodat') = None
2992 If not None, it should be a file descriptor open to a directory,
2993 and path should be relative; path will then be relative to that
2994 directory.
2995
2996 follow_symlinks: bool = True
2997 If False, and the last element of the path is a symbolic link,
2998 chmod will modify the symbolic link itself instead of the file
2999 the link points to.
3000
3001Change the access permissions of a file.
3002
3003It is an error to use dir_fd or follow_symlinks when specifying path as
3004 an open file descriptor.
3005dir_fd and follow_symlinks may not be implemented on your platform.
3006 If they are unavailable, using them will raise a NotImplementedError.
3007
3008[clinic start generated code]*/
3009
Larry Hastings2f936352014-08-05 14:04:04 +10003010static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003011os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003012 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003013/*[clinic end generated code: output=5cf6a94915cc7bff input=989081551c00293b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003014{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003015 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003016
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003017#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003018 DWORD attr;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003019#endif
Hirokazu Yamamoto892a37a2009-06-28 11:07:03 +00003020
Larry Hastings9cf065c2012-06-22 16:30:09 -07003021#ifdef HAVE_FCHMODAT
3022 int fchmodat_nofollow_unsupported = 0;
3023#endif
3024
Larry Hastings9cf065c2012-06-22 16:30:09 -07003025#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
3026 if (follow_symlinks_specified("chmod", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003027 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003028#endif
3029
3030#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003031 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003032 attr = GetFileAttributesW(path->wide);
Tim Golden23005082013-10-25 11:22:37 +01003033 if (attr == INVALID_FILE_ATTRIBUTES)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003034 result = 0;
3035 else {
3036 if (mode & _S_IWRITE)
Victor Stinner8c62be82010-05-06 00:08:46 +00003037 attr &= ~FILE_ATTRIBUTE_READONLY;
3038 else
3039 attr |= FILE_ATTRIBUTE_READONLY;
Steve Dowercc16be82016-09-08 10:35:16 -07003040 result = SetFileAttributesW(path->wide, attr);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003041 }
3042 Py_END_ALLOW_THREADS
3043
3044 if (!result) {
Larry Hastings2f936352014-08-05 14:04:04 +10003045 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003046 }
3047#else /* MS_WINDOWS */
3048 Py_BEGIN_ALLOW_THREADS
3049#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003050 if (path->fd != -1)
3051 result = fchmod(path->fd, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003052 else
3053#endif
3054#ifdef HAVE_LCHMOD
3055 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003056 result = lchmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003057 else
3058#endif
3059#ifdef HAVE_FCHMODAT
3060 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
3061 /*
3062 * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
3063 * The documentation specifically shows how to use it,
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003064 * and then says it isn't implemented yet.
3065 * (true on linux with glibc 2.15, and openindiana 3.x)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003066 *
3067 * Once it is supported, os.chmod will automatically
3068 * support dir_fd and follow_symlinks=False. (Hopefully.)
3069 * Until then, we need to be careful what exception we raise.
3070 */
Larry Hastings2f936352014-08-05 14:04:04 +10003071 result = fchmodat(dir_fd, path->narrow, mode,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003072 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3073 /*
3074 * But wait! We can't throw the exception without allowing threads,
3075 * and we can't do that in this nested scope. (Macro trickery, sigh.)
3076 */
3077 fchmodat_nofollow_unsupported =
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003078 result &&
3079 ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
3080 !follow_symlinks;
Victor Stinner8c62be82010-05-06 00:08:46 +00003081 }
3082 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00003083#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003084 result = chmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003085 Py_END_ALLOW_THREADS
3086
3087 if (result) {
3088#ifdef HAVE_FCHMODAT
3089 if (fchmodat_nofollow_unsupported) {
3090 if (dir_fd != DEFAULT_DIR_FD)
3091 dir_fd_and_follow_symlinks_invalid("chmod",
3092 dir_fd, follow_symlinks);
3093 else
3094 follow_symlinks_specified("chmod", follow_symlinks);
Anthony Sottile233ef242017-12-14 08:57:55 -08003095 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003096 }
3097 else
3098#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003099 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003100 }
3101#endif
3102
Larry Hastings2f936352014-08-05 14:04:04 +10003103 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003104}
3105
Larry Hastings9cf065c2012-06-22 16:30:09 -07003106
Christian Heimes4e30a842007-11-30 22:12:06 +00003107#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003108/*[clinic input]
3109os.fchmod
3110
3111 fd: int
3112 mode: int
3113
3114Change the access permissions of the file given by file descriptor fd.
3115
3116Equivalent to os.chmod(fd, mode).
3117[clinic start generated code]*/
3118
Larry Hastings2f936352014-08-05 14:04:04 +10003119static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003120os_fchmod_impl(PyObject *module, int fd, int mode)
3121/*[clinic end generated code: output=afd9bc05b4e426b3 input=8ab11975ca01ee5b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003122{
3123 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003124 int async_err = 0;
3125
3126 do {
3127 Py_BEGIN_ALLOW_THREADS
3128 res = fchmod(fd, mode);
3129 Py_END_ALLOW_THREADS
3130 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3131 if (res != 0)
3132 return (!async_err) ? posix_error() : NULL;
3133
Victor Stinner8c62be82010-05-06 00:08:46 +00003134 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003135}
3136#endif /* HAVE_FCHMOD */
3137
Larry Hastings2f936352014-08-05 14:04:04 +10003138
Christian Heimes4e30a842007-11-30 22:12:06 +00003139#ifdef HAVE_LCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003140/*[clinic input]
3141os.lchmod
3142
3143 path: path_t
3144 mode: int
3145
3146Change the access permissions of a file, without following symbolic links.
3147
3148If path is a symlink, this affects the link itself rather than the target.
3149Equivalent to chmod(path, mode, follow_symlinks=False)."
3150[clinic start generated code]*/
3151
Larry Hastings2f936352014-08-05 14:04:04 +10003152static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003153os_lchmod_impl(PyObject *module, path_t *path, int mode)
3154/*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003155{
Victor Stinner8c62be82010-05-06 00:08:46 +00003156 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003157 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003158 res = lchmod(path->narrow, mode);
Victor Stinner8c62be82010-05-06 00:08:46 +00003159 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003160 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003161 path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003162 return NULL;
3163 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003164 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003165}
3166#endif /* HAVE_LCHMOD */
3167
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003168
Thomas Wouterscf297e42007-02-23 15:07:44 +00003169#ifdef HAVE_CHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003170/*[clinic input]
3171os.chflags
3172
3173 path: path_t
3174 flags: unsigned_long(bitwise=True)
3175 follow_symlinks: bool=True
3176
3177Set file flags.
3178
3179If follow_symlinks is False, and the last element of the path is a symbolic
3180 link, chflags will change flags on the symbolic link itself instead of the
3181 file the link points to.
3182follow_symlinks may not be implemented on your platform. If it is
3183unavailable, using it will raise a NotImplementedError.
3184
3185[clinic start generated code]*/
3186
Larry Hastings2f936352014-08-05 14:04:04 +10003187static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003188os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
Larry Hastings89964c42015-04-14 18:07:59 -04003189 int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003190/*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003191{
3192 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003193
3194#ifndef HAVE_LCHFLAGS
3195 if (follow_symlinks_specified("chflags", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003196 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003197#endif
3198
Victor Stinner8c62be82010-05-06 00:08:46 +00003199 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003200#ifdef HAVE_LCHFLAGS
3201 if (!follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +10003202 result = lchflags(path->narrow, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003203 else
3204#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003205 result = chflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003206 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003207
Larry Hastings2f936352014-08-05 14:04:04 +10003208 if (result)
3209 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003210
Larry Hastings2f936352014-08-05 14:04:04 +10003211 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003212}
3213#endif /* HAVE_CHFLAGS */
3214
Larry Hastings2f936352014-08-05 14:04:04 +10003215
Thomas Wouterscf297e42007-02-23 15:07:44 +00003216#ifdef HAVE_LCHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003217/*[clinic input]
3218os.lchflags
3219
3220 path: path_t
3221 flags: unsigned_long(bitwise=True)
3222
3223Set file flags.
3224
3225This function will not follow symbolic links.
3226Equivalent to chflags(path, flags, follow_symlinks=False).
3227[clinic start generated code]*/
3228
Larry Hastings2f936352014-08-05 14:04:04 +10003229static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003230os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
3231/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003232{
Victor Stinner8c62be82010-05-06 00:08:46 +00003233 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003234 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003235 res = lchflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003236 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003237 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003238 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003239 }
Victor Stinner292c8352012-10-30 02:17:38 +01003240 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003241}
3242#endif /* HAVE_LCHFLAGS */
3243
Larry Hastings2f936352014-08-05 14:04:04 +10003244
Martin v. Löwis244edc82001-10-04 22:44:26 +00003245#ifdef HAVE_CHROOT
Larry Hastings2f936352014-08-05 14:04:04 +10003246/*[clinic input]
3247os.chroot
3248 path: path_t
3249
3250Change root directory to path.
3251
3252[clinic start generated code]*/
3253
Larry Hastings2f936352014-08-05 14:04:04 +10003254static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003255os_chroot_impl(PyObject *module, path_t *path)
3256/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003257{
3258 int res;
3259 Py_BEGIN_ALLOW_THREADS
3260 res = chroot(path->narrow);
3261 Py_END_ALLOW_THREADS
3262 if (res < 0)
3263 return path_error(path);
3264 Py_RETURN_NONE;
3265}
3266#endif /* HAVE_CHROOT */
3267
Martin v. Löwis244edc82001-10-04 22:44:26 +00003268
Guido van Rossum21142a01999-01-08 21:05:37 +00003269#ifdef HAVE_FSYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003270/*[clinic input]
3271os.fsync
3272
3273 fd: fildes
3274
3275Force write of fd to disk.
3276[clinic start generated code]*/
3277
Larry Hastings2f936352014-08-05 14:04:04 +10003278static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003279os_fsync_impl(PyObject *module, int fd)
3280/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003281{
3282 return posix_fildes_fd(fd, fsync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003283}
3284#endif /* HAVE_FSYNC */
3285
Larry Hastings2f936352014-08-05 14:04:04 +10003286
Ross Lagerwall7807c352011-03-17 20:20:30 +02003287#ifdef HAVE_SYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003288/*[clinic input]
3289os.sync
3290
3291Force write of everything to disk.
3292[clinic start generated code]*/
3293
Larry Hastings2f936352014-08-05 14:04:04 +10003294static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003295os_sync_impl(PyObject *module)
3296/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
Ross Lagerwall7807c352011-03-17 20:20:30 +02003297{
3298 Py_BEGIN_ALLOW_THREADS
3299 sync();
3300 Py_END_ALLOW_THREADS
3301 Py_RETURN_NONE;
3302}
Larry Hastings2f936352014-08-05 14:04:04 +10003303#endif /* HAVE_SYNC */
3304
Ross Lagerwall7807c352011-03-17 20:20:30 +02003305
Guido van Rossum21142a01999-01-08 21:05:37 +00003306#ifdef HAVE_FDATASYNC
Guido van Rossum7f58e2e2000-09-22 17:26:14 +00003307#ifdef __hpux
Guido van Rossumecc23b02000-09-22 16:01:05 +00003308extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
3309#endif
3310
Larry Hastings2f936352014-08-05 14:04:04 +10003311/*[clinic input]
3312os.fdatasync
3313
3314 fd: fildes
3315
3316Force write of fd to disk without forcing update of metadata.
3317[clinic start generated code]*/
3318
Larry Hastings2f936352014-08-05 14:04:04 +10003319static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003320os_fdatasync_impl(PyObject *module, int fd)
3321/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003322{
3323 return posix_fildes_fd(fd, fdatasync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003324}
3325#endif /* HAVE_FDATASYNC */
3326
3327
Fredrik Lundh10723342000-07-10 16:38:09 +00003328#ifdef HAVE_CHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003329/*[clinic input]
3330os.chown
3331
3332 path : path_t(allow_fd='PATH_HAVE_FCHOWN')
BNMetricsb9427072018-11-02 15:20:19 +00003333 Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
Larry Hastings2f936352014-08-05 14:04:04 +10003334
3335 uid: uid_t
3336
3337 gid: gid_t
3338
3339 *
3340
3341 dir_fd : dir_fd(requires='fchownat') = None
3342 If not None, it should be a file descriptor open to a directory,
3343 and path should be relative; path will then be relative to that
3344 directory.
3345
3346 follow_symlinks: bool = True
3347 If False, and the last element of the path is a symbolic link,
3348 stat will examine the symbolic link itself instead of the file
3349 the link points to.
3350
3351Change the owner and group id of path to the numeric uid and gid.\
3352
3353path may always be specified as a string.
3354On some platforms, path may also be specified as an open file descriptor.
3355 If this functionality is unavailable, using it raises an exception.
3356If dir_fd is not None, it should be a file descriptor open to a directory,
3357 and path should be relative; path will then be relative to that directory.
3358If follow_symlinks is False, and the last element of the path is a symbolic
3359 link, chown will modify the symbolic link itself instead of the file the
3360 link points to.
3361It is an error to use dir_fd or follow_symlinks when specifying path as
3362 an open file descriptor.
3363dir_fd and follow_symlinks may not be implemented on your platform.
3364 If they are unavailable, using them will raise a NotImplementedError.
3365
3366[clinic start generated code]*/
3367
Larry Hastings2f936352014-08-05 14:04:04 +10003368static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003369os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
Larry Hastings89964c42015-04-14 18:07:59 -04003370 int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003371/*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003372{
3373 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003374
3375#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
3376 if (follow_symlinks_specified("chown", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003377 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003378#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003379 if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
3380 fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
3381 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003382
3383#ifdef __APPLE__
3384 /*
3385 * This is for Mac OS X 10.3, which doesn't have lchown.
3386 * (But we still have an lchown symbol because of weak-linking.)
3387 * It doesn't have fchownat either. So there's no possibility
3388 * of a graceful failover.
Georg Brandlf7875592012-06-24 13:58:31 +02003389 */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003390 if ((!follow_symlinks) && (lchown == NULL)) {
3391 follow_symlinks_specified("chown", follow_symlinks);
Larry Hastings2f936352014-08-05 14:04:04 +10003392 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003393 }
3394#endif
3395
Victor Stinner8c62be82010-05-06 00:08:46 +00003396 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003397#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003398 if (path->fd != -1)
3399 result = fchown(path->fd, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003400 else
3401#endif
3402#ifdef HAVE_LCHOWN
3403 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003404 result = lchown(path->narrow, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003405 else
3406#endif
3407#ifdef HAVE_FCHOWNAT
3408 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003409 result = fchownat(dir_fd, path->narrow, uid, gid,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003410 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3411 else
3412#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003413 result = chown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003414 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003415
Larry Hastings2f936352014-08-05 14:04:04 +10003416 if (result)
3417 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003418
Larry Hastings2f936352014-08-05 14:04:04 +10003419 Py_RETURN_NONE;
Guido van Rossumb6775db1994-08-01 11:34:53 +00003420}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003421#endif /* HAVE_CHOWN */
Guido van Rossumb6775db1994-08-01 11:34:53 +00003422
Larry Hastings2f936352014-08-05 14:04:04 +10003423
Christian Heimes4e30a842007-11-30 22:12:06 +00003424#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003425/*[clinic input]
3426os.fchown
3427
3428 fd: int
3429 uid: uid_t
3430 gid: gid_t
3431
3432Change the owner and group id of the file specified by file descriptor.
3433
3434Equivalent to os.chown(fd, uid, gid).
3435
3436[clinic start generated code]*/
3437
Larry Hastings2f936352014-08-05 14:04:04 +10003438static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003439os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
3440/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003441{
Victor Stinner8c62be82010-05-06 00:08:46 +00003442 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003443 int async_err = 0;
3444
3445 do {
3446 Py_BEGIN_ALLOW_THREADS
3447 res = fchown(fd, uid, gid);
3448 Py_END_ALLOW_THREADS
3449 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3450 if (res != 0)
3451 return (!async_err) ? posix_error() : NULL;
3452
Victor Stinner8c62be82010-05-06 00:08:46 +00003453 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003454}
3455#endif /* HAVE_FCHOWN */
3456
Larry Hastings2f936352014-08-05 14:04:04 +10003457
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003458#ifdef HAVE_LCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003459/*[clinic input]
3460os.lchown
3461
3462 path : path_t
3463 uid: uid_t
3464 gid: gid_t
3465
3466Change the owner and group id of path to the numeric uid and gid.
3467
3468This function will not follow symbolic links.
3469Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
3470[clinic start generated code]*/
3471
Larry Hastings2f936352014-08-05 14:04:04 +10003472static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003473os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
3474/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003475{
Victor Stinner8c62be82010-05-06 00:08:46 +00003476 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003477 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10003478 res = lchown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003479 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003480 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003481 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003482 }
Larry Hastings2f936352014-08-05 14:04:04 +10003483 Py_RETURN_NONE;
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003484}
3485#endif /* HAVE_LCHOWN */
3486
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003487
Barry Warsaw53699e91996-12-10 23:23:01 +00003488static PyObject *
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003489posix_getcwd(int use_bytes)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003490{
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003491#ifdef MS_WINDOWS
Victor Stinner689830e2019-06-26 17:31:12 +02003492 wchar_t wbuf[MAXPATHLEN];
3493 wchar_t *wbuf2 = wbuf;
3494 DWORD len;
3495
3496 Py_BEGIN_ALLOW_THREADS
3497 len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
3498 /* If the buffer is large enough, len does not include the
3499 terminating \0. If the buffer is too small, len includes
3500 the space needed for the terminator. */
3501 if (len >= Py_ARRAY_LENGTH(wbuf)) {
Victor Stinnerec3e20a2019-06-28 18:01:59 +02003502 if (len <= PY_SSIZE_T_MAX / sizeof(wchar_t)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02003503 wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00003504 }
Victor Stinner689830e2019-06-26 17:31:12 +02003505 else {
3506 wbuf2 = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003507 }
Victor Stinner689830e2019-06-26 17:31:12 +02003508 if (wbuf2) {
3509 len = GetCurrentDirectoryW(len, wbuf2);
Victor Stinner8c62be82010-05-06 00:08:46 +00003510 }
Victor Stinner689830e2019-06-26 17:31:12 +02003511 }
3512 Py_END_ALLOW_THREADS
3513
3514 if (!wbuf2) {
3515 PyErr_NoMemory();
3516 return NULL;
3517 }
3518 if (!len) {
Victor Stinnerb024e842012-10-31 22:24:06 +01003519 if (wbuf2 != wbuf)
Victor Stinnerb6404912013-07-07 16:21:41 +02003520 PyMem_RawFree(wbuf2);
Victor Stinner689830e2019-06-26 17:31:12 +02003521 return PyErr_SetFromWindowsErr(0);
Victor Stinner8c62be82010-05-06 00:08:46 +00003522 }
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01003523
Victor Stinner689830e2019-06-26 17:31:12 +02003524 PyObject *resobj = PyUnicode_FromWideChar(wbuf2, len);
3525 if (wbuf2 != wbuf) {
3526 PyMem_RawFree(wbuf2);
3527 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003528
Victor Stinner689830e2019-06-26 17:31:12 +02003529 if (use_bytes) {
3530 if (resobj == NULL) {
3531 return NULL;
3532 }
3533 Py_SETREF(resobj, PyUnicode_EncodeFSDefault(resobj));
3534 }
3535
3536 return resobj;
3537#else
3538 const size_t chunk = 1024;
3539
3540 char *buf = NULL;
3541 char *cwd = NULL;
3542 size_t buflen = 0;
3543
Victor Stinner8c62be82010-05-06 00:08:46 +00003544 Py_BEGIN_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003545 do {
Victor Stinner689830e2019-06-26 17:31:12 +02003546 char *newbuf;
3547 if (buflen <= PY_SSIZE_T_MAX - chunk) {
3548 buflen += chunk;
3549 newbuf = PyMem_RawRealloc(buf, buflen);
3550 }
3551 else {
3552 newbuf = NULL;
3553 }
3554 if (newbuf == NULL) {
3555 PyMem_RawFree(buf);
3556 buf = NULL;
Victor Stinnerc44f7072016-03-14 18:07:53 +01003557 break;
3558 }
Victor Stinner689830e2019-06-26 17:31:12 +02003559 buf = newbuf;
Victor Stinner4403d7d2015-04-25 00:16:10 +02003560
Victor Stinner4403d7d2015-04-25 00:16:10 +02003561 cwd = getcwd(buf, buflen);
3562 } while (cwd == NULL && errno == ERANGE);
Victor Stinner8c62be82010-05-06 00:08:46 +00003563 Py_END_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003564
Victor Stinner689830e2019-06-26 17:31:12 +02003565 if (buf == NULL) {
3566 return PyErr_NoMemory();
3567 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003568 if (cwd == NULL) {
3569 PyMem_RawFree(buf);
Victor Stinner8c62be82010-05-06 00:08:46 +00003570 return posix_error();
Victor Stinner4403d7d2015-04-25 00:16:10 +02003571 }
3572
Victor Stinner689830e2019-06-26 17:31:12 +02003573 PyObject *obj;
3574 if (use_bytes) {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003575 obj = PyBytes_FromStringAndSize(buf, strlen(buf));
Victor Stinner689830e2019-06-26 17:31:12 +02003576 }
3577 else {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003578 obj = PyUnicode_DecodeFSDefault(buf);
Victor Stinner689830e2019-06-26 17:31:12 +02003579 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003580 PyMem_RawFree(buf);
3581
3582 return obj;
Victor Stinner689830e2019-06-26 17:31:12 +02003583#endif /* !MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003584}
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003585
Larry Hastings2f936352014-08-05 14:04:04 +10003586
3587/*[clinic input]
3588os.getcwd
3589
3590Return a unicode string representing the current working directory.
3591[clinic start generated code]*/
3592
Larry Hastings2f936352014-08-05 14:04:04 +10003593static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003594os_getcwd_impl(PyObject *module)
3595/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003596{
3597 return posix_getcwd(0);
3598}
3599
Larry Hastings2f936352014-08-05 14:04:04 +10003600
3601/*[clinic input]
3602os.getcwdb
3603
3604Return a bytes string representing the current working directory.
3605[clinic start generated code]*/
3606
Larry Hastings2f936352014-08-05 14:04:04 +10003607static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003608os_getcwdb_impl(PyObject *module)
3609/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003610{
3611 return posix_getcwd(1);
3612}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003613
Larry Hastings2f936352014-08-05 14:04:04 +10003614
Larry Hastings9cf065c2012-06-22 16:30:09 -07003615#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
3616#define HAVE_LINK 1
3617#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003618
Guido van Rossumb6775db1994-08-01 11:34:53 +00003619#ifdef HAVE_LINK
Larry Hastings2f936352014-08-05 14:04:04 +10003620/*[clinic input]
3621
3622os.link
3623
3624 src : path_t
3625 dst : path_t
3626 *
3627 src_dir_fd : dir_fd = None
3628 dst_dir_fd : dir_fd = None
3629 follow_symlinks: bool = True
3630
3631Create a hard link to a file.
3632
3633If either src_dir_fd or dst_dir_fd is not None, it should be a file
3634 descriptor open to a directory, and the respective path string (src or dst)
3635 should be relative; the path will then be relative to that directory.
3636If follow_symlinks is False, and the last element of src is a symbolic
3637 link, link will create a link to the symbolic link itself instead of the
3638 file the link points to.
3639src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
3640 platform. If they are unavailable, using them will raise a
3641 NotImplementedError.
3642[clinic start generated code]*/
3643
Larry Hastings2f936352014-08-05 14:04:04 +10003644static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003645os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003646 int dst_dir_fd, int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003647/*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003648{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003649#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07003650 BOOL result = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003651#else
3652 int result;
3653#endif
3654
Larry Hastings9cf065c2012-06-22 16:30:09 -07003655#ifndef HAVE_LINKAT
3656 if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
3657 argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10003658 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003659 }
3660#endif
3661
Steve Dowercc16be82016-09-08 10:35:16 -07003662#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10003663 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003664 PyErr_SetString(PyExc_NotImplementedError,
3665 "link: src and dst must be the same type");
Larry Hastings2f936352014-08-05 14:04:04 +10003666 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003667 }
Steve Dowercc16be82016-09-08 10:35:16 -07003668#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003669
Brian Curtin1b9df392010-11-24 20:24:31 +00003670#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003671 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08003672 result = CreateHardLinkW(dst->wide, src->wide, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003673 Py_END_ALLOW_THREADS
Brian Curtin1b9df392010-11-24 20:24:31 +00003674
Larry Hastings2f936352014-08-05 14:04:04 +10003675 if (!result)
3676 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003677#else
3678 Py_BEGIN_ALLOW_THREADS
Larry Hastings67cbf7b2012-06-22 17:06:48 -07003679#ifdef HAVE_LINKAT
Larry Hastings9cf065c2012-06-22 16:30:09 -07003680 if ((src_dir_fd != DEFAULT_DIR_FD) ||
3681 (dst_dir_fd != DEFAULT_DIR_FD) ||
3682 (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003683 result = linkat(src_dir_fd, src->narrow,
3684 dst_dir_fd, dst->narrow,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003685 follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
3686 else
Steve Dowercc16be82016-09-08 10:35:16 -07003687#endif /* HAVE_LINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10003688 result = link(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003689 Py_END_ALLOW_THREADS
Brian Curtinfc889c42010-11-28 23:59:46 +00003690
Larry Hastings2f936352014-08-05 14:04:04 +10003691 if (result)
3692 return path_error2(src, dst);
Steve Dowercc16be82016-09-08 10:35:16 -07003693#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003694
Larry Hastings2f936352014-08-05 14:04:04 +10003695 Py_RETURN_NONE;
Brian Curtin1b9df392010-11-24 20:24:31 +00003696}
Larry Hastings9cf065c2012-06-22 16:30:09 -07003697#endif
3698
Brian Curtin1b9df392010-11-24 20:24:31 +00003699
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003700#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
Barry Warsaw53699e91996-12-10 23:23:01 +00003701static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003702_listdir_windows_no_opendir(path_t *path, PyObject *list)
Guido van Rossumb6775db1994-08-01 11:34:53 +00003703{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003704 PyObject *v;
3705 HANDLE hFindFile = INVALID_HANDLE_VALUE;
3706 BOOL result;
Steve Dowercc16be82016-09-08 10:35:16 -07003707 wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003708 /* only claim to have space for MAX_PATH */
Victor Stinner75875072013-11-24 19:23:25 +01003709 Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003710 wchar_t *wnamebuf = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003711
Steve Dowercc16be82016-09-08 10:35:16 -07003712 WIN32_FIND_DATAW wFileData;
3713 const wchar_t *po_wchars;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003714
Steve Dowercc16be82016-09-08 10:35:16 -07003715 if (!path->wide) { /* Default arg: "." */
3716 po_wchars = L".";
3717 len = 1;
3718 } else {
3719 po_wchars = path->wide;
3720 len = wcslen(path->wide);
3721 }
3722 /* The +5 is so we can append "\\*.*\0" */
3723 wnamebuf = PyMem_New(wchar_t, len + 5);
3724 if (!wnamebuf) {
3725 PyErr_NoMemory();
Larry Hastings9cf065c2012-06-22 16:30:09 -07003726 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003727 }
Steve Dowercc16be82016-09-08 10:35:16 -07003728 wcscpy(wnamebuf, po_wchars);
Victor Stinner8c62be82010-05-06 00:08:46 +00003729 if (len > 0) {
Steve Dowercc16be82016-09-08 10:35:16 -07003730 wchar_t wch = wnamebuf[len-1];
3731 if (wch != SEP && wch != ALTSEP && wch != L':')
3732 wnamebuf[len++] = SEP;
3733 wcscpy(wnamebuf + len, L"*.*");
Victor Stinner8c62be82010-05-06 00:08:46 +00003734 }
Steve Dowercc16be82016-09-08 10:35:16 -07003735 if ((list = PyList_New(0)) == NULL) {
3736 goto exit;
3737 }
Antoine Pitroub73caab2010-08-09 23:39:31 +00003738 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003739 hFindFile = FindFirstFileW(wnamebuf, &wFileData);
Antoine Pitroub73caab2010-08-09 23:39:31 +00003740 Py_END_ALLOW_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +00003741 if (hFindFile == INVALID_HANDLE_VALUE) {
3742 int error = GetLastError();
3743 if (error == ERROR_FILE_NOT_FOUND)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003744 goto exit;
3745 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003746 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003747 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003748 }
3749 do {
3750 /* Skip over . and .. */
Steve Dowercc16be82016-09-08 10:35:16 -07003751 if (wcscmp(wFileData.cFileName, L".") != 0 &&
3752 wcscmp(wFileData.cFileName, L"..") != 0) {
3753 v = PyUnicode_FromWideChar(wFileData.cFileName,
3754 wcslen(wFileData.cFileName));
3755 if (path->narrow && v) {
3756 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3757 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003758 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003759 Py_DECREF(list);
3760 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003761 break;
3762 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003763 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003764 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003765 Py_DECREF(list);
3766 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003767 break;
3768 }
3769 Py_DECREF(v);
3770 }
3771 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003772 result = FindNextFileW(hFindFile, &wFileData);
Victor Stinner8c62be82010-05-06 00:08:46 +00003773 Py_END_ALLOW_THREADS
3774 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
3775 it got to the end of the directory. */
3776 if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003777 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003778 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003779 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003780 }
3781 } while (result == TRUE);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003782
Larry Hastings9cf065c2012-06-22 16:30:09 -07003783exit:
3784 if (hFindFile != INVALID_HANDLE_VALUE) {
3785 if (FindClose(hFindFile) == FALSE) {
3786 if (list != NULL) {
3787 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003788 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003789 }
3790 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003791 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003792 PyMem_Free(wnamebuf);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003793
Larry Hastings9cf065c2012-06-22 16:30:09 -07003794 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003795} /* end of _listdir_windows_no_opendir */
3796
3797#else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
3798
3799static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003800_posix_listdir(path_t *path, PyObject *list)
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003801{
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003802 PyObject *v;
3803 DIR *dirp = NULL;
3804 struct dirent *ep;
3805 int return_str; /* if false, return bytes */
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003806#ifdef HAVE_FDOPENDIR
3807 int fd = -1;
3808#endif
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003809
Victor Stinner8c62be82010-05-06 00:08:46 +00003810 errno = 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003811#ifdef HAVE_FDOPENDIR
Gregory P. Smith40a21602013-03-20 20:52:50 -07003812 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003813 /* closedir() closes the FD, so we duplicate it */
Victor Stinnerdaf45552013-08-28 00:53:59 +02003814 fd = _Py_dup(path->fd);
Victor Stinnerf3266652013-12-19 13:24:49 +01003815 if (fd == -1)
3816 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003817
Larry Hastingsfdaea062012-06-25 04:42:23 -07003818 return_str = 1;
3819
Larry Hastings9cf065c2012-06-22 16:30:09 -07003820 Py_BEGIN_ALLOW_THREADS
3821 dirp = fdopendir(fd);
3822 Py_END_ALLOW_THREADS
3823 }
3824 else
3825#endif
3826 {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003827 const char *name;
Gregory P. Smith40a21602013-03-20 20:52:50 -07003828 if (path->narrow) {
3829 name = path->narrow;
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03003830 /* only return bytes if they specified a bytes-like object */
3831 return_str = !PyObject_CheckBuffer(path->object);
Larry Hastingsfdaea062012-06-25 04:42:23 -07003832 }
3833 else {
3834 name = ".";
3835 return_str = 1;
3836 }
3837
Larry Hastings9cf065c2012-06-22 16:30:09 -07003838 Py_BEGIN_ALLOW_THREADS
3839 dirp = opendir(name);
3840 Py_END_ALLOW_THREADS
3841 }
3842
3843 if (dirp == NULL) {
Gregory P. Smith40a21602013-03-20 20:52:50 -07003844 list = path_error(path);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003845#ifdef HAVE_FDOPENDIR
3846 if (fd != -1) {
3847 Py_BEGIN_ALLOW_THREADS
3848 close(fd);
3849 Py_END_ALLOW_THREADS
3850 }
3851#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003852 goto exit;
3853 }
3854 if ((list = PyList_New(0)) == NULL) {
3855 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003856 }
3857 for (;;) {
3858 errno = 0;
3859 Py_BEGIN_ALLOW_THREADS
3860 ep = readdir(dirp);
3861 Py_END_ALLOW_THREADS
3862 if (ep == NULL) {
3863 if (errno == 0) {
3864 break;
3865 } else {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003866 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003867 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003868 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003869 }
3870 }
3871 if (ep->d_name[0] == '.' &&
3872 (NAMLEN(ep) == 1 ||
3873 (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
3874 continue;
Larry Hastingsfdaea062012-06-25 04:42:23 -07003875 if (return_str)
Victor Stinnera45598a2010-05-14 16:35:39 +00003876 v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
3877 else
3878 v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
Victor Stinner8c62be82010-05-06 00:08:46 +00003879 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003880 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003881 break;
3882 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003883 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003884 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003885 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003886 break;
3887 }
3888 Py_DECREF(v);
3889 }
Guido van Rossum0ee42cd1991-04-08 21:01:03 +00003890
Larry Hastings9cf065c2012-06-22 16:30:09 -07003891exit:
3892 if (dirp != NULL) {
3893 Py_BEGIN_ALLOW_THREADS
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003894#ifdef HAVE_FDOPENDIR
Larry Hastings9cf065c2012-06-22 16:30:09 -07003895 if (fd > -1)
3896 rewinddir(dirp);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003897#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003898 closedir(dirp);
3899 Py_END_ALLOW_THREADS
3900 }
3901
Larry Hastings9cf065c2012-06-22 16:30:09 -07003902 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003903} /* end of _posix_listdir */
3904#endif /* which OS */
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003905
Larry Hastings2f936352014-08-05 14:04:04 +10003906
3907/*[clinic input]
3908os.listdir
3909
3910 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
3911
3912Return a list containing the names of the files in the directory.
3913
BNMetricsb9427072018-11-02 15:20:19 +00003914path can be specified as either str, bytes, or a path-like object. If path is bytes,
Larry Hastings2f936352014-08-05 14:04:04 +10003915 the filenames returned will also be bytes; in all other circumstances
3916 the filenames returned will be str.
3917If path is None, uses the path='.'.
3918On some platforms, path may also be specified as an open file descriptor;\
3919 the file descriptor must refer to a directory.
3920 If this functionality is unavailable, using it raises NotImplementedError.
3921
3922The list is in arbitrary order. It does not include the special
3923entries '.' and '..' even if they are present in the directory.
3924
3925
3926[clinic start generated code]*/
3927
Larry Hastings2f936352014-08-05 14:04:04 +10003928static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003929os_listdir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +00003930/*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003931{
Steve Dower60419a72019-06-24 08:42:54 -07003932 if (PySys_Audit("os.listdir", "O",
3933 path->object ? path->object : Py_None) < 0) {
3934 return NULL;
3935 }
Larry Hastings2f936352014-08-05 14:04:04 +10003936#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
3937 return _listdir_windows_no_opendir(path, NULL);
3938#else
3939 return _posix_listdir(path, NULL);
3940#endif
3941}
3942
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00003943#ifdef MS_WINDOWS
Mark Hammondef8b6542001-05-13 08:04:26 +00003944/* A helper function for abspath on win32 */
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003945/*[clinic input]
3946os._getfullpathname
Victor Stinnereb5657a2011-09-30 01:44:27 +02003947
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003948 path: path_t
3949 /
3950
3951[clinic start generated code]*/
3952
3953static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003954os__getfullpathname_impl(PyObject *module, path_t *path)
3955/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003956{
Victor Stinner3939c322019-06-25 15:02:43 +02003957 wchar_t *abspath;
Victor Stinnereb5657a2011-09-30 01:44:27 +02003958
Victor Stinner3939c322019-06-25 15:02:43 +02003959 /* _Py_abspath() is implemented with GetFullPathNameW() on Windows */
3960 if (_Py_abspath(path->wide, &abspath) < 0) {
3961 return win32_error_object("GetFullPathNameW", path->object);
Victor Stinner8c62be82010-05-06 00:08:46 +00003962 }
Victor Stinner3939c322019-06-25 15:02:43 +02003963 if (abspath == NULL) {
3964 return PyErr_NoMemory();
3965 }
3966
3967 PyObject *str = PyUnicode_FromWideChar(abspath, wcslen(abspath));
3968 PyMem_RawFree(abspath);
3969 if (str == NULL) {
3970 return NULL;
3971 }
3972 if (path->narrow) {
3973 Py_SETREF(str, PyUnicode_EncodeFSDefault(str));
3974 }
3975 return str;
Larry Hastings2f936352014-08-05 14:04:04 +10003976}
Brian Curtind40e6f72010-07-08 21:39:08 +00003977
Brian Curtind25aef52011-06-13 15:16:04 -05003978
Larry Hastings2f936352014-08-05 14:04:04 +10003979/*[clinic input]
3980os._getfinalpathname
Brian Curtinf5e76d02010-11-24 13:14:05 +00003981
Steve Dower23ad6d02018-02-22 10:39:10 -08003982 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10003983 /
3984
3985A helper function for samepath on windows.
3986[clinic start generated code]*/
3987
Larry Hastings2f936352014-08-05 14:04:04 +10003988static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08003989os__getfinalpathname_impl(PyObject *module, path_t *path)
3990/*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
Brian Curtind40e6f72010-07-08 21:39:08 +00003991{
3992 HANDLE hFile;
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003993 wchar_t buf[MAXPATHLEN], *target_path = buf;
3994 int buf_size = Py_ARRAY_LENGTH(buf);
Brian Curtind40e6f72010-07-08 21:39:08 +00003995 int result_length;
Larry Hastings2f936352014-08-05 14:04:04 +10003996 PyObject *result;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003997
Steve Dower23ad6d02018-02-22 10:39:10 -08003998 Py_BEGIN_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00003999 hFile = CreateFileW(
Steve Dower23ad6d02018-02-22 10:39:10 -08004000 path->wide,
Brian Curtind40e6f72010-07-08 21:39:08 +00004001 0, /* desired access */
4002 0, /* share mode */
4003 NULL, /* security attributes */
4004 OPEN_EXISTING,
4005 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
4006 FILE_FLAG_BACKUP_SEMANTICS,
4007 NULL);
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004008 Py_END_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004009
Steve Dower23ad6d02018-02-22 10:39:10 -08004010 if (hFile == INVALID_HANDLE_VALUE) {
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004011 return win32_error_object("CreateFileW", path->object);
Steve Dower23ad6d02018-02-22 10:39:10 -08004012 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004013
4014 /* We have a good handle to the target, use it to determine the
4015 target path name. */
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004016 while (1) {
4017 Py_BEGIN_ALLOW_THREADS
4018 result_length = GetFinalPathNameByHandleW(hFile, target_path,
4019 buf_size, VOLUME_NAME_DOS);
4020 Py_END_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00004021
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004022 if (!result_length) {
4023 result = win32_error_object("GetFinalPathNameByHandleW",
4024 path->object);
4025 goto cleanup;
4026 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004027
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004028 if (result_length < buf_size) {
4029 break;
4030 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004031
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004032 wchar_t *tmp;
4033 tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
4034 result_length * sizeof(*tmp));
4035 if (!tmp) {
4036 result = PyErr_NoMemory();
4037 goto cleanup;
4038 }
4039
4040 buf_size = result_length;
4041 target_path = tmp;
Steve Dower23ad6d02018-02-22 10:39:10 -08004042 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004043
Victor Stinner9d3b93b2011-11-22 02:27:30 +01004044 result = PyUnicode_FromWideChar(target_path, result_length);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004045 if (result && path->narrow) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004046 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004047 }
Steve Dower23ad6d02018-02-22 10:39:10 -08004048
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004049cleanup:
4050 if (target_path != buf) {
4051 PyMem_Free(target_path);
4052 }
4053 CloseHandle(hFile);
4054 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10004055}
Brian Curtin62857742010-09-06 17:07:27 +00004056
Tim Golden6b528062013-08-01 12:44:00 +01004057
Larry Hastings2f936352014-08-05 14:04:04 +10004058/*[clinic input]
4059os._getvolumepathname
4060
Steve Dower23ad6d02018-02-22 10:39:10 -08004061 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10004062
4063A helper function for ismount on Win32.
4064[clinic start generated code]*/
4065
Larry Hastings2f936352014-08-05 14:04:04 +10004066static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08004067os__getvolumepathname_impl(PyObject *module, path_t *path)
4068/*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004069{
4070 PyObject *result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004071 wchar_t *mountpath=NULL;
Victor Stinner6edddfa2013-11-24 19:22:57 +01004072 size_t buflen;
Tim Golden6b528062013-08-01 12:44:00 +01004073 BOOL ret;
4074
Tim Golden6b528062013-08-01 12:44:00 +01004075 /* Volume path should be shorter than entire path */
Steve Dower23ad6d02018-02-22 10:39:10 -08004076 buflen = Py_MAX(path->length, MAX_PATH);
Victor Stinner6edddfa2013-11-24 19:22:57 +01004077
Victor Stinner850a18e2017-10-24 16:53:32 -07004078 if (buflen > PY_DWORD_MAX) {
Victor Stinner6edddfa2013-11-24 19:22:57 +01004079 PyErr_SetString(PyExc_OverflowError, "path too long");
4080 return NULL;
4081 }
4082
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004083 mountpath = PyMem_New(wchar_t, buflen);
Tim Golden6b528062013-08-01 12:44:00 +01004084 if (mountpath == NULL)
4085 return PyErr_NoMemory();
4086
4087 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -08004088 ret = GetVolumePathNameW(path->wide, mountpath,
Victor Stinner6edddfa2013-11-24 19:22:57 +01004089 Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
Tim Golden6b528062013-08-01 12:44:00 +01004090 Py_END_ALLOW_THREADS
4091
4092 if (!ret) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004093 result = win32_error_object("_getvolumepathname", path->object);
Tim Golden6b528062013-08-01 12:44:00 +01004094 goto exit;
4095 }
4096 result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
Steve Dower23ad6d02018-02-22 10:39:10 -08004097 if (path->narrow)
4098 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Tim Golden6b528062013-08-01 12:44:00 +01004099
4100exit:
4101 PyMem_Free(mountpath);
4102 return result;
4103}
Tim Golden6b528062013-08-01 12:44:00 +01004104
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004105#endif /* MS_WINDOWS */
Mark Hammondef8b6542001-05-13 08:04:26 +00004106
Larry Hastings2f936352014-08-05 14:04:04 +10004107
4108/*[clinic input]
4109os.mkdir
4110
4111 path : path_t
4112
4113 mode: int = 0o777
4114
4115 *
4116
4117 dir_fd : dir_fd(requires='mkdirat') = None
4118
4119# "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
4120
4121Create a directory.
4122
4123If dir_fd is not None, it should be a file descriptor open to a directory,
4124 and path should be relative; path will then be relative to that directory.
4125dir_fd may not be implemented on your platform.
4126 If it is unavailable, using it will raise a NotImplementedError.
4127
4128The mode argument is ignored on Windows.
4129[clinic start generated code]*/
4130
Larry Hastings2f936352014-08-05 14:04:04 +10004131static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004132os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
4133/*[clinic end generated code: output=a70446903abe821f input=e965f68377e9b1ce]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004134{
4135 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004136
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004137#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004138 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004139 result = CreateDirectoryW(path->wide, NULL);
Victor Stinner8c62be82010-05-06 00:08:46 +00004140 Py_END_ALLOW_THREADS
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004141
Larry Hastings2f936352014-08-05 14:04:04 +10004142 if (!result)
4143 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004144#else
Victor Stinner8c62be82010-05-06 00:08:46 +00004145 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004146#if HAVE_MKDIRAT
4147 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004148 result = mkdirat(dir_fd, path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004149 else
4150#endif
Erik Bray03eb11f2017-10-27 14:27:06 +02004151#if defined(__WATCOMC__) && !defined(__QNX__)
Larry Hastings2f936352014-08-05 14:04:04 +10004152 result = mkdir(path->narrow);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004153#else
Larry Hastings2f936352014-08-05 14:04:04 +10004154 result = mkdir(path->narrow, mode);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004155#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004156 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004157 if (result < 0)
4158 return path_error(path);
Steve Dowercc16be82016-09-08 10:35:16 -07004159#endif /* MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10004160 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004161}
4162
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004163
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004164/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
4165#if defined(HAVE_SYS_RESOURCE_H)
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004166#include <sys/resource.h>
4167#endif
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004168
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004169
4170#ifdef HAVE_NICE
Larry Hastings2f936352014-08-05 14:04:04 +10004171/*[clinic input]
4172os.nice
4173
4174 increment: int
4175 /
4176
4177Add increment to the priority of process and return the new priority.
4178[clinic start generated code]*/
4179
Larry Hastings2f936352014-08-05 14:04:04 +10004180static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004181os_nice_impl(PyObject *module, int increment)
4182/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004183{
4184 int value;
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004185
Victor Stinner8c62be82010-05-06 00:08:46 +00004186 /* There are two flavours of 'nice': one that returns the new
4187 priority (as required by almost all standards out there) and the
Benjamin Peterson288d1da2017-09-28 22:44:27 -07004188 Linux/FreeBSD one, which returns '0' on success and advices
Victor Stinner8c62be82010-05-06 00:08:46 +00004189 the use of getpriority() to get the new priority.
Tim Peters5aa91602002-01-30 05:46:57 +00004190
Victor Stinner8c62be82010-05-06 00:08:46 +00004191 If we are of the nice family that returns the new priority, we
4192 need to clear errno before the call, and check if errno is filled
4193 before calling posix_error() on a returnvalue of -1, because the
4194 -1 may be the actual new priority! */
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004195
Victor Stinner8c62be82010-05-06 00:08:46 +00004196 errno = 0;
4197 value = nice(increment);
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004198#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
Victor Stinner8c62be82010-05-06 00:08:46 +00004199 if (value == 0)
4200 value = getpriority(PRIO_PROCESS, 0);
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004201#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004202 if (value == -1 && errno != 0)
4203 /* either nice() or getpriority() returned an error */
4204 return posix_error();
4205 return PyLong_FromLong((long) value);
Guido van Rossum775f4da1993-01-09 17:18:52 +00004206}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004207#endif /* HAVE_NICE */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004208
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004209
4210#ifdef HAVE_GETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004211/*[clinic input]
4212os.getpriority
4213
4214 which: int
4215 who: int
4216
4217Return program scheduling priority.
4218[clinic start generated code]*/
4219
Larry Hastings2f936352014-08-05 14:04:04 +10004220static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004221os_getpriority_impl(PyObject *module, int which, int who)
4222/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004223{
4224 int retval;
4225
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004226 errno = 0;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004227 retval = getpriority(which, who);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004228 if (errno != 0)
4229 return posix_error();
4230 return PyLong_FromLong((long)retval);
4231}
4232#endif /* HAVE_GETPRIORITY */
4233
4234
4235#ifdef HAVE_SETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004236/*[clinic input]
4237os.setpriority
4238
4239 which: int
4240 who: int
4241 priority: int
4242
4243Set program scheduling priority.
4244[clinic start generated code]*/
4245
Larry Hastings2f936352014-08-05 14:04:04 +10004246static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004247os_setpriority_impl(PyObject *module, int which, int who, int priority)
4248/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004249{
4250 int retval;
4251
4252 retval = setpriority(which, who, priority);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004253 if (retval == -1)
4254 return posix_error();
4255 Py_RETURN_NONE;
4256}
4257#endif /* HAVE_SETPRIORITY */
4258
4259
Barry Warsaw53699e91996-12-10 23:23:01 +00004260static PyObject *
Larry Hastings2f936352014-08-05 14:04:04 +10004261internal_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 +00004262{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004263 const char *function_name = is_replace ? "replace" : "rename";
Larry Hastings9cf065c2012-06-22 16:30:09 -07004264 int dir_fd_specified;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004265
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004266#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004267 BOOL result;
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004268 int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004269#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004270 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004271#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004272
Larry Hastings9cf065c2012-06-22 16:30:09 -07004273 dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
4274 (dst_dir_fd != DEFAULT_DIR_FD);
4275#ifndef HAVE_RENAMEAT
4276 if (dir_fd_specified) {
4277 argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10004278 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004279 }
4280#endif
4281
Larry Hastings9cf065c2012-06-22 16:30:09 -07004282#ifdef MS_WINDOWS
4283 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004284 result = MoveFileExW(src->wide, dst->wide, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004285 Py_END_ALLOW_THREADS
4286
Larry Hastings2f936352014-08-05 14:04:04 +10004287 if (!result)
4288 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004289
4290#else
Steve Dowercc16be82016-09-08 10:35:16 -07004291 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
4292 PyErr_Format(PyExc_ValueError,
4293 "%s: src and dst must be the same type", function_name);
4294 return NULL;
4295 }
4296
Larry Hastings9cf065c2012-06-22 16:30:09 -07004297 Py_BEGIN_ALLOW_THREADS
4298#ifdef HAVE_RENAMEAT
4299 if (dir_fd_specified)
Larry Hastings2f936352014-08-05 14:04:04 +10004300 result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004301 else
4302#endif
Steve Dowercc16be82016-09-08 10:35:16 -07004303 result = rename(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004304 Py_END_ALLOW_THREADS
4305
Larry Hastings2f936352014-08-05 14:04:04 +10004306 if (result)
4307 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004308#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004309 Py_RETURN_NONE;
4310}
Larry Hastings9cf065c2012-06-22 16:30:09 -07004311
Larry Hastings2f936352014-08-05 14:04:04 +10004312
4313/*[clinic input]
4314os.rename
4315
4316 src : path_t
4317 dst : path_t
4318 *
4319 src_dir_fd : dir_fd = None
4320 dst_dir_fd : dir_fd = None
4321
4322Rename a file or directory.
4323
4324If either src_dir_fd or dst_dir_fd is not None, it should be a file
4325 descriptor open to a directory, and the respective path string (src or dst)
4326 should be relative; the path will then be relative to that directory.
4327src_dir_fd and dst_dir_fd, may not be implemented on your platform.
4328 If they are unavailable, using them will raise a NotImplementedError.
4329[clinic start generated code]*/
4330
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004331static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004332os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04004333 int dst_dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004334/*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004335{
Larry Hastings2f936352014-08-05 14:04:04 +10004336 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004337}
4338
Larry Hastings2f936352014-08-05 14:04:04 +10004339
4340/*[clinic input]
4341os.replace = os.rename
4342
4343Rename a file or directory, overwriting the destination.
4344
4345If either src_dir_fd or dst_dir_fd is not None, it should be a file
4346 descriptor open to a directory, and the respective path string (src or dst)
4347 should be relative; the path will then be relative to that directory.
4348src_dir_fd and dst_dir_fd, may not be implemented on your platform.
Anthony Sottile73d60022019-02-12 23:15:54 -05004349 If they are unavailable, using them will raise a NotImplementedError.
Larry Hastings2f936352014-08-05 14:04:04 +10004350[clinic start generated code]*/
4351
Larry Hastings2f936352014-08-05 14:04:04 +10004352static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004353os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
4354 int dst_dir_fd)
Anthony Sottile73d60022019-02-12 23:15:54 -05004355/*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004356{
4357 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
4358}
4359
4360
4361/*[clinic input]
4362os.rmdir
4363
4364 path: path_t
4365 *
4366 dir_fd: dir_fd(requires='unlinkat') = None
4367
4368Remove a directory.
4369
4370If dir_fd is not None, it should be a file descriptor open to a directory,
4371 and path should be relative; path will then be relative to that directory.
4372dir_fd may not be implemented on your platform.
4373 If it is unavailable, using it will raise a NotImplementedError.
4374[clinic start generated code]*/
4375
Larry Hastings2f936352014-08-05 14:04:04 +10004376static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004377os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
4378/*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004379{
4380 int result;
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004381
4382 Py_BEGIN_ALLOW_THREADS
4383#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004384 /* Windows, success=1, UNIX, success=0 */
4385 result = !RemoveDirectoryW(path->wide);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004386#else
4387#ifdef HAVE_UNLINKAT
4388 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004389 result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004390 else
4391#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004392 result = rmdir(path->narrow);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004393#endif
4394 Py_END_ALLOW_THREADS
4395
Larry Hastings2f936352014-08-05 14:04:04 +10004396 if (result)
4397 return path_error(path);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004398
Larry Hastings2f936352014-08-05 14:04:04 +10004399 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004400}
4401
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004402
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004403#ifdef HAVE_SYSTEM
Larry Hastings2f936352014-08-05 14:04:04 +10004404#ifdef MS_WINDOWS
4405/*[clinic input]
4406os.system -> long
4407
4408 command: Py_UNICODE
4409
4410Execute the command in a subshell.
4411[clinic start generated code]*/
4412
Larry Hastings2f936352014-08-05 14:04:04 +10004413static long
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02004414os_system_impl(PyObject *module, const Py_UNICODE *command)
4415/*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004416{
4417 long result;
Steve Dowerb82e17e2019-05-23 08:45:22 -07004418
Steve Dowerfbe3c762019-10-18 00:52:15 -07004419 if (PySys_Audit("os.system", "(u)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004420 return -1;
4421 }
4422
Victor Stinner8c62be82010-05-06 00:08:46 +00004423 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08004424 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10004425 result = _wsystem(command);
Steve Dowerc3630612016-11-19 18:41:16 -08004426 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00004427 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004428 return result;
4429}
4430#else /* MS_WINDOWS */
4431/*[clinic input]
4432os.system -> long
4433
4434 command: FSConverter
4435
4436Execute the command in a subshell.
4437[clinic start generated code]*/
4438
Larry Hastings2f936352014-08-05 14:04:04 +10004439static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004440os_system_impl(PyObject *module, PyObject *command)
4441/*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004442{
4443 long result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004444 const char *bytes = PyBytes_AsString(command);
Steve Dowerb82e17e2019-05-23 08:45:22 -07004445
Steve Dowerfbe3c762019-10-18 00:52:15 -07004446 if (PySys_Audit("os.system", "(O)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004447 return -1;
4448 }
4449
Larry Hastings2f936352014-08-05 14:04:04 +10004450 Py_BEGIN_ALLOW_THREADS
4451 result = system(bytes);
4452 Py_END_ALLOW_THREADS
4453 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004454}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004455#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004456#endif /* HAVE_SYSTEM */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004457
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004458
Larry Hastings2f936352014-08-05 14:04:04 +10004459/*[clinic input]
4460os.umask
4461
4462 mask: int
4463 /
4464
4465Set the current numeric umask and return the previous umask.
4466[clinic start generated code]*/
4467
Larry Hastings2f936352014-08-05 14:04:04 +10004468static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004469os_umask_impl(PyObject *module, int mask)
4470/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004471{
4472 int i = (int)umask(mask);
Victor Stinner8c62be82010-05-06 00:08:46 +00004473 if (i < 0)
4474 return posix_error();
4475 return PyLong_FromLong((long)i);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004476}
4477
Brian Curtind40e6f72010-07-08 21:39:08 +00004478#ifdef MS_WINDOWS
4479
4480/* override the default DeleteFileW behavior so that directory
4481symlinks can be removed with this function, the same as with
4482Unix symlinks */
4483BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
4484{
4485 WIN32_FILE_ATTRIBUTE_DATA info;
4486 WIN32_FIND_DATAW find_data;
4487 HANDLE find_data_handle;
4488 int is_directory = 0;
4489 int is_link = 0;
4490
4491 if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
4492 is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004493
Brian Curtind40e6f72010-07-08 21:39:08 +00004494 /* Get WIN32_FIND_DATA structure for the path to determine if
4495 it is a symlink */
4496 if(is_directory &&
4497 info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
4498 find_data_handle = FindFirstFileW(lpFileName, &find_data);
4499
4500 if(find_data_handle != INVALID_HANDLE_VALUE) {
Tim Golden0321cf22014-05-05 19:46:17 +01004501 /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
4502 IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
4503 is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
4504 find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
Brian Curtind40e6f72010-07-08 21:39:08 +00004505 FindClose(find_data_handle);
4506 }
4507 }
4508 }
4509
4510 if (is_directory && is_link)
4511 return RemoveDirectoryW(lpFileName);
4512
4513 return DeleteFileW(lpFileName);
4514}
4515#endif /* MS_WINDOWS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004516
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004517
Larry Hastings2f936352014-08-05 14:04:04 +10004518/*[clinic input]
4519os.unlink
4520
4521 path: path_t
4522 *
4523 dir_fd: dir_fd(requires='unlinkat')=None
4524
4525Remove a file (same as remove()).
4526
4527If dir_fd is not None, it should be a file descriptor open to a directory,
4528 and path should be relative; path will then be relative to that directory.
4529dir_fd may not be implemented on your platform.
4530 If it is unavailable, using it will raise a NotImplementedError.
4531
4532[clinic start generated code]*/
4533
Larry Hastings2f936352014-08-05 14:04:04 +10004534static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004535os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
4536/*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004537{
4538 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004539
4540 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04004541 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004542#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004543 /* Windows, success=1, UNIX, success=0 */
4544 result = !Py_DeleteFileW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004545#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004546#ifdef HAVE_UNLINKAT
4547 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004548 result = unlinkat(dir_fd, path->narrow, 0);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004549 else
4550#endif /* HAVE_UNLINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10004551 result = unlink(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004552#endif
Steve Dower8fc89802015-04-12 00:26:27 -04004553 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004554 Py_END_ALLOW_THREADS
4555
Larry Hastings2f936352014-08-05 14:04:04 +10004556 if (result)
4557 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004558
Larry Hastings2f936352014-08-05 14:04:04 +10004559 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004560}
4561
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004562
Larry Hastings2f936352014-08-05 14:04:04 +10004563/*[clinic input]
4564os.remove = os.unlink
4565
4566Remove a file (same as unlink()).
4567
4568If dir_fd is not None, it should be a file descriptor open to a directory,
4569 and path should be relative; path will then be relative to that directory.
4570dir_fd may not be implemented on your platform.
4571 If it is unavailable, using it will raise a NotImplementedError.
4572[clinic start generated code]*/
4573
Larry Hastings2f936352014-08-05 14:04:04 +10004574static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004575os_remove_impl(PyObject *module, path_t *path, int dir_fd)
4576/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004577{
4578 return os_unlink_impl(module, path, dir_fd);
4579}
4580
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004581
Larry Hastings605a62d2012-06-24 04:33:36 -07004582static PyStructSequence_Field uname_result_fields[] = {
4583 {"sysname", "operating system name"},
4584 {"nodename", "name of machine on network (implementation-defined)"},
4585 {"release", "operating system release"},
4586 {"version", "operating system version"},
4587 {"machine", "hardware identifier"},
4588 {NULL}
4589};
4590
4591PyDoc_STRVAR(uname_result__doc__,
4592"uname_result: Result from os.uname().\n\n\
4593This object may be accessed either as a tuple of\n\
4594 (sysname, nodename, release, version, machine),\n\
4595or via the attributes sysname, nodename, release, version, and machine.\n\
4596\n\
4597See os.uname for more information.");
4598
4599static PyStructSequence_Desc uname_result_desc = {
Eddie Elizondob3966632019-11-05 07:16:14 -08004600 MODNAME ".uname_result", /* name */
Larry Hastings605a62d2012-06-24 04:33:36 -07004601 uname_result__doc__, /* doc */
4602 uname_result_fields,
4603 5
4604};
4605
Larry Hastings605a62d2012-06-24 04:33:36 -07004606#ifdef HAVE_UNAME
Larry Hastings2f936352014-08-05 14:04:04 +10004607/*[clinic input]
4608os.uname
4609
4610Return an object identifying the current operating system.
4611
4612The object behaves like a named tuple with the following fields:
4613 (sysname, nodename, release, version, machine)
4614
4615[clinic start generated code]*/
4616
Larry Hastings2f936352014-08-05 14:04:04 +10004617static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004618os_uname_impl(PyObject *module)
4619/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004620{
Victor Stinner8c62be82010-05-06 00:08:46 +00004621 struct utsname u;
4622 int res;
Larry Hastings605a62d2012-06-24 04:33:36 -07004623 PyObject *value;
Neal Norwitze241ce82003-02-17 18:17:05 +00004624
Victor Stinner8c62be82010-05-06 00:08:46 +00004625 Py_BEGIN_ALLOW_THREADS
4626 res = uname(&u);
4627 Py_END_ALLOW_THREADS
4628 if (res < 0)
4629 return posix_error();
Larry Hastings605a62d2012-06-24 04:33:36 -07004630
Eddie Elizondob3966632019-11-05 07:16:14 -08004631 PyObject *UnameResultType = _posixstate(module)->UnameResultType;
4632 value = PyStructSequence_New((PyTypeObject *)UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07004633 if (value == NULL)
4634 return NULL;
4635
4636#define SET(i, field) \
4637 { \
Victor Stinnera534fc42013-06-03 22:07:27 +02004638 PyObject *o = PyUnicode_DecodeFSDefault(field); \
Larry Hastings605a62d2012-06-24 04:33:36 -07004639 if (!o) { \
4640 Py_DECREF(value); \
4641 return NULL; \
4642 } \
4643 PyStructSequence_SET_ITEM(value, i, o); \
4644 } \
4645
4646 SET(0, u.sysname);
4647 SET(1, u.nodename);
4648 SET(2, u.release);
4649 SET(3, u.version);
4650 SET(4, u.machine);
4651
4652#undef SET
4653
4654 return value;
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004655}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004656#endif /* HAVE_UNAME */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004657
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004658
Larry Hastings9cf065c2012-06-22 16:30:09 -07004659
4660typedef struct {
4661 int now;
4662 time_t atime_s;
4663 long atime_ns;
4664 time_t mtime_s;
4665 long mtime_ns;
4666} utime_t;
4667
4668/*
Victor Stinner484df002014-10-09 13:52:31 +02004669 * these macros assume that "ut" is a pointer to a utime_t
Larry Hastings9cf065c2012-06-22 16:30:09 -07004670 * they also intentionally leak the declaration of a pointer named "time"
4671 */
4672#define UTIME_TO_TIMESPEC \
4673 struct timespec ts[2]; \
4674 struct timespec *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004675 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004676 time = NULL; \
4677 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004678 ts[0].tv_sec = ut->atime_s; \
4679 ts[0].tv_nsec = ut->atime_ns; \
4680 ts[1].tv_sec = ut->mtime_s; \
4681 ts[1].tv_nsec = ut->mtime_ns; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004682 time = ts; \
4683 } \
4684
4685#define UTIME_TO_TIMEVAL \
4686 struct timeval tv[2]; \
4687 struct timeval *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004688 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004689 time = NULL; \
4690 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004691 tv[0].tv_sec = ut->atime_s; \
4692 tv[0].tv_usec = ut->atime_ns / 1000; \
4693 tv[1].tv_sec = ut->mtime_s; \
4694 tv[1].tv_usec = ut->mtime_ns / 1000; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004695 time = tv; \
4696 } \
4697
4698#define UTIME_TO_UTIMBUF \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004699 struct utimbuf u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004700 struct utimbuf *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004701 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004702 time = NULL; \
4703 else { \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004704 u.actime = ut->atime_s; \
4705 u.modtime = ut->mtime_s; \
4706 time = &u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004707 }
4708
4709#define UTIME_TO_TIME_T \
4710 time_t timet[2]; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004711 time_t *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004712 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004713 time = NULL; \
4714 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004715 timet[0] = ut->atime_s; \
4716 timet[1] = ut->mtime_s; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004717 time = timet; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004718 } \
4719
4720
Victor Stinner528a9ab2015-09-03 21:30:26 +02004721#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004722
4723static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004724utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004725{
4726#ifdef HAVE_UTIMENSAT
4727 int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
4728 UTIME_TO_TIMESPEC;
4729 return utimensat(dir_fd, path, time, flags);
4730#elif defined(HAVE_FUTIMESAT)
4731 UTIME_TO_TIMEVAL;
4732 /*
4733 * follow_symlinks will never be false here;
4734 * we only allow !follow_symlinks and dir_fd together
4735 * if we have utimensat()
4736 */
4737 assert(follow_symlinks);
4738 return futimesat(dir_fd, path, time);
4739#endif
4740}
4741
Larry Hastings2f936352014-08-05 14:04:04 +10004742 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
4743#else
4744 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings9cf065c2012-06-22 16:30:09 -07004745#endif
4746
Victor Stinner528a9ab2015-09-03 21:30:26 +02004747#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004748
4749static int
Victor Stinner484df002014-10-09 13:52:31 +02004750utime_fd(utime_t *ut, int fd)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004751{
4752#ifdef HAVE_FUTIMENS
4753 UTIME_TO_TIMESPEC;
4754 return futimens(fd, time);
4755#else
4756 UTIME_TO_TIMEVAL;
4757 return futimes(fd, time);
4758#endif
4759}
4760
Larry Hastings2f936352014-08-05 14:04:04 +10004761 #define PATH_UTIME_HAVE_FD 1
4762#else
4763 #define PATH_UTIME_HAVE_FD 0
Larry Hastings9cf065c2012-06-22 16:30:09 -07004764#endif
4765
Victor Stinner5ebae872015-09-22 01:29:33 +02004766#if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
4767# define UTIME_HAVE_NOFOLLOW_SYMLINKS
4768#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004769
Victor Stinner4552ced2015-09-21 22:37:15 +02004770#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004771
4772static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004773utime_nofollow_symlinks(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004774{
4775#ifdef HAVE_UTIMENSAT
4776 UTIME_TO_TIMESPEC;
4777 return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
4778#else
4779 UTIME_TO_TIMEVAL;
4780 return lutimes(path, time);
4781#endif
4782}
4783
4784#endif
4785
4786#ifndef MS_WINDOWS
4787
4788static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004789utime_default(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004790{
4791#ifdef HAVE_UTIMENSAT
4792 UTIME_TO_TIMESPEC;
4793 return utimensat(DEFAULT_DIR_FD, path, time, 0);
4794#elif defined(HAVE_UTIMES)
4795 UTIME_TO_TIMEVAL;
4796 return utimes(path, time);
4797#elif defined(HAVE_UTIME_H)
4798 UTIME_TO_UTIMBUF;
4799 return utime(path, time);
4800#else
4801 UTIME_TO_TIME_T;
4802 return utime(path, time);
4803#endif
4804}
4805
4806#endif
4807
Larry Hastings76ad59b2012-05-03 00:30:07 -07004808static int
4809split_py_long_to_s_and_ns(PyObject *py_long, time_t *s, long *ns)
4810{
4811 int result = 0;
Benjamin Petersonfbd85a02012-05-04 11:06:09 -04004812 PyObject *divmod;
Eddie Elizondob3966632019-11-05 07:16:14 -08004813 divmod = PyNumber_Divmod(py_long, _posixstate_global->billion);
Larry Hastings76ad59b2012-05-03 00:30:07 -07004814 if (!divmod)
4815 goto exit;
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004816 if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
4817 PyErr_Format(PyExc_TypeError,
4818 "%.200s.__divmod__() must return a 2-tuple, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -08004819 _PyType_Name(Py_TYPE(py_long)), _PyType_Name(Py_TYPE(divmod)));
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004820 goto exit;
4821 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004822 *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
4823 if ((*s == -1) && PyErr_Occurred())
4824 goto exit;
4825 *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
Benjamin Peterson35a8f0d2012-05-04 01:10:59 -04004826 if ((*ns == -1) && PyErr_Occurred())
Larry Hastings76ad59b2012-05-03 00:30:07 -07004827 goto exit;
4828
4829 result = 1;
4830exit:
4831 Py_XDECREF(divmod);
4832 return result;
4833}
4834
Larry Hastings2f936352014-08-05 14:04:04 +10004835
4836/*[clinic input]
4837os.utime
4838
4839 path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004840 times: object = None
Larry Hastings2f936352014-08-05 14:04:04 +10004841 *
4842 ns: object = NULL
4843 dir_fd: dir_fd(requires='futimensat') = None
4844 follow_symlinks: bool=True
4845
Martin Panter0ff89092015-09-09 01:56:53 +00004846# "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
Larry Hastings2f936352014-08-05 14:04:04 +10004847
4848Set the access and modified time of path.
4849
4850path may always be specified as a string.
4851On some platforms, path may also be specified as an open file descriptor.
4852 If this functionality is unavailable, using it raises an exception.
4853
4854If times is not None, it must be a tuple (atime, mtime);
4855 atime and mtime should be expressed as float seconds since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004856If ns is specified, it must be a tuple (atime_ns, mtime_ns);
Larry Hastings2f936352014-08-05 14:04:04 +10004857 atime_ns and mtime_ns should be expressed as integer nanoseconds
4858 since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004859If times is None and ns is unspecified, utime uses the current time.
Larry Hastings2f936352014-08-05 14:04:04 +10004860Specifying tuples for both times and ns is an error.
4861
4862If dir_fd is not None, it should be a file descriptor open to a directory,
4863 and path should be relative; path will then be relative to that directory.
4864If follow_symlinks is False, and the last element of the path is a symbolic
4865 link, utime will modify the symbolic link itself instead of the file the
4866 link points to.
4867It is an error to use dir_fd or follow_symlinks when specifying path
4868 as an open file descriptor.
4869dir_fd and follow_symlinks may not be available on your platform.
4870 If they are unavailable, using them will raise a NotImplementedError.
4871
4872[clinic start generated code]*/
4873
Larry Hastings2f936352014-08-05 14:04:04 +10004874static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004875os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
4876 int dir_fd, int follow_symlinks)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004877/*[clinic end generated code: output=cfcac69d027b82cf input=2fbd62a2f228f8f4]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004878{
Larry Hastings9cf065c2012-06-22 16:30:09 -07004879#ifdef MS_WINDOWS
4880 HANDLE hFile;
4881 FILETIME atime, mtime;
4882#else
4883 int result;
4884#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004885
Larry Hastings2f936352014-08-05 14:04:04 +10004886 utime_t utime;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004887
Christian Heimesb3c87242013-08-01 00:08:16 +02004888 memset(&utime, 0, sizeof(utime_t));
Larry Hastings76ad59b2012-05-03 00:30:07 -07004889
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004890 if (times != Py_None && ns) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004891 PyErr_SetString(PyExc_ValueError,
4892 "utime: you may specify either 'times'"
4893 " or 'ns' but not both");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004894 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004895 }
4896
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004897 if (times != Py_None) {
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004898 time_t a_sec, m_sec;
4899 long a_nsec, m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004900 if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004901 PyErr_SetString(PyExc_TypeError,
4902 "utime: 'times' must be either"
4903 " a tuple of two ints or None");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004904 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004905 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004906 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004907 if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004908 &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004909 _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004910 &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004911 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004912 }
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004913 utime.atime_s = a_sec;
4914 utime.atime_ns = a_nsec;
4915 utime.mtime_s = m_sec;
4916 utime.mtime_ns = m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004917 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004918 else if (ns) {
Larry Hastings76ad59b2012-05-03 00:30:07 -07004919 if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004920 PyErr_SetString(PyExc_TypeError,
4921 "utime: 'ns' must be a tuple of two ints");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004922 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004923 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004924 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004925 if (!split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 0),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004926 &utime.atime_s, &utime.atime_ns) ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004927 !split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 1),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004928 &utime.mtime_s, &utime.mtime_ns)) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004929 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004930 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004931 }
4932 else {
4933 /* times and ns are both None/unspecified. use "now". */
4934 utime.now = 1;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004935 }
4936
Victor Stinner4552ced2015-09-21 22:37:15 +02004937#if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004938 if (follow_symlinks_specified("utime", follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004939 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004940#endif
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004941
Larry Hastings2f936352014-08-05 14:04:04 +10004942 if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
4943 dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
4944 fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004945 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004946
Larry Hastings9cf065c2012-06-22 16:30:09 -07004947#if !defined(HAVE_UTIMENSAT)
4948 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
Georg Brandl969288e2012-06-26 09:25:44 +02004949 PyErr_SetString(PyExc_ValueError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07004950 "utime: cannot use dir_fd and follow_symlinks "
4951 "together on this platform");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004952 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004953 }
4954#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004955
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004956#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004957 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004958 hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
4959 NULL, OPEN_EXISTING,
4960 FILE_FLAG_BACKUP_SEMANTICS, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004961 Py_END_ALLOW_THREADS
4962 if (hFile == INVALID_HANDLE_VALUE) {
Larry Hastings2f936352014-08-05 14:04:04 +10004963 path_error(path);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004964 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004965 }
4966
Larry Hastings9cf065c2012-06-22 16:30:09 -07004967 if (utime.now) {
Antoine Pitrou91a7af32013-11-23 15:23:26 +01004968 GetSystemTimeAsFileTime(&mtime);
4969 atime = mtime;
Victor Stinner8c62be82010-05-06 00:08:46 +00004970 }
Victor Stinner8c62be82010-05-06 00:08:46 +00004971 else {
Steve Dowerbf1f3762015-02-21 15:26:02 -08004972 _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
4973 _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
Victor Stinner8c62be82010-05-06 00:08:46 +00004974 }
4975 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
4976 /* Avoid putting the file name into the error here,
4977 as that may confuse the user into believing that
4978 something is wrong with the file, when it also
4979 could be the time stamp that gives a problem. */
Victor Stinnerb024e842012-10-31 22:24:06 +01004980 PyErr_SetFromWindowsErr(0);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004981 CloseHandle(hFile);
4982 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004983 }
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004984 CloseHandle(hFile);
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004985#else /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07004986 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004987
Victor Stinner4552ced2015-09-21 22:37:15 +02004988#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004989 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10004990 result = utime_nofollow_symlinks(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004991 else
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004992#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004993
Victor Stinner528a9ab2015-09-03 21:30:26 +02004994#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004995 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10004996 result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004997 else
4998#endif
4999
Victor Stinner528a9ab2015-09-03 21:30:26 +02005000#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings2f936352014-08-05 14:04:04 +10005001 if (path->fd != -1)
5002 result = utime_fd(&utime, path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005003 else
5004#endif
5005
Larry Hastings2f936352014-08-05 14:04:04 +10005006 result = utime_default(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005007
5008 Py_END_ALLOW_THREADS
5009
5010 if (result < 0) {
5011 /* see previous comment about not putting filename in error here */
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005012 posix_error();
5013 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00005014 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07005015
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00005016#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07005017
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005018 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005019}
5020
Guido van Rossum3b066191991-06-04 19:40:25 +00005021/* Process operations */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005022
Larry Hastings2f936352014-08-05 14:04:04 +10005023
5024/*[clinic input]
5025os._exit
5026
5027 status: int
5028
5029Exit to the system with specified status, without normal exit processing.
5030[clinic start generated code]*/
5031
Larry Hastings2f936352014-08-05 14:04:04 +10005032static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005033os__exit_impl(PyObject *module, int status)
5034/*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005035{
5036 _exit(status);
Victor Stinner8c62be82010-05-06 00:08:46 +00005037 return NULL; /* Make gcc -Wall happy */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005038}
5039
Steve Dowercc16be82016-09-08 10:35:16 -07005040#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5041#define EXECV_CHAR wchar_t
5042#else
5043#define EXECV_CHAR char
5044#endif
5045
pxinwrf2d7ac72019-05-21 18:46:37 +08005046#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005047static void
Steve Dowercc16be82016-09-08 10:35:16 -07005048free_string_array(EXECV_CHAR **array, Py_ssize_t count)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005049{
Victor Stinner8c62be82010-05-06 00:08:46 +00005050 Py_ssize_t i;
5051 for (i = 0; i < count; i++)
5052 PyMem_Free(array[i]);
5053 PyMem_DEL(array);
Martin v. Löwis114619e2002-10-07 06:44:21 +00005054}
Martin v. Löwis011e8422009-05-05 04:43:17 +00005055
Berker Peksag81816462016-09-15 20:19:47 +03005056static int
5057fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
Martin v. Löwis011e8422009-05-05 04:43:17 +00005058{
Victor Stinner8c62be82010-05-06 00:08:46 +00005059 Py_ssize_t size;
Berker Peksag81816462016-09-15 20:19:47 +03005060 PyObject *ub;
5061 int result = 0;
Steve Dowercc16be82016-09-08 10:35:16 -07005062#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
Berker Peksag81816462016-09-15 20:19:47 +03005063 if (!PyUnicode_FSDecoder(o, &ub))
Steve Dowercc16be82016-09-08 10:35:16 -07005064 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005065 *out = PyUnicode_AsWideCharString(ub, &size);
5066 if (*out)
5067 result = 1;
Steve Dowercc16be82016-09-08 10:35:16 -07005068#else
Berker Peksag81816462016-09-15 20:19:47 +03005069 if (!PyUnicode_FSConverter(o, &ub))
Victor Stinner8c62be82010-05-06 00:08:46 +00005070 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005071 size = PyBytes_GET_SIZE(ub);
5072 *out = PyMem_Malloc(size + 1);
5073 if (*out) {
5074 memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
5075 result = 1;
5076 } else
Victor Stinner50abf222013-11-07 23:56:10 +01005077 PyErr_NoMemory();
Steve Dowercc16be82016-09-08 10:35:16 -07005078#endif
Berker Peksag81816462016-09-15 20:19:47 +03005079 Py_DECREF(ub);
5080 return result;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005081}
Martin v. Löwis114619e2002-10-07 06:44:21 +00005082#endif
5083
pxinwrf2d7ac72019-05-21 18:46:37 +08005084#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
Steve Dowercc16be82016-09-08 10:35:16 -07005085static EXECV_CHAR**
Victor Stinner13bb71c2010-04-23 21:41:56 +00005086parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
5087{
Victor Stinner8c62be82010-05-06 00:08:46 +00005088 Py_ssize_t i, pos, envc;
5089 PyObject *keys=NULL, *vals=NULL;
Berker Peksag81816462016-09-15 20:19:47 +03005090 PyObject *key, *val, *key2, *val2, *keyval;
Steve Dowercc16be82016-09-08 10:35:16 -07005091 EXECV_CHAR **envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005092
Victor Stinner8c62be82010-05-06 00:08:46 +00005093 i = PyMapping_Size(env);
5094 if (i < 0)
5095 return NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07005096 envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005097 if (envlist == NULL) {
5098 PyErr_NoMemory();
5099 return NULL;
5100 }
5101 envc = 0;
5102 keys = PyMapping_Keys(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005103 if (!keys)
5104 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00005105 vals = PyMapping_Values(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005106 if (!vals)
Victor Stinner8c62be82010-05-06 00:08:46 +00005107 goto error;
5108 if (!PyList_Check(keys) || !PyList_Check(vals)) {
5109 PyErr_Format(PyExc_TypeError,
5110 "env.keys() or env.values() is not a list");
5111 goto error;
5112 }
Victor Stinner13bb71c2010-04-23 21:41:56 +00005113
Victor Stinner8c62be82010-05-06 00:08:46 +00005114 for (pos = 0; pos < i; pos++) {
5115 key = PyList_GetItem(keys, pos);
5116 val = PyList_GetItem(vals, pos);
5117 if (!key || !val)
5118 goto error;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005119
Berker Peksag81816462016-09-15 20:19:47 +03005120#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5121 if (!PyUnicode_FSDecoder(key, &key2))
5122 goto error;
5123 if (!PyUnicode_FSDecoder(val, &val2)) {
5124 Py_DECREF(key2);
5125 goto error;
5126 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005127 /* Search from index 1 because on Windows starting '=' is allowed for
5128 defining hidden environment variables. */
5129 if (PyUnicode_GET_LENGTH(key2) == 0 ||
5130 PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
5131 {
5132 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005133 Py_DECREF(key2);
5134 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005135 goto error;
5136 }
Berker Peksag81816462016-09-15 20:19:47 +03005137 keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
5138#else
5139 if (!PyUnicode_FSConverter(key, &key2))
5140 goto error;
5141 if (!PyUnicode_FSConverter(val, &val2)) {
5142 Py_DECREF(key2);
5143 goto error;
5144 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005145 if (PyBytes_GET_SIZE(key2) == 0 ||
5146 strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
5147 {
5148 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005149 Py_DECREF(key2);
5150 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005151 goto error;
5152 }
Berker Peksag81816462016-09-15 20:19:47 +03005153 keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
5154 PyBytes_AS_STRING(val2));
5155#endif
5156 Py_DECREF(key2);
5157 Py_DECREF(val2);
Steve Dowercc16be82016-09-08 10:35:16 -07005158 if (!keyval)
Victor Stinner8c62be82010-05-06 00:08:46 +00005159 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -07005160
5161 if (!fsconvert_strdup(keyval, &envlist[envc++])) {
5162 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005163 goto error;
5164 }
Berker Peksag81816462016-09-15 20:19:47 +03005165
Steve Dowercc16be82016-09-08 10:35:16 -07005166 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005167 }
5168 Py_DECREF(vals);
5169 Py_DECREF(keys);
Victor Stinner13bb71c2010-04-23 21:41:56 +00005170
Victor Stinner8c62be82010-05-06 00:08:46 +00005171 envlist[envc] = 0;
5172 *envc_ptr = envc;
5173 return envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005174
5175error:
Victor Stinner8c62be82010-05-06 00:08:46 +00005176 Py_XDECREF(keys);
5177 Py_XDECREF(vals);
Steve Dowercc16be82016-09-08 10:35:16 -07005178 free_string_array(envlist, envc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005179 return NULL;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005180}
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005181
Steve Dowercc16be82016-09-08 10:35:16 -07005182static EXECV_CHAR**
Ross Lagerwall7807c352011-03-17 20:20:30 +02005183parse_arglist(PyObject* argv, Py_ssize_t *argc)
5184{
5185 int i;
Steve Dowercc16be82016-09-08 10:35:16 -07005186 EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005187 if (argvlist == NULL) {
5188 PyErr_NoMemory();
5189 return NULL;
5190 }
5191 for (i = 0; i < *argc; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005192 PyObject* item = PySequence_ITEM(argv, i);
5193 if (item == NULL)
5194 goto fail;
5195 if (!fsconvert_strdup(item, &argvlist[i])) {
5196 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005197 goto fail;
5198 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005199 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005200 }
5201 argvlist[*argc] = NULL;
5202 return argvlist;
5203fail:
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005204 *argc = i;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005205 free_string_array(argvlist, *argc);
5206 return NULL;
5207}
Steve Dowercc16be82016-09-08 10:35:16 -07005208
Ross Lagerwall7807c352011-03-17 20:20:30 +02005209#endif
5210
Larry Hastings2f936352014-08-05 14:04:04 +10005211
Ross Lagerwall7807c352011-03-17 20:20:30 +02005212#ifdef HAVE_EXECV
Larry Hastings2f936352014-08-05 14:04:04 +10005213/*[clinic input]
5214os.execv
5215
Steve Dowercc16be82016-09-08 10:35:16 -07005216 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005217 Path of executable file.
5218 argv: object
5219 Tuple or list of strings.
5220 /
5221
5222Execute an executable path with arguments, replacing current process.
5223[clinic start generated code]*/
5224
Larry Hastings2f936352014-08-05 14:04:04 +10005225static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005226os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
5227/*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005228{
Steve Dowercc16be82016-09-08 10:35:16 -07005229 EXECV_CHAR **argvlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005230 Py_ssize_t argc;
5231
5232 /* execv has two arguments: (path, argv), where
5233 argv is a list or tuple of strings. */
5234
Ross Lagerwall7807c352011-03-17 20:20:30 +02005235 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
5236 PyErr_SetString(PyExc_TypeError,
5237 "execv() arg 2 must be a tuple or list");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005238 return NULL;
5239 }
5240 argc = PySequence_Size(argv);
5241 if (argc < 1) {
5242 PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005243 return NULL;
5244 }
5245
5246 argvlist = parse_arglist(argv, &argc);
5247 if (argvlist == NULL) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02005248 return NULL;
5249 }
Steve Dowerbce26262016-11-19 19:17:26 -08005250 if (!argvlist[0][0]) {
5251 PyErr_SetString(PyExc_ValueError,
5252 "execv() arg 2 first element cannot be empty");
5253 free_string_array(argvlist, argc);
5254 return NULL;
5255 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005256
Steve Dowerbce26262016-11-19 19:17:26 -08005257 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005258#ifdef HAVE_WEXECV
5259 _wexecv(path->wide, argvlist);
5260#else
5261 execv(path->narrow, argvlist);
5262#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005263 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005264
5265 /* If we get here it's definitely an error */
5266
5267 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005268 return posix_error();
5269}
5270
Larry Hastings2f936352014-08-05 14:04:04 +10005271
5272/*[clinic input]
5273os.execve
5274
5275 path: path_t(allow_fd='PATH_HAVE_FEXECVE')
5276 Path of executable file.
5277 argv: object
5278 Tuple or list of strings.
5279 env: object
5280 Dictionary of strings mapping to strings.
5281
5282Execute an executable path with arguments, replacing current process.
5283[clinic start generated code]*/
5284
Larry Hastings2f936352014-08-05 14:04:04 +10005285static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005286os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
5287/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005288{
Steve Dowercc16be82016-09-08 10:35:16 -07005289 EXECV_CHAR **argvlist = NULL;
5290 EXECV_CHAR **envlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005291 Py_ssize_t argc, envc;
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005292
Victor Stinner8c62be82010-05-06 00:08:46 +00005293 /* execve has three arguments: (path, argv, env), where
5294 argv is a list or tuple of strings and env is a dictionary
5295 like posix.environ. */
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005296
Ross Lagerwall7807c352011-03-17 20:20:30 +02005297 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005298 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005299 "execve: argv must be a tuple or list");
5300 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005301 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005302 argc = PySequence_Size(argv);
Steve Dowerbce26262016-11-19 19:17:26 -08005303 if (argc < 1) {
5304 PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
5305 return NULL;
5306 }
5307
Victor Stinner8c62be82010-05-06 00:08:46 +00005308 if (!PyMapping_Check(env)) {
5309 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005310 "execve: environment must be a mapping object");
5311 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005312 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005313
Ross Lagerwall7807c352011-03-17 20:20:30 +02005314 argvlist = parse_arglist(argv, &argc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005315 if (argvlist == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07005316 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005317 }
Steve Dowerbce26262016-11-19 19:17:26 -08005318 if (!argvlist[0][0]) {
5319 PyErr_SetString(PyExc_ValueError,
5320 "execve: argv first element cannot be empty");
5321 goto fail;
5322 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005323
Victor Stinner8c62be82010-05-06 00:08:46 +00005324 envlist = parse_envlist(env, &envc);
5325 if (envlist == NULL)
Ross Lagerwall7807c352011-03-17 20:20:30 +02005326 goto fail;
5327
Steve Dowerbce26262016-11-19 19:17:26 -08005328 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07005329#ifdef HAVE_FEXECVE
Larry Hastings2f936352014-08-05 14:04:04 +10005330 if (path->fd > -1)
5331 fexecve(path->fd, argvlist, envlist);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005332 else
5333#endif
Steve Dowercc16be82016-09-08 10:35:16 -07005334#ifdef HAVE_WEXECV
5335 _wexecve(path->wide, argvlist, envlist);
5336#else
Larry Hastings2f936352014-08-05 14:04:04 +10005337 execve(path->narrow, argvlist, envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07005338#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005339 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005340
5341 /* If we get here it's definitely an error */
5342
Alexey Izbyshev83460312018-10-20 03:28:22 +03005343 posix_path_error(path);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005344
Steve Dowercc16be82016-09-08 10:35:16 -07005345 free_string_array(envlist, envc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005346 fail:
Larry Hastings9cf065c2012-06-22 16:30:09 -07005347 if (argvlist)
5348 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005349 return NULL;
5350}
Steve Dowercc16be82016-09-08 10:35:16 -07005351
Larry Hastings9cf065c2012-06-22 16:30:09 -07005352#endif /* HAVE_EXECV */
5353
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005354#ifdef HAVE_POSIX_SPAWN
5355
5356enum posix_spawn_file_actions_identifier {
5357 POSIX_SPAWN_OPEN,
5358 POSIX_SPAWN_CLOSE,
5359 POSIX_SPAWN_DUP2
5360};
5361
William Orr81574b82018-10-01 22:19:56 -07005362#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005363static int
Pablo Galindo254a4662018-09-07 16:44:24 +01005364convert_sched_param(PyObject *param, struct sched_param *res);
William Orr81574b82018-10-01 22:19:56 -07005365#endif
Pablo Galindo254a4662018-09-07 16:44:24 +01005366
5367static int
Victor Stinner325e4ba2019-02-01 15:47:24 +01005368parse_posix_spawn_flags(const char *func_name, PyObject *setpgroup,
5369 int resetids, int setsid, PyObject *setsigmask,
Pablo Galindo254a4662018-09-07 16:44:24 +01005370 PyObject *setsigdef, PyObject *scheduler,
5371 posix_spawnattr_t *attrp)
5372{
5373 long all_flags = 0;
5374
5375 errno = posix_spawnattr_init(attrp);
5376 if (errno) {
5377 posix_error();
5378 return -1;
5379 }
5380
5381 if (setpgroup) {
5382 pid_t pgid = PyLong_AsPid(setpgroup);
5383 if (pgid == (pid_t)-1 && PyErr_Occurred()) {
5384 goto fail;
5385 }
5386 errno = posix_spawnattr_setpgroup(attrp, pgid);
5387 if (errno) {
5388 posix_error();
5389 goto fail;
5390 }
5391 all_flags |= POSIX_SPAWN_SETPGROUP;
5392 }
5393
5394 if (resetids) {
5395 all_flags |= POSIX_SPAWN_RESETIDS;
5396 }
5397
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005398 if (setsid) {
5399#ifdef POSIX_SPAWN_SETSID
5400 all_flags |= POSIX_SPAWN_SETSID;
5401#elif defined(POSIX_SPAWN_SETSID_NP)
5402 all_flags |= POSIX_SPAWN_SETSID_NP;
5403#else
5404 argument_unavailable_error(func_name, "setsid");
5405 return -1;
5406#endif
5407 }
5408
Pablo Galindo254a4662018-09-07 16:44:24 +01005409 if (setsigmask) {
5410 sigset_t set;
5411 if (!_Py_Sigset_Converter(setsigmask, &set)) {
5412 goto fail;
5413 }
5414 errno = posix_spawnattr_setsigmask(attrp, &set);
5415 if (errno) {
5416 posix_error();
5417 goto fail;
5418 }
5419 all_flags |= POSIX_SPAWN_SETSIGMASK;
5420 }
5421
5422 if (setsigdef) {
5423 sigset_t set;
5424 if (!_Py_Sigset_Converter(setsigdef, &set)) {
5425 goto fail;
5426 }
5427 errno = posix_spawnattr_setsigdefault(attrp, &set);
5428 if (errno) {
5429 posix_error();
5430 goto fail;
5431 }
5432 all_flags |= POSIX_SPAWN_SETSIGDEF;
5433 }
5434
5435 if (scheduler) {
5436#ifdef POSIX_SPAWN_SETSCHEDULER
5437 PyObject *py_schedpolicy;
5438 struct sched_param schedparam;
5439
5440 if (!PyArg_ParseTuple(scheduler, "OO&"
5441 ";A scheduler tuple must have two elements",
5442 &py_schedpolicy, convert_sched_param, &schedparam)) {
5443 goto fail;
5444 }
5445 if (py_schedpolicy != Py_None) {
5446 int schedpolicy = _PyLong_AsInt(py_schedpolicy);
5447
5448 if (schedpolicy == -1 && PyErr_Occurred()) {
5449 goto fail;
5450 }
5451 errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
5452 if (errno) {
5453 posix_error();
5454 goto fail;
5455 }
5456 all_flags |= POSIX_SPAWN_SETSCHEDULER;
5457 }
5458 errno = posix_spawnattr_setschedparam(attrp, &schedparam);
5459 if (errno) {
5460 posix_error();
5461 goto fail;
5462 }
5463 all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
5464#else
5465 PyErr_SetString(PyExc_NotImplementedError,
5466 "The scheduler option is not supported in this system.");
5467 goto fail;
5468#endif
5469 }
5470
5471 errno = posix_spawnattr_setflags(attrp, all_flags);
5472 if (errno) {
5473 posix_error();
5474 goto fail;
5475 }
5476
5477 return 0;
5478
5479fail:
5480 (void)posix_spawnattr_destroy(attrp);
5481 return -1;
5482}
5483
5484static int
Serhiy Storchakaef347532018-05-01 16:45:04 +03005485parse_file_actions(PyObject *file_actions,
Pablo Galindocb970732018-06-19 09:19:50 +01005486 posix_spawn_file_actions_t *file_actionsp,
5487 PyObject *temp_buffer)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005488{
5489 PyObject *seq;
5490 PyObject *file_action = NULL;
5491 PyObject *tag_obj;
5492
5493 seq = PySequence_Fast(file_actions,
5494 "file_actions must be a sequence or None");
5495 if (seq == NULL) {
5496 return -1;
5497 }
5498
5499 errno = posix_spawn_file_actions_init(file_actionsp);
5500 if (errno) {
5501 posix_error();
5502 Py_DECREF(seq);
5503 return -1;
5504 }
5505
Zackery Spytzd52a83a2019-06-26 14:54:20 -06005506 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
Serhiy Storchakaef347532018-05-01 16:45:04 +03005507 file_action = PySequence_Fast_GET_ITEM(seq, i);
5508 Py_INCREF(file_action);
5509 if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
5510 PyErr_SetString(PyExc_TypeError,
5511 "Each file_actions element must be a non-empty tuple");
5512 goto fail;
5513 }
5514 long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
5515 if (tag == -1 && PyErr_Occurred()) {
5516 goto fail;
5517 }
5518
5519 /* Populate the file_actions object */
5520 switch (tag) {
5521 case POSIX_SPAWN_OPEN: {
5522 int fd, oflag;
5523 PyObject *path;
5524 unsigned long mode;
5525 if (!PyArg_ParseTuple(file_action, "OiO&ik"
5526 ";A open file_action tuple must have 5 elements",
5527 &tag_obj, &fd, PyUnicode_FSConverter, &path,
5528 &oflag, &mode))
5529 {
5530 goto fail;
5531 }
Pablo Galindocb970732018-06-19 09:19:50 +01005532 if (PyList_Append(temp_buffer, path)) {
5533 Py_DECREF(path);
5534 goto fail;
5535 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005536 errno = posix_spawn_file_actions_addopen(file_actionsp,
5537 fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
Pablo Galindocb970732018-06-19 09:19:50 +01005538 Py_DECREF(path);
Serhiy Storchakaef347532018-05-01 16:45:04 +03005539 if (errno) {
5540 posix_error();
5541 goto fail;
5542 }
5543 break;
5544 }
5545 case POSIX_SPAWN_CLOSE: {
5546 int fd;
5547 if (!PyArg_ParseTuple(file_action, "Oi"
5548 ";A close file_action tuple must have 2 elements",
5549 &tag_obj, &fd))
5550 {
5551 goto fail;
5552 }
5553 errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
5554 if (errno) {
5555 posix_error();
5556 goto fail;
5557 }
5558 break;
5559 }
5560 case POSIX_SPAWN_DUP2: {
5561 int fd1, fd2;
5562 if (!PyArg_ParseTuple(file_action, "Oii"
5563 ";A dup2 file_action tuple must have 3 elements",
5564 &tag_obj, &fd1, &fd2))
5565 {
5566 goto fail;
5567 }
5568 errno = posix_spawn_file_actions_adddup2(file_actionsp,
5569 fd1, fd2);
5570 if (errno) {
5571 posix_error();
5572 goto fail;
5573 }
5574 break;
5575 }
5576 default: {
5577 PyErr_SetString(PyExc_TypeError,
5578 "Unknown file_actions identifier");
5579 goto fail;
5580 }
5581 }
5582 Py_DECREF(file_action);
5583 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005584
Serhiy Storchakaef347532018-05-01 16:45:04 +03005585 Py_DECREF(seq);
5586 return 0;
5587
5588fail:
5589 Py_DECREF(seq);
5590 Py_DECREF(file_action);
5591 (void)posix_spawn_file_actions_destroy(file_actionsp);
5592 return -1;
5593}
5594
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005595
5596static PyObject *
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005597py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
5598 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005599 PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005600 PyObject *setsigdef, PyObject *scheduler)
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005601{
Victor Stinner325e4ba2019-02-01 15:47:24 +01005602 const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005603 EXECV_CHAR **argvlist = NULL;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005604 EXECV_CHAR **envlist = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005605 posix_spawn_file_actions_t file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005606 posix_spawn_file_actions_t *file_actionsp = NULL;
Pablo Galindo254a4662018-09-07 16:44:24 +01005607 posix_spawnattr_t attr;
5608 posix_spawnattr_t *attrp = NULL;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005609 Py_ssize_t argc, envc;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005610 PyObject *result = NULL;
Pablo Galindocb970732018-06-19 09:19:50 +01005611 PyObject *temp_buffer = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005612 pid_t pid;
5613 int err_code;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005614
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005615 /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
Serhiy Storchakaef347532018-05-01 16:45:04 +03005616 argv is a list or tuple of strings and env is a dictionary
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005617 like posix.environ. */
5618
Serhiy Storchakaef347532018-05-01 16:45:04 +03005619 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005620 PyErr_Format(PyExc_TypeError,
5621 "%s: argv must be a tuple or list", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005622 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005623 }
5624 argc = PySequence_Size(argv);
5625 if (argc < 1) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005626 PyErr_Format(PyExc_ValueError,
5627 "%s: argv must not be empty", func_name);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005628 return NULL;
5629 }
5630
5631 if (!PyMapping_Check(env)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005632 PyErr_Format(PyExc_TypeError,
5633 "%s: environment must be a mapping object", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005634 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005635 }
5636
5637 argvlist = parse_arglist(argv, &argc);
5638 if (argvlist == NULL) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005639 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005640 }
5641 if (!argvlist[0][0]) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005642 PyErr_Format(PyExc_ValueError,
5643 "%s: argv first element cannot be empty", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005644 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005645 }
5646
5647 envlist = parse_envlist(env, &envc);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005648 if (envlist == NULL) {
5649 goto exit;
5650 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005651
Anthony Shaw948ed8c2019-05-10 12:00:06 +10005652 if (file_actions != NULL && file_actions != Py_None) {
Pablo Galindocb970732018-06-19 09:19:50 +01005653 /* There is a bug in old versions of glibc that makes some of the
5654 * helper functions for manipulating file actions not copy the provided
5655 * buffers. The problem is that posix_spawn_file_actions_addopen does not
5656 * copy the value of path for some old versions of glibc (<2.20).
5657 * The use of temp_buffer here is a workaround that keeps the
5658 * python objects that own the buffers alive until posix_spawn gets called.
5659 * Check https://bugs.python.org/issue33630 and
5660 * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
5661 temp_buffer = PyList_New(0);
5662 if (!temp_buffer) {
5663 goto exit;
5664 }
5665 if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005666 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005667 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005668 file_actionsp = &file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005669 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005670
Victor Stinner325e4ba2019-02-01 15:47:24 +01005671 if (parse_posix_spawn_flags(func_name, setpgroup, resetids, setsid,
5672 setsigmask, setsigdef, scheduler, &attr)) {
Pablo Galindo254a4662018-09-07 16:44:24 +01005673 goto exit;
5674 }
5675 attrp = &attr;
5676
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005677 _Py_BEGIN_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005678#ifdef HAVE_POSIX_SPAWNP
5679 if (use_posix_spawnp) {
5680 err_code = posix_spawnp(&pid, path->narrow,
5681 file_actionsp, attrp, argvlist, envlist);
5682 }
5683 else
5684#endif /* HAVE_POSIX_SPAWNP */
5685 {
5686 err_code = posix_spawn(&pid, path->narrow,
5687 file_actionsp, attrp, argvlist, envlist);
5688 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005689 _Py_END_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005690
Serhiy Storchakaef347532018-05-01 16:45:04 +03005691 if (err_code) {
5692 errno = err_code;
5693 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005694 goto exit;
5695 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08005696#ifdef _Py_MEMORY_SANITIZER
5697 __msan_unpoison(&pid, sizeof(pid));
5698#endif
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005699 result = PyLong_FromPid(pid);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005700
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005701exit:
Serhiy Storchakaef347532018-05-01 16:45:04 +03005702 if (file_actionsp) {
5703 (void)posix_spawn_file_actions_destroy(file_actionsp);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005704 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005705 if (attrp) {
5706 (void)posix_spawnattr_destroy(attrp);
5707 }
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005708 if (envlist) {
5709 free_string_array(envlist, envc);
5710 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005711 if (argvlist) {
5712 free_string_array(argvlist, argc);
5713 }
Pablo Galindocb970732018-06-19 09:19:50 +01005714 Py_XDECREF(temp_buffer);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005715 return result;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005716}
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005717
5718
5719/*[clinic input]
5720
5721os.posix_spawn
5722 path: path_t
5723 Path of executable file.
5724 argv: object
5725 Tuple or list of strings.
5726 env: object
5727 Dictionary of strings mapping to strings.
5728 /
5729 *
5730 file_actions: object(c_default='NULL') = ()
5731 A sequence of file action tuples.
5732 setpgroup: object = NULL
5733 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5734 resetids: bool(accept={int}) = False
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005735 If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
5736 setsid: bool(accept={int}) = False
5737 If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005738 setsigmask: object(c_default='NULL') = ()
5739 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5740 setsigdef: object(c_default='NULL') = ()
5741 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5742 scheduler: object = NULL
5743 A tuple with the scheduler policy (optional) and parameters.
5744
5745Execute the program specified by path in a new process.
5746[clinic start generated code]*/
5747
5748static PyObject *
5749os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
5750 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005751 PyObject *setpgroup, int resetids, int setsid,
5752 PyObject *setsigmask, PyObject *setsigdef,
5753 PyObject *scheduler)
5754/*[clinic end generated code: output=14a1098c566bc675 input=8c6305619a00ad04]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005755{
5756 return py_posix_spawn(0, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005757 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005758 scheduler);
5759}
5760 #endif /* HAVE_POSIX_SPAWN */
5761
5762
5763
5764#ifdef HAVE_POSIX_SPAWNP
5765/*[clinic input]
5766
5767os.posix_spawnp
5768 path: path_t
5769 Path of executable file.
5770 argv: object
5771 Tuple or list of strings.
5772 env: object
5773 Dictionary of strings mapping to strings.
5774 /
5775 *
5776 file_actions: object(c_default='NULL') = ()
5777 A sequence of file action tuples.
5778 setpgroup: object = NULL
5779 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5780 resetids: bool(accept={int}) = False
5781 If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005782 setsid: bool(accept={int}) = False
5783 If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005784 setsigmask: object(c_default='NULL') = ()
5785 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5786 setsigdef: object(c_default='NULL') = ()
5787 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5788 scheduler: object = NULL
5789 A tuple with the scheduler policy (optional) and parameters.
5790
5791Execute the program specified by path in a new process.
5792[clinic start generated code]*/
5793
5794static PyObject *
5795os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
5796 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005797 PyObject *setpgroup, int resetids, int setsid,
5798 PyObject *setsigmask, PyObject *setsigdef,
5799 PyObject *scheduler)
5800/*[clinic end generated code: output=7b9aaefe3031238d input=c1911043a22028da]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005801{
5802 return py_posix_spawn(1, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005803 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005804 scheduler);
5805}
5806#endif /* HAVE_POSIX_SPAWNP */
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005807
pxinwrf2d7ac72019-05-21 18:46:37 +08005808#ifdef HAVE_RTPSPAWN
5809static intptr_t
5810_rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
5811 const char *envp[])
5812{
5813 RTP_ID rtpid;
5814 int status;
5815 pid_t res;
5816 int async_err = 0;
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005817
pxinwrf2d7ac72019-05-21 18:46:37 +08005818 /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
5819 uStackSize=0 cannot be used, the default stack size is too small for
5820 Python. */
5821 if (envp) {
5822 rtpid = rtpSpawn(rtpFileName, argv, envp,
5823 100, 0x1000000, 0, VX_FP_TASK);
5824 }
5825 else {
5826 rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
5827 100, 0x1000000, 0, VX_FP_TASK);
5828 }
5829 if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
5830 do {
5831 res = waitpid((pid_t)rtpid, &status, 0);
5832 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
5833
5834 if (res < 0)
5835 return RTP_ID_ERROR;
5836 return ((intptr_t)status);
5837 }
5838 return ((intptr_t)rtpid);
5839}
5840#endif
5841
5842#if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
Larry Hastings2f936352014-08-05 14:04:04 +10005843/*[clinic input]
5844os.spawnv
5845
5846 mode: int
5847 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005848 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005849 Path of executable file.
5850 argv: object
5851 Tuple or list of strings.
5852 /
5853
5854Execute the program specified by path in a new process.
5855[clinic start generated code]*/
5856
Larry Hastings2f936352014-08-05 14:04:04 +10005857static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005858os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
5859/*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005860{
Steve Dowercc16be82016-09-08 10:35:16 -07005861 EXECV_CHAR **argvlist;
Larry Hastings2f936352014-08-05 14:04:04 +10005862 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00005863 Py_ssize_t argc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005864 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005865 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Guido van Rossuma1065681999-01-25 23:20:23 +00005866
Victor Stinner8c62be82010-05-06 00:08:46 +00005867 /* spawnv has three arguments: (mode, path, argv), where
5868 argv is a list or tuple of strings. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005869
Victor Stinner8c62be82010-05-06 00:08:46 +00005870 if (PyList_Check(argv)) {
5871 argc = PyList_Size(argv);
5872 getitem = PyList_GetItem;
5873 }
5874 else if (PyTuple_Check(argv)) {
5875 argc = PyTuple_Size(argv);
5876 getitem = PyTuple_GetItem;
5877 }
5878 else {
5879 PyErr_SetString(PyExc_TypeError,
5880 "spawnv() arg 2 must be a tuple or list");
Victor Stinner8c62be82010-05-06 00:08:46 +00005881 return NULL;
5882 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005883 if (argc == 0) {
5884 PyErr_SetString(PyExc_ValueError,
5885 "spawnv() arg 2 cannot be empty");
5886 return NULL;
5887 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005888
Steve Dowercc16be82016-09-08 10:35:16 -07005889 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005890 if (argvlist == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005891 return PyErr_NoMemory();
5892 }
5893 for (i = 0; i < argc; i++) {
5894 if (!fsconvert_strdup((*getitem)(argv, i),
5895 &argvlist[i])) {
5896 free_string_array(argvlist, i);
5897 PyErr_SetString(
5898 PyExc_TypeError,
5899 "spawnv() arg 2 must contain only strings");
Victor Stinner8c62be82010-05-06 00:08:46 +00005900 return NULL;
5901 }
Steve Dower93ff8722016-11-19 19:03:54 -08005902 if (i == 0 && !argvlist[0][0]) {
Victor Stinner8acb4cf2017-06-15 15:30:40 +02005903 free_string_array(argvlist, i + 1);
Steve Dower93ff8722016-11-19 19:03:54 -08005904 PyErr_SetString(
5905 PyExc_ValueError,
5906 "spawnv() arg 2 first element cannot be empty");
5907 return NULL;
5908 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005909 }
5910 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005911
pxinwrf2d7ac72019-05-21 18:46:37 +08005912#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00005913 if (mode == _OLD_P_OVERLAY)
5914 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08005915#endif
Tim Peters5aa91602002-01-30 05:46:57 +00005916
Victor Stinner8c62be82010-05-06 00:08:46 +00005917 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07005918 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005919#ifdef HAVE_WSPAWNV
5920 spawnval = _wspawnv(mode, path->wide, argvlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08005921#elif defined(HAVE_RTPSPAWN)
5922 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
Steve Dowercc16be82016-09-08 10:35:16 -07005923#else
5924 spawnval = _spawnv(mode, path->narrow, argvlist);
5925#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07005926 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00005927 Py_END_ALLOW_THREADS
Tim Peters5aa91602002-01-30 05:46:57 +00005928
Victor Stinner8c62be82010-05-06 00:08:46 +00005929 free_string_array(argvlist, argc);
Guido van Rossuma1065681999-01-25 23:20:23 +00005930
Victor Stinner8c62be82010-05-06 00:08:46 +00005931 if (spawnval == -1)
5932 return posix_error();
5933 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01005934 return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00005935}
5936
Larry Hastings2f936352014-08-05 14:04:04 +10005937/*[clinic input]
5938os.spawnve
5939
5940 mode: int
5941 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005942 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005943 Path of executable file.
5944 argv: object
5945 Tuple or list of strings.
5946 env: object
5947 Dictionary of strings mapping to strings.
5948 /
5949
5950Execute the program specified by path in a new process.
5951[clinic start generated code]*/
5952
Larry Hastings2f936352014-08-05 14:04:04 +10005953static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005954os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005955 PyObject *env)
Steve Dowercc16be82016-09-08 10:35:16 -07005956/*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005957{
Steve Dowercc16be82016-09-08 10:35:16 -07005958 EXECV_CHAR **argvlist;
5959 EXECV_CHAR **envlist;
Victor Stinner8c62be82010-05-06 00:08:46 +00005960 PyObject *res = NULL;
Antoine Pitrou22e41552010-08-15 18:07:50 +00005961 Py_ssize_t argc, i, envc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005962 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005963 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005964 Py_ssize_t lastarg = 0;
Guido van Rossuma1065681999-01-25 23:20:23 +00005965
Victor Stinner8c62be82010-05-06 00:08:46 +00005966 /* spawnve has four arguments: (mode, path, argv, env), where
5967 argv is a list or tuple of strings and env is a dictionary
5968 like posix.environ. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005969
Victor Stinner8c62be82010-05-06 00:08:46 +00005970 if (PyList_Check(argv)) {
5971 argc = PyList_Size(argv);
5972 getitem = PyList_GetItem;
5973 }
5974 else if (PyTuple_Check(argv)) {
5975 argc = PyTuple_Size(argv);
5976 getitem = PyTuple_GetItem;
5977 }
5978 else {
5979 PyErr_SetString(PyExc_TypeError,
5980 "spawnve() arg 2 must be a tuple or list");
5981 goto fail_0;
5982 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005983 if (argc == 0) {
5984 PyErr_SetString(PyExc_ValueError,
5985 "spawnve() arg 2 cannot be empty");
5986 goto fail_0;
5987 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005988 if (!PyMapping_Check(env)) {
5989 PyErr_SetString(PyExc_TypeError,
5990 "spawnve() arg 3 must be a mapping object");
5991 goto fail_0;
5992 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005993
Steve Dowercc16be82016-09-08 10:35:16 -07005994 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005995 if (argvlist == NULL) {
5996 PyErr_NoMemory();
5997 goto fail_0;
5998 }
5999 for (i = 0; i < argc; i++) {
6000 if (!fsconvert_strdup((*getitem)(argv, i),
6001 &argvlist[i]))
6002 {
6003 lastarg = i;
6004 goto fail_1;
6005 }
Steve Dowerbce26262016-11-19 19:17:26 -08006006 if (i == 0 && !argvlist[0][0]) {
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006007 lastarg = i + 1;
Steve Dowerbce26262016-11-19 19:17:26 -08006008 PyErr_SetString(
6009 PyExc_ValueError,
6010 "spawnv() arg 2 first element cannot be empty");
6011 goto fail_1;
6012 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006013 }
6014 lastarg = argc;
6015 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00006016
Victor Stinner8c62be82010-05-06 00:08:46 +00006017 envlist = parse_envlist(env, &envc);
6018 if (envlist == NULL)
6019 goto fail_1;
Guido van Rossuma1065681999-01-25 23:20:23 +00006020
pxinwrf2d7ac72019-05-21 18:46:37 +08006021#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00006022 if (mode == _OLD_P_OVERLAY)
6023 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08006024#endif
Tim Peters25059d32001-12-07 20:35:43 +00006025
Victor Stinner8c62be82010-05-06 00:08:46 +00006026 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07006027 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07006028#ifdef HAVE_WSPAWNV
6029 spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08006030#elif defined(HAVE_RTPSPAWN)
6031 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
6032 (const char **)envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07006033#else
6034 spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
6035#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07006036 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00006037 Py_END_ALLOW_THREADS
Tim Peters25059d32001-12-07 20:35:43 +00006038
Victor Stinner8c62be82010-05-06 00:08:46 +00006039 if (spawnval == -1)
6040 (void) posix_error();
6041 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01006042 res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00006043
Victor Stinner8c62be82010-05-06 00:08:46 +00006044 while (--envc >= 0)
6045 PyMem_DEL(envlist[envc]);
6046 PyMem_DEL(envlist);
Guido van Rossum0847c5c2002-12-13 18:36:22 +00006047 fail_1:
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006048 free_string_array(argvlist, lastarg);
Martin v. Löwis114619e2002-10-07 06:44:21 +00006049 fail_0:
Victor Stinner8c62be82010-05-06 00:08:46 +00006050 return res;
Guido van Rossuma1065681999-01-25 23:20:23 +00006051}
Andrew MacIntyre69e18c92004-04-04 07:11:43 +00006052
Guido van Rossuma1065681999-01-25 23:20:23 +00006053#endif /* HAVE_SPAWNV */
6054
6055
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006056#ifdef HAVE_FORK
Gregory P. Smith163468a2017-05-29 10:03:41 -07006057
6058/* Helper function to validate arguments.
6059 Returns 0 on success. non-zero on failure with a TypeError raised.
6060 If obj is non-NULL it must be callable. */
6061static int
6062check_null_or_callable(PyObject *obj, const char* obj_name)
6063{
6064 if (obj && !PyCallable_Check(obj)) {
6065 PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
Eddie Elizondob3966632019-11-05 07:16:14 -08006066 obj_name, _PyType_Name(Py_TYPE(obj)));
Gregory P. Smith163468a2017-05-29 10:03:41 -07006067 return -1;
6068 }
6069 return 0;
6070}
6071
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006072/*[clinic input]
6073os.register_at_fork
6074
Gregory P. Smith163468a2017-05-29 10:03:41 -07006075 *
6076 before: object=NULL
6077 A callable to be called in the parent before the fork() syscall.
6078 after_in_child: object=NULL
6079 A callable to be called in the child after fork().
6080 after_in_parent: object=NULL
6081 A callable to be called in the parent after fork().
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006082
Gregory P. Smith163468a2017-05-29 10:03:41 -07006083Register callables to be called when forking a new process.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006084
Gregory P. Smith163468a2017-05-29 10:03:41 -07006085'before' callbacks are called in reverse order.
6086'after_in_child' and 'after_in_parent' callbacks are called in order.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006087
6088[clinic start generated code]*/
6089
6090static PyObject *
Gregory P. Smith163468a2017-05-29 10:03:41 -07006091os_register_at_fork_impl(PyObject *module, PyObject *before,
6092 PyObject *after_in_child, PyObject *after_in_parent)
6093/*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006094{
6095 PyInterpreterState *interp;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006096
Gregory P. Smith163468a2017-05-29 10:03:41 -07006097 if (!before && !after_in_child && !after_in_parent) {
6098 PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
6099 return NULL;
6100 }
6101 if (check_null_or_callable(before, "before") ||
6102 check_null_or_callable(after_in_child, "after_in_child") ||
6103 check_null_or_callable(after_in_parent, "after_in_parent")) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006104 return NULL;
6105 }
Victor Stinnercaba55b2018-08-03 15:33:52 +02006106 interp = _PyInterpreterState_Get();
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006107
Gregory P. Smith163468a2017-05-29 10:03:41 -07006108 if (register_at_forker(&interp->before_forkers, before)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006109 return NULL;
6110 }
Gregory P. Smith163468a2017-05-29 10:03:41 -07006111 if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006112 return NULL;
Gregory P. Smith163468a2017-05-29 10:03:41 -07006113 }
6114 if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
6115 return NULL;
6116 }
6117 Py_RETURN_NONE;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006118}
6119#endif /* HAVE_FORK */
6120
6121
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006122#ifdef HAVE_FORK1
Larry Hastings2f936352014-08-05 14:04:04 +10006123/*[clinic input]
6124os.fork1
6125
6126Fork a child process with a single multiplexed (i.e., not bound) thread.
6127
6128Return 0 to child process and PID of child to parent process.
6129[clinic start generated code]*/
6130
Larry Hastings2f936352014-08-05 14:04:04 +10006131static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006132os_fork1_impl(PyObject *module)
6133/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006134{
Victor Stinner8c62be82010-05-06 00:08:46 +00006135 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006136
Eric Snow59032962018-09-14 14:17:20 -07006137 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6138 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6139 return NULL;
6140 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006141 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006142 pid = fork1();
6143 if (pid == 0) {
6144 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006145 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006146 } else {
6147 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006148 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006149 }
6150 if (pid == -1)
6151 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006152 return PyLong_FromPid(pid);
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006153}
Larry Hastings2f936352014-08-05 14:04:04 +10006154#endif /* HAVE_FORK1 */
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006155
6156
Guido van Rossumad0ee831995-03-01 10:34:45 +00006157#ifdef HAVE_FORK
Larry Hastings2f936352014-08-05 14:04:04 +10006158/*[clinic input]
6159os.fork
6160
6161Fork a child process.
6162
6163Return 0 to child process and PID of child to parent process.
6164[clinic start generated code]*/
6165
Larry Hastings2f936352014-08-05 14:04:04 +10006166static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006167os_fork_impl(PyObject *module)
6168/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006169{
Victor Stinner8c62be82010-05-06 00:08:46 +00006170 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006171
Eric Snow59032962018-09-14 14:17:20 -07006172 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6173 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6174 return NULL;
6175 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006176 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006177 pid = fork();
6178 if (pid == 0) {
6179 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006180 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006181 } else {
6182 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006183 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006184 }
6185 if (pid == -1)
6186 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006187 return PyLong_FromPid(pid);
Guido van Rossum85e3b011991-06-03 12:42:10 +00006188}
Larry Hastings2f936352014-08-05 14:04:04 +10006189#endif /* HAVE_FORK */
6190
Guido van Rossum85e3b011991-06-03 12:42:10 +00006191
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006192#ifdef HAVE_SCHED_H
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006193#ifdef HAVE_SCHED_GET_PRIORITY_MAX
Larry Hastings2f936352014-08-05 14:04:04 +10006194/*[clinic input]
6195os.sched_get_priority_max
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006196
Larry Hastings2f936352014-08-05 14:04:04 +10006197 policy: int
6198
6199Get the maximum scheduling priority for policy.
6200[clinic start generated code]*/
6201
Larry Hastings2f936352014-08-05 14:04:04 +10006202static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006203os_sched_get_priority_max_impl(PyObject *module, int policy)
6204/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006205{
6206 int max;
6207
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006208 max = sched_get_priority_max(policy);
6209 if (max < 0)
6210 return posix_error();
6211 return PyLong_FromLong(max);
6212}
6213
Larry Hastings2f936352014-08-05 14:04:04 +10006214
6215/*[clinic input]
6216os.sched_get_priority_min
6217
6218 policy: int
6219
6220Get the minimum scheduling priority for policy.
6221[clinic start generated code]*/
6222
Larry Hastings2f936352014-08-05 14:04:04 +10006223static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006224os_sched_get_priority_min_impl(PyObject *module, int policy)
6225/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006226{
6227 int min = sched_get_priority_min(policy);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006228 if (min < 0)
6229 return posix_error();
6230 return PyLong_FromLong(min);
6231}
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006232#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
6233
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006234
Larry Hastings2f936352014-08-05 14:04:04 +10006235#ifdef HAVE_SCHED_SETSCHEDULER
6236/*[clinic input]
6237os.sched_getscheduler
6238 pid: pid_t
6239 /
6240
Min ho Kimc4cacc82019-07-31 08:16:13 +10006241Get the scheduling policy for the process identified by pid.
Larry Hastings2f936352014-08-05 14:04:04 +10006242
6243Passing 0 for pid returns the scheduling policy for the calling process.
6244[clinic start generated code]*/
6245
Larry Hastings2f936352014-08-05 14:04:04 +10006246static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006247os_sched_getscheduler_impl(PyObject *module, pid_t pid)
Min ho Kimc4cacc82019-07-31 08:16:13 +10006248/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=8d99dac505485ac8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006249{
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006250 int policy;
6251
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006252 policy = sched_getscheduler(pid);
6253 if (policy < 0)
6254 return posix_error();
6255 return PyLong_FromLong(policy);
6256}
Larry Hastings2f936352014-08-05 14:04:04 +10006257#endif /* HAVE_SCHED_SETSCHEDULER */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006258
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006259
William Orr81574b82018-10-01 22:19:56 -07006260#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Larry Hastings2f936352014-08-05 14:04:04 +10006261/*[clinic input]
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006262class os.sched_param "PyObject *" "SchedParamType"
Larry Hastings2f936352014-08-05 14:04:04 +10006263
6264@classmethod
6265os.sched_param.__new__
6266
6267 sched_priority: object
6268 A scheduling parameter.
6269
Eddie Elizondob3966632019-11-05 07:16:14 -08006270Currently has only one field: sched_priority
Larry Hastings2f936352014-08-05 14:04:04 +10006271[clinic start generated code]*/
6272
Larry Hastings2f936352014-08-05 14:04:04 +10006273static PyObject *
6274os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
Eddie Elizondob3966632019-11-05 07:16:14 -08006275/*[clinic end generated code: output=48f4067d60f48c13 input=eb42909a2c0e3e6c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006276{
6277 PyObject *res;
6278
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006279 res = PyStructSequence_New(type);
6280 if (!res)
6281 return NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10006282 Py_INCREF(sched_priority);
6283 PyStructSequence_SET_ITEM(res, 0, sched_priority);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006284 return res;
6285}
6286
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03006287PyDoc_VAR(os_sched_param__doc__);
6288
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006289static PyStructSequence_Field sched_param_fields[] = {
6290 {"sched_priority", "the scheduling priority"},
6291 {0}
6292};
6293
6294static PyStructSequence_Desc sched_param_desc = {
6295 "sched_param", /* name */
Larry Hastings2f936352014-08-05 14:04:04 +10006296 os_sched_param__doc__, /* doc */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006297 sched_param_fields,
6298 1
6299};
6300
6301static int
6302convert_sched_param(PyObject *param, struct sched_param *res)
6303{
6304 long priority;
6305
Eddie Elizondob3966632019-11-05 07:16:14 -08006306 PyObject *SchedParamType = _posixstate_global->SchedParamType;
6307 if (Py_TYPE(param) != (PyTypeObject *)SchedParamType) {
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006308 PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
6309 return 0;
6310 }
6311 priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
6312 if (priority == -1 && PyErr_Occurred())
6313 return 0;
6314 if (priority > INT_MAX || priority < INT_MIN) {
6315 PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
6316 return 0;
6317 }
6318 res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
6319 return 1;
6320}
William Orr81574b82018-10-01 22:19:56 -07006321#endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006322
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006323
6324#ifdef HAVE_SCHED_SETSCHEDULER
Larry Hastings2f936352014-08-05 14:04:04 +10006325/*[clinic input]
6326os.sched_setscheduler
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006327
Larry Hastings2f936352014-08-05 14:04:04 +10006328 pid: pid_t
6329 policy: int
6330 param: sched_param
6331 /
6332
6333Set the scheduling policy for the process identified by pid.
6334
6335If pid is 0, the calling process is changed.
6336param is an instance of sched_param.
6337[clinic start generated code]*/
6338
Larry Hastings2f936352014-08-05 14:04:04 +10006339static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006340os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
Larry Hastings89964c42015-04-14 18:07:59 -04006341 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006342/*[clinic end generated code: output=b0ac0a70d3b1d705 input=c581f9469a5327dd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006343{
Jesus Cea9c822272011-09-10 01:40:52 +02006344 /*
Jesus Cea54b01492011-09-10 01:53:19 +02006345 ** sched_setscheduler() returns 0 in Linux, but the previous
6346 ** scheduling policy under Solaris/Illumos, and others.
6347 ** On error, -1 is returned in all Operating Systems.
Jesus Cea9c822272011-09-10 01:40:52 +02006348 */
Larry Hastings2f936352014-08-05 14:04:04 +10006349 if (sched_setscheduler(pid, policy, param) == -1)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006350 return posix_error();
6351 Py_RETURN_NONE;
6352}
Larry Hastings2f936352014-08-05 14:04:04 +10006353#endif /* HAVE_SCHED_SETSCHEDULER*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006354
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006355
6356#ifdef HAVE_SCHED_SETPARAM
Larry Hastings2f936352014-08-05 14:04:04 +10006357/*[clinic input]
6358os.sched_getparam
6359 pid: pid_t
6360 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006361
Larry Hastings2f936352014-08-05 14:04:04 +10006362Returns scheduling parameters for the process identified by pid.
6363
6364If pid is 0, returns parameters for the calling process.
6365Return value is an instance of sched_param.
6366[clinic start generated code]*/
6367
Larry Hastings2f936352014-08-05 14:04:04 +10006368static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006369os_sched_getparam_impl(PyObject *module, pid_t pid)
6370/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006371{
6372 struct sched_param param;
6373 PyObject *result;
6374 PyObject *priority;
6375
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006376 if (sched_getparam(pid, &param))
6377 return posix_error();
Eddie Elizondob3966632019-11-05 07:16:14 -08006378 PyObject *SchedParamType = _posixstate_global->SchedParamType;
6379 result = PyStructSequence_New((PyTypeObject *)SchedParamType);
Larry Hastings2f936352014-08-05 14:04:04 +10006380 if (!result)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006381 return NULL;
6382 priority = PyLong_FromLong(param.sched_priority);
6383 if (!priority) {
Larry Hastings2f936352014-08-05 14:04:04 +10006384 Py_DECREF(result);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006385 return NULL;
6386 }
Larry Hastings2f936352014-08-05 14:04:04 +10006387 PyStructSequence_SET_ITEM(result, 0, priority);
6388 return result;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006389}
6390
Larry Hastings2f936352014-08-05 14:04:04 +10006391
6392/*[clinic input]
6393os.sched_setparam
6394 pid: pid_t
6395 param: sched_param
6396 /
6397
6398Set scheduling parameters for the process identified by pid.
6399
6400If pid is 0, sets parameters for the calling process.
6401param should be an instance of sched_param.
6402[clinic start generated code]*/
6403
Larry Hastings2f936352014-08-05 14:04:04 +10006404static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006405os_sched_setparam_impl(PyObject *module, pid_t pid,
Larry Hastings89964c42015-04-14 18:07:59 -04006406 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006407/*[clinic end generated code: output=8af013f78a32b591 input=6b8d6dfcecdc21bd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006408{
6409 if (sched_setparam(pid, param))
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006410 return posix_error();
6411 Py_RETURN_NONE;
6412}
Larry Hastings2f936352014-08-05 14:04:04 +10006413#endif /* HAVE_SCHED_SETPARAM */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006414
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006415
6416#ifdef HAVE_SCHED_RR_GET_INTERVAL
Larry Hastings2f936352014-08-05 14:04:04 +10006417/*[clinic input]
6418os.sched_rr_get_interval -> double
6419 pid: pid_t
6420 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006421
Larry Hastings2f936352014-08-05 14:04:04 +10006422Return the round-robin quantum for the process identified by pid, in seconds.
6423
6424Value returned is a float.
6425[clinic start generated code]*/
6426
Larry Hastings2f936352014-08-05 14:04:04 +10006427static double
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006428os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
6429/*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006430{
6431 struct timespec interval;
6432 if (sched_rr_get_interval(pid, &interval)) {
6433 posix_error();
6434 return -1.0;
6435 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006436#ifdef _Py_MEMORY_SANITIZER
6437 __msan_unpoison(&interval, sizeof(interval));
6438#endif
Larry Hastings2f936352014-08-05 14:04:04 +10006439 return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
6440}
6441#endif /* HAVE_SCHED_RR_GET_INTERVAL */
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006442
Larry Hastings2f936352014-08-05 14:04:04 +10006443
6444/*[clinic input]
6445os.sched_yield
6446
6447Voluntarily relinquish the CPU.
6448[clinic start generated code]*/
6449
Larry Hastings2f936352014-08-05 14:04:04 +10006450static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006451os_sched_yield_impl(PyObject *module)
6452/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006453{
6454 if (sched_yield())
6455 return posix_error();
6456 Py_RETURN_NONE;
6457}
6458
Benjamin Peterson2740af82011-08-02 17:41:34 -05006459#ifdef HAVE_SCHED_SETAFFINITY
Antoine Pitrou84869872012-08-04 16:16:35 +02006460/* The minimum number of CPUs allocated in a cpu_set_t */
6461static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006462
Larry Hastings2f936352014-08-05 14:04:04 +10006463/*[clinic input]
6464os.sched_setaffinity
6465 pid: pid_t
6466 mask : object
6467 /
6468
6469Set the CPU affinity of the process identified by pid to mask.
6470
6471mask should be an iterable of integers identifying CPUs.
6472[clinic start generated code]*/
6473
Larry Hastings2f936352014-08-05 14:04:04 +10006474static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006475os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
6476/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006477{
Antoine Pitrou84869872012-08-04 16:16:35 +02006478 int ncpus;
6479 size_t setsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006480 cpu_set_t *cpu_set = NULL;
6481 PyObject *iterator = NULL, *item;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006482
Larry Hastings2f936352014-08-05 14:04:04 +10006483 iterator = PyObject_GetIter(mask);
Antoine Pitrou84869872012-08-04 16:16:35 +02006484 if (iterator == NULL)
6485 return NULL;
6486
6487 ncpus = NCPUS_START;
6488 setsize = CPU_ALLOC_SIZE(ncpus);
Larry Hastings2f936352014-08-05 14:04:04 +10006489 cpu_set = CPU_ALLOC(ncpus);
6490 if (cpu_set == NULL) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006491 PyErr_NoMemory();
6492 goto error;
6493 }
Larry Hastings2f936352014-08-05 14:04:04 +10006494 CPU_ZERO_S(setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006495
6496 while ((item = PyIter_Next(iterator))) {
6497 long cpu;
6498 if (!PyLong_Check(item)) {
6499 PyErr_Format(PyExc_TypeError,
6500 "expected an iterator of ints, "
6501 "but iterator yielded %R",
6502 Py_TYPE(item));
6503 Py_DECREF(item);
6504 goto error;
6505 }
6506 cpu = PyLong_AsLong(item);
6507 Py_DECREF(item);
6508 if (cpu < 0) {
6509 if (!PyErr_Occurred())
6510 PyErr_SetString(PyExc_ValueError, "negative CPU number");
6511 goto error;
6512 }
6513 if (cpu > INT_MAX - 1) {
6514 PyErr_SetString(PyExc_OverflowError, "CPU number too large");
6515 goto error;
6516 }
6517 if (cpu >= ncpus) {
6518 /* Grow CPU mask to fit the CPU number */
6519 int newncpus = ncpus;
6520 cpu_set_t *newmask;
6521 size_t newsetsize;
6522 while (newncpus <= cpu) {
6523 if (newncpus > INT_MAX / 2)
6524 newncpus = cpu + 1;
6525 else
6526 newncpus = newncpus * 2;
6527 }
6528 newmask = CPU_ALLOC(newncpus);
6529 if (newmask == NULL) {
6530 PyErr_NoMemory();
6531 goto error;
6532 }
6533 newsetsize = CPU_ALLOC_SIZE(newncpus);
6534 CPU_ZERO_S(newsetsize, newmask);
Larry Hastings2f936352014-08-05 14:04:04 +10006535 memcpy(newmask, cpu_set, setsize);
6536 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006537 setsize = newsetsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006538 cpu_set = newmask;
Antoine Pitrou84869872012-08-04 16:16:35 +02006539 ncpus = newncpus;
6540 }
Larry Hastings2f936352014-08-05 14:04:04 +10006541 CPU_SET_S(cpu, setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006542 }
Brandt Bucher45a30af2019-06-27 09:10:57 -07006543 if (PyErr_Occurred()) {
6544 goto error;
6545 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006546 Py_CLEAR(iterator);
6547
Larry Hastings2f936352014-08-05 14:04:04 +10006548 if (sched_setaffinity(pid, setsize, cpu_set)) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006549 posix_error();
6550 goto error;
6551 }
Larry Hastings2f936352014-08-05 14:04:04 +10006552 CPU_FREE(cpu_set);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006553 Py_RETURN_NONE;
Antoine Pitrou84869872012-08-04 16:16:35 +02006554
6555error:
Larry Hastings2f936352014-08-05 14:04:04 +10006556 if (cpu_set)
6557 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006558 Py_XDECREF(iterator);
6559 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006560}
6561
Larry Hastings2f936352014-08-05 14:04:04 +10006562
6563/*[clinic input]
6564os.sched_getaffinity
6565 pid: pid_t
6566 /
6567
Charles-François Natalidc87e4b2015-07-13 21:01:39 +01006568Return the affinity of the process identified by pid (or the current process if zero).
Larry Hastings2f936352014-08-05 14:04:04 +10006569
6570The affinity is returned as a set of CPU identifiers.
6571[clinic start generated code]*/
6572
Larry Hastings2f936352014-08-05 14:04:04 +10006573static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006574os_sched_getaffinity_impl(PyObject *module, pid_t pid)
Serhiy Storchaka2954f832016-07-07 18:20:03 +03006575/*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006576{
Antoine Pitrou84869872012-08-04 16:16:35 +02006577 int cpu, ncpus, count;
6578 size_t setsize;
6579 cpu_set_t *mask = NULL;
6580 PyObject *res = NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006581
Antoine Pitrou84869872012-08-04 16:16:35 +02006582 ncpus = NCPUS_START;
6583 while (1) {
6584 setsize = CPU_ALLOC_SIZE(ncpus);
6585 mask = CPU_ALLOC(ncpus);
6586 if (mask == NULL)
6587 return PyErr_NoMemory();
6588 if (sched_getaffinity(pid, setsize, mask) == 0)
6589 break;
6590 CPU_FREE(mask);
6591 if (errno != EINVAL)
6592 return posix_error();
6593 if (ncpus > INT_MAX / 2) {
6594 PyErr_SetString(PyExc_OverflowError, "could not allocate "
6595 "a large enough CPU set");
6596 return NULL;
6597 }
6598 ncpus = ncpus * 2;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006599 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006600
6601 res = PySet_New(NULL);
6602 if (res == NULL)
6603 goto error;
6604 for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
6605 if (CPU_ISSET_S(cpu, setsize, mask)) {
6606 PyObject *cpu_num = PyLong_FromLong(cpu);
6607 --count;
6608 if (cpu_num == NULL)
6609 goto error;
6610 if (PySet_Add(res, cpu_num)) {
6611 Py_DECREF(cpu_num);
6612 goto error;
6613 }
6614 Py_DECREF(cpu_num);
6615 }
6616 }
6617 CPU_FREE(mask);
6618 return res;
6619
6620error:
6621 if (mask)
6622 CPU_FREE(mask);
6623 Py_XDECREF(res);
6624 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006625}
6626
Benjamin Peterson2740af82011-08-02 17:41:34 -05006627#endif /* HAVE_SCHED_SETAFFINITY */
6628
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006629#endif /* HAVE_SCHED_H */
6630
Larry Hastings2f936352014-08-05 14:04:04 +10006631
Neal Norwitzb59798b2003-03-21 01:43:31 +00006632/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
Neal Norwitz2deaddb2003-03-21 03:08:31 +00006633/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
6634#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
Neal Norwitzb59798b2003-03-21 01:43:31 +00006635#define DEV_PTY_FILE "/dev/ptc"
6636#define HAVE_DEV_PTMX
6637#else
6638#define DEV_PTY_FILE "/dev/ptmx"
6639#endif
6640
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006641#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
Fred Drake8cef4cf2000-06-28 16:40:38 +00006642#ifdef HAVE_PTY_H
6643#include <pty.h>
6644#else
6645#ifdef HAVE_LIBUTIL_H
6646#include <libutil.h>
Ronald Oussoren755740f2010-02-07 19:56:39 +00006647#else
6648#ifdef HAVE_UTIL_H
6649#include <util.h>
6650#endif /* HAVE_UTIL_H */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006651#endif /* HAVE_LIBUTIL_H */
6652#endif /* HAVE_PTY_H */
Martin v. Löwis14e73b12003-01-01 09:51:12 +00006653#ifdef HAVE_STROPTS_H
6654#include <stropts.h>
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006655#endif
ngie-eign7745ec42018-02-14 11:54:28 -08006656#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006657
Larry Hastings2f936352014-08-05 14:04:04 +10006658
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006659#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
Larry Hastings2f936352014-08-05 14:04:04 +10006660/*[clinic input]
6661os.openpty
6662
6663Open a pseudo-terminal.
6664
6665Return a tuple of (master_fd, slave_fd) containing open file descriptors
6666for both the master and slave ends.
6667[clinic start generated code]*/
6668
Larry Hastings2f936352014-08-05 14:04:04 +10006669static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006670os_openpty_impl(PyObject *module)
6671/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006672{
Victor Stinnerdaf45552013-08-28 00:53:59 +02006673 int master_fd = -1, slave_fd = -1;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006674#ifndef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006675 char * slave_name;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006676#endif
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006677#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006678 PyOS_sighandler_t sig_saved;
Jakub Kulík6f9bc722018-12-31 03:16:40 +01006679#if defined(__sun) && defined(__SVR4)
Victor Stinner8c62be82010-05-06 00:08:46 +00006680 extern char *ptsname(int fildes);
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006681#endif
6682#endif
Thomas Wouters70c21a12000-07-14 14:28:33 +00006683
Thomas Wouters70c21a12000-07-14 14:28:33 +00006684#ifdef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006685 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006686 goto posix_error;
6687
6688 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6689 goto error;
6690 if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
6691 goto error;
6692
Neal Norwitzb59798b2003-03-21 01:43:31 +00006693#elif defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006694 slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
6695 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006696 goto posix_error;
6697 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6698 goto error;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006699
Victor Stinnerdaf45552013-08-28 00:53:59 +02006700 slave_fd = _Py_open(slave_name, O_RDWR);
Victor Stinner8c62be82010-05-06 00:08:46 +00006701 if (slave_fd < 0)
Victor Stinnera555cfc2015-03-18 00:22:14 +01006702 goto error;
Victor Stinnerdaf45552013-08-28 00:53:59 +02006703
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006704#else
Victor Stinner000de532013-11-25 23:19:58 +01006705 master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
Victor Stinner8c62be82010-05-06 00:08:46 +00006706 if (master_fd < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006707 goto posix_error;
6708
Victor Stinner8c62be82010-05-06 00:08:46 +00006709 sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006710
Victor Stinner8c62be82010-05-06 00:08:46 +00006711 /* change permission of slave */
6712 if (grantpt(master_fd) < 0) {
6713 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006714 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006715 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006716
Victor Stinner8c62be82010-05-06 00:08:46 +00006717 /* unlock slave */
6718 if (unlockpt(master_fd) < 0) {
6719 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006720 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006721 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006722
Victor Stinner8c62be82010-05-06 00:08:46 +00006723 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006724
Victor Stinner8c62be82010-05-06 00:08:46 +00006725 slave_name = ptsname(master_fd); /* get name of slave */
6726 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006727 goto posix_error;
6728
6729 slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
Victor Stinnera555cfc2015-03-18 00:22:14 +01006730 if (slave_fd == -1)
6731 goto error;
Victor Stinner000de532013-11-25 23:19:58 +01006732
6733 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6734 goto posix_error;
6735
Stefan Krahfb7c8ae2016-04-26 17:04:18 +02006736#if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
Victor Stinner8c62be82010-05-06 00:08:46 +00006737 ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
6738 ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
Neal Norwitz6700e472002-12-31 16:16:07 +00006739#ifndef __hpux
Victor Stinner8c62be82010-05-06 00:08:46 +00006740 ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
Neal Norwitz6700e472002-12-31 16:16:07 +00006741#endif /* __hpux */
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006742#endif /* HAVE_CYGWIN */
Thomas Wouters1e0c2f42000-07-24 16:06:23 +00006743#endif /* HAVE_OPENPTY */
Thomas Wouters70c21a12000-07-14 14:28:33 +00006744
Victor Stinner8c62be82010-05-06 00:08:46 +00006745 return Py_BuildValue("(ii)", master_fd, slave_fd);
Thomas Wouters70c21a12000-07-14 14:28:33 +00006746
Victor Stinnerdaf45552013-08-28 00:53:59 +02006747posix_error:
6748 posix_error();
6749error:
6750 if (master_fd != -1)
6751 close(master_fd);
6752 if (slave_fd != -1)
6753 close(slave_fd);
6754 return NULL;
Fred Drake8cef4cf2000-06-28 16:40:38 +00006755}
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006756#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006757
Larry Hastings2f936352014-08-05 14:04:04 +10006758
Fred Drake8cef4cf2000-06-28 16:40:38 +00006759#ifdef HAVE_FORKPTY
Larry Hastings2f936352014-08-05 14:04:04 +10006760/*[clinic input]
6761os.forkpty
6762
6763Fork a new process with a new pseudo-terminal as controlling tty.
6764
6765Returns a tuple of (pid, master_fd).
6766Like fork(), return pid of 0 to the child process,
6767and pid of child to the parent process.
6768To both, return fd of newly opened pseudo-terminal.
6769[clinic start generated code]*/
6770
Larry Hastings2f936352014-08-05 14:04:04 +10006771static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006772os_forkpty_impl(PyObject *module)
6773/*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006774{
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006775 int master_fd = -1;
Victor Stinner8c62be82010-05-06 00:08:46 +00006776 pid_t pid;
Tim Peters5aa91602002-01-30 05:46:57 +00006777
Eric Snow59032962018-09-14 14:17:20 -07006778 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6779 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6780 return NULL;
6781 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006782 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006783 pid = forkpty(&master_fd, NULL, NULL, NULL);
6784 if (pid == 0) {
6785 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006786 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006787 } else {
6788 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006789 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006790 }
6791 if (pid == -1)
6792 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006793 return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
Fred Drake8cef4cf2000-06-28 16:40:38 +00006794}
Larry Hastings2f936352014-08-05 14:04:04 +10006795#endif /* HAVE_FORKPTY */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006796
Ross Lagerwall7807c352011-03-17 20:20:30 +02006797
Guido van Rossumad0ee831995-03-01 10:34:45 +00006798#ifdef HAVE_GETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10006799/*[clinic input]
6800os.getegid
6801
6802Return the current process's effective group id.
6803[clinic start generated code]*/
6804
Larry Hastings2f936352014-08-05 14:04:04 +10006805static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006806os_getegid_impl(PyObject *module)
6807/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006808{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006809 return _PyLong_FromGid(getegid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006810}
Larry Hastings2f936352014-08-05 14:04:04 +10006811#endif /* HAVE_GETEGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006812
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006813
Guido van Rossumad0ee831995-03-01 10:34:45 +00006814#ifdef HAVE_GETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10006815/*[clinic input]
6816os.geteuid
6817
6818Return the current process's effective user id.
6819[clinic start generated code]*/
6820
Larry Hastings2f936352014-08-05 14:04:04 +10006821static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006822os_geteuid_impl(PyObject *module)
6823/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006824{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006825 return _PyLong_FromUid(geteuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006826}
Larry Hastings2f936352014-08-05 14:04:04 +10006827#endif /* HAVE_GETEUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006828
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006829
Guido van Rossumad0ee831995-03-01 10:34:45 +00006830#ifdef HAVE_GETGID
Larry Hastings2f936352014-08-05 14:04:04 +10006831/*[clinic input]
6832os.getgid
6833
6834Return the current process's group id.
6835[clinic start generated code]*/
6836
Larry Hastings2f936352014-08-05 14:04:04 +10006837static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006838os_getgid_impl(PyObject *module)
6839/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006840{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006841 return _PyLong_FromGid(getgid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006842}
Larry Hastings2f936352014-08-05 14:04:04 +10006843#endif /* HAVE_GETGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006844
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006845
Berker Peksag39404992016-09-15 20:45:16 +03006846#ifdef HAVE_GETPID
Larry Hastings2f936352014-08-05 14:04:04 +10006847/*[clinic input]
6848os.getpid
6849
6850Return the current process id.
6851[clinic start generated code]*/
6852
Larry Hastings2f936352014-08-05 14:04:04 +10006853static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006854os_getpid_impl(PyObject *module)
6855/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006856{
Victor Stinner8c62be82010-05-06 00:08:46 +00006857 return PyLong_FromPid(getpid());
Guido van Rossum85e3b011991-06-03 12:42:10 +00006858}
Berker Peksag39404992016-09-15 20:45:16 +03006859#endif /* HAVE_GETPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00006860
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07006861#ifdef NGROUPS_MAX
6862#define MAX_GROUPS NGROUPS_MAX
6863#else
6864 /* defined to be 16 on Solaris7, so this should be a small number */
6865#define MAX_GROUPS 64
6866#endif
6867
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006868#ifdef HAVE_GETGROUPLIST
Larry Hastings2f936352014-08-05 14:04:04 +10006869
6870/* AC 3.5: funny apple logic below */
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006871PyDoc_STRVAR(posix_getgrouplist__doc__,
6872"getgrouplist(user, group) -> list of groups to which a user belongs\n\n\
6873Returns a list of groups to which a user belongs.\n\n\
6874 user: username to lookup\n\
6875 group: base group id of the user");
6876
6877static PyObject *
6878posix_getgrouplist(PyObject *self, PyObject *args)
6879{
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006880 const char *user;
6881 int i, ngroups;
6882 PyObject *list;
6883#ifdef __APPLE__
6884 int *groups, basegid;
6885#else
6886 gid_t *groups, basegid;
6887#endif
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07006888
6889 /*
6890 * NGROUPS_MAX is defined by POSIX.1 as the maximum
6891 * number of supplimental groups a users can belong to.
6892 * We have to increment it by one because
6893 * getgrouplist() returns both the supplemental groups
6894 * and the primary group, i.e. all of the groups the
6895 * user belongs to.
6896 */
6897 ngroups = 1 + MAX_GROUPS;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006898
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006899#ifdef __APPLE__
6900 if (!PyArg_ParseTuple(args, "si:getgrouplist", &user, &basegid))
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006901 return NULL;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006902#else
6903 if (!PyArg_ParseTuple(args, "sO&:getgrouplist", &user,
6904 _Py_Gid_Converter, &basegid))
6905 return NULL;
6906#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006907
6908#ifdef __APPLE__
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006909 groups = PyMem_New(int, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006910#else
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006911 groups = PyMem_New(gid_t, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006912#endif
6913 if (groups == NULL)
6914 return PyErr_NoMemory();
6915
6916 if (getgrouplist(user, basegid, groups, &ngroups) == -1) {
6917 PyMem_Del(groups);
6918 return posix_error();
6919 }
6920
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006921#ifdef _Py_MEMORY_SANITIZER
6922 /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
6923 __msan_unpoison(&ngroups, sizeof(ngroups));
6924 __msan_unpoison(groups, ngroups*sizeof(*groups));
6925#endif
6926
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006927 list = PyList_New(ngroups);
6928 if (list == NULL) {
6929 PyMem_Del(groups);
6930 return NULL;
6931 }
6932
6933 for (i = 0; i < ngroups; i++) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006934#ifdef __APPLE__
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006935 PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006936#else
6937 PyObject *o = _PyLong_FromGid(groups[i]);
6938#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006939 if (o == NULL) {
6940 Py_DECREF(list);
6941 PyMem_Del(groups);
6942 return NULL;
6943 }
6944 PyList_SET_ITEM(list, i, o);
6945 }
6946
6947 PyMem_Del(groups);
6948
6949 return list;
6950}
Larry Hastings2f936352014-08-05 14:04:04 +10006951#endif /* HAVE_GETGROUPLIST */
6952
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006953
Fred Drakec9680921999-12-13 16:37:25 +00006954#ifdef HAVE_GETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10006955/*[clinic input]
6956os.getgroups
6957
6958Return list of supplemental group IDs for the process.
6959[clinic start generated code]*/
6960
Larry Hastings2f936352014-08-05 14:04:04 +10006961static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006962os_getgroups_impl(PyObject *module)
6963/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
Fred Drakec9680921999-12-13 16:37:25 +00006964{
6965 PyObject *result = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00006966 gid_t grouplist[MAX_GROUPS];
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006967
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00006968 /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006969 * This is a helper variable to store the intermediate result when
6970 * that happens.
6971 *
6972 * To keep the code readable the OSX behaviour is unconditional,
6973 * according to the POSIX spec this should be safe on all unix-y
6974 * systems.
6975 */
6976 gid_t* alt_grouplist = grouplist;
Victor Stinner8c62be82010-05-06 00:08:46 +00006977 int n;
Fred Drakec9680921999-12-13 16:37:25 +00006978
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006979#ifdef __APPLE__
6980 /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
6981 * there are more groups than can fit in grouplist. Therefore, on OS X
6982 * always first call getgroups with length 0 to get the actual number
6983 * of groups.
6984 */
6985 n = getgroups(0, NULL);
6986 if (n < 0) {
6987 return posix_error();
6988 } else if (n <= MAX_GROUPS) {
6989 /* groups will fit in existing array */
6990 alt_grouplist = grouplist;
6991 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006992 alt_grouplist = PyMem_New(gid_t, n);
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006993 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07006994 return PyErr_NoMemory();
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006995 }
6996 }
6997
6998 n = getgroups(n, alt_grouplist);
6999 if (n == -1) {
7000 if (alt_grouplist != grouplist) {
7001 PyMem_Free(alt_grouplist);
7002 }
7003 return posix_error();
7004 }
7005#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007006 n = getgroups(MAX_GROUPS, grouplist);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007007 if (n < 0) {
7008 if (errno == EINVAL) {
7009 n = getgroups(0, NULL);
7010 if (n == -1) {
7011 return posix_error();
7012 }
7013 if (n == 0) {
7014 /* Avoid malloc(0) */
7015 alt_grouplist = grouplist;
7016 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02007017 alt_grouplist = PyMem_New(gid_t, n);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007018 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07007019 return PyErr_NoMemory();
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007020 }
7021 n = getgroups(n, alt_grouplist);
7022 if (n == -1) {
7023 PyMem_Free(alt_grouplist);
7024 return posix_error();
7025 }
7026 }
7027 } else {
7028 return posix_error();
7029 }
7030 }
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007031#endif
7032
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007033 result = PyList_New(n);
7034 if (result != NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007035 int i;
7036 for (i = 0; i < n; ++i) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007037 PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
Victor Stinner8c62be82010-05-06 00:08:46 +00007038 if (o == NULL) {
Stefan Krah0e803b32010-11-26 16:16:47 +00007039 Py_DECREF(result);
7040 result = NULL;
7041 break;
Fred Drakec9680921999-12-13 16:37:25 +00007042 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007043 PyList_SET_ITEM(result, i, o);
Fred Drakec9680921999-12-13 16:37:25 +00007044 }
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007045 }
7046
7047 if (alt_grouplist != grouplist) {
7048 PyMem_Free(alt_grouplist);
Victor Stinner8c62be82010-05-06 00:08:46 +00007049 }
Neal Norwitze241ce82003-02-17 18:17:05 +00007050
Fred Drakec9680921999-12-13 16:37:25 +00007051 return result;
7052}
Larry Hastings2f936352014-08-05 14:04:04 +10007053#endif /* HAVE_GETGROUPS */
Fred Drakec9680921999-12-13 16:37:25 +00007054
Antoine Pitroub7572f02009-12-02 20:46:48 +00007055#ifdef HAVE_INITGROUPS
7056PyDoc_STRVAR(posix_initgroups__doc__,
7057"initgroups(username, gid) -> None\n\n\
7058Call the system initgroups() to initialize the group access list with all of\n\
7059the groups of which the specified username is a member, plus the specified\n\
7060group id.");
7061
Larry Hastings2f936352014-08-05 14:04:04 +10007062/* AC 3.5: funny apple logic */
Antoine Pitroub7572f02009-12-02 20:46:48 +00007063static PyObject *
7064posix_initgroups(PyObject *self, PyObject *args)
7065{
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007066 PyObject *oname;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03007067 const char *username;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007068 int res;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007069#ifdef __APPLE__
7070 int gid;
7071#else
7072 gid_t gid;
7073#endif
Antoine Pitroub7572f02009-12-02 20:46:48 +00007074
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007075#ifdef __APPLE__
7076 if (!PyArg_ParseTuple(args, "O&i:initgroups",
7077 PyUnicode_FSConverter, &oname,
7078 &gid))
7079#else
7080 if (!PyArg_ParseTuple(args, "O&O&:initgroups",
7081 PyUnicode_FSConverter, &oname,
7082 _Py_Gid_Converter, &gid))
7083#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00007084 return NULL;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007085 username = PyBytes_AS_STRING(oname);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007086
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007087 res = initgroups(username, gid);
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007088 Py_DECREF(oname);
7089 if (res == -1)
Victor Stinner8c62be82010-05-06 00:08:46 +00007090 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007091
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007092 Py_RETURN_NONE;
Antoine Pitroub7572f02009-12-02 20:46:48 +00007093}
Larry Hastings2f936352014-08-05 14:04:04 +10007094#endif /* HAVE_INITGROUPS */
7095
Antoine Pitroub7572f02009-12-02 20:46:48 +00007096
Martin v. Löwis606edc12002-06-13 21:09:11 +00007097#ifdef HAVE_GETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10007098/*[clinic input]
7099os.getpgid
7100
7101 pid: pid_t
7102
7103Call the system call getpgid(), and return the result.
7104[clinic start generated code]*/
7105
Larry Hastings2f936352014-08-05 14:04:04 +10007106static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007107os_getpgid_impl(PyObject *module, pid_t pid)
7108/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007109{
7110 pid_t pgid = getpgid(pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007111 if (pgid < 0)
7112 return posix_error();
7113 return PyLong_FromPid(pgid);
Martin v. Löwis606edc12002-06-13 21:09:11 +00007114}
7115#endif /* HAVE_GETPGID */
7116
7117
Guido van Rossumb6775db1994-08-01 11:34:53 +00007118#ifdef HAVE_GETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007119/*[clinic input]
7120os.getpgrp
7121
7122Return the current process group id.
7123[clinic start generated code]*/
7124
Larry Hastings2f936352014-08-05 14:04:04 +10007125static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007126os_getpgrp_impl(PyObject *module)
7127/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
Guido van Rossum04814471991-06-04 20:23:49 +00007128{
Guido van Rossumb6775db1994-08-01 11:34:53 +00007129#ifdef GETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007130 return PyLong_FromPid(getpgrp(0));
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007131#else /* GETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007132 return PyLong_FromPid(getpgrp());
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007133#endif /* GETPGRP_HAVE_ARG */
Guido van Rossum04814471991-06-04 20:23:49 +00007134}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007135#endif /* HAVE_GETPGRP */
Guido van Rossum04814471991-06-04 20:23:49 +00007136
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007137
Guido van Rossumb6775db1994-08-01 11:34:53 +00007138#ifdef HAVE_SETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007139/*[clinic input]
7140os.setpgrp
7141
7142Make the current process the leader of its process group.
7143[clinic start generated code]*/
7144
Larry Hastings2f936352014-08-05 14:04:04 +10007145static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007146os_setpgrp_impl(PyObject *module)
7147/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00007148{
Guido van Rossum64933891994-10-20 21:56:42 +00007149#ifdef SETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007150 if (setpgrp(0, 0) < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007151#else /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007152 if (setpgrp() < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007153#endif /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007154 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007155 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00007156}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007157#endif /* HAVE_SETPGRP */
7158
Guido van Rossumad0ee831995-03-01 10:34:45 +00007159#ifdef HAVE_GETPPID
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007160
7161#ifdef MS_WINDOWS
7162#include <tlhelp32.h>
7163
7164static PyObject*
7165win32_getppid()
7166{
7167 HANDLE snapshot;
7168 pid_t mypid;
7169 PyObject* result = NULL;
7170 BOOL have_record;
7171 PROCESSENTRY32 pe;
7172
7173 mypid = getpid(); /* This function never fails */
7174
7175 snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
7176 if (snapshot == INVALID_HANDLE_VALUE)
7177 return PyErr_SetFromWindowsErr(GetLastError());
7178
7179 pe.dwSize = sizeof(pe);
7180 have_record = Process32First(snapshot, &pe);
7181 while (have_record) {
7182 if (mypid == (pid_t)pe.th32ProcessID) {
7183 /* We could cache the ulong value in a static variable. */
7184 result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
7185 break;
7186 }
7187
7188 have_record = Process32Next(snapshot, &pe);
7189 }
7190
7191 /* If our loop exits and our pid was not found (result will be NULL)
7192 * then GetLastError will return ERROR_NO_MORE_FILES. This is an
7193 * error anyway, so let's raise it. */
7194 if (!result)
7195 result = PyErr_SetFromWindowsErr(GetLastError());
7196
7197 CloseHandle(snapshot);
7198
7199 return result;
7200}
7201#endif /*MS_WINDOWS*/
7202
Larry Hastings2f936352014-08-05 14:04:04 +10007203
7204/*[clinic input]
7205os.getppid
7206
7207Return the parent's process id.
7208
7209If the parent process has already exited, Windows machines will still
7210return its id; others systems will return the id of the 'init' process (1).
7211[clinic start generated code]*/
7212
Larry Hastings2f936352014-08-05 14:04:04 +10007213static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007214os_getppid_impl(PyObject *module)
7215/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00007216{
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007217#ifdef MS_WINDOWS
7218 return win32_getppid();
7219#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007220 return PyLong_FromPid(getppid());
Guido van Rossumad0ee831995-03-01 10:34:45 +00007221#endif
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007222}
7223#endif /* HAVE_GETPPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007224
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007225
Fred Drake12c6e2d1999-12-14 21:25:03 +00007226#ifdef HAVE_GETLOGIN
Larry Hastings2f936352014-08-05 14:04:04 +10007227/*[clinic input]
7228os.getlogin
7229
7230Return the actual login name.
7231[clinic start generated code]*/
7232
Larry Hastings2f936352014-08-05 14:04:04 +10007233static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007234os_getlogin_impl(PyObject *module)
7235/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
Fred Drake12c6e2d1999-12-14 21:25:03 +00007236{
Victor Stinner8c62be82010-05-06 00:08:46 +00007237 PyObject *result = NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007238#ifdef MS_WINDOWS
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007239 wchar_t user_name[UNLEN + 1];
Victor Stinner63941882011-09-29 00:42:28 +02007240 DWORD num_chars = Py_ARRAY_LENGTH(user_name);
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007241
7242 if (GetUserNameW(user_name, &num_chars)) {
7243 /* num_chars is the number of unicode chars plus null terminator */
7244 result = PyUnicode_FromWideChar(user_name, num_chars - 1);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007245 }
7246 else
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007247 result = PyErr_SetFromWindowsErr(GetLastError());
7248#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007249 char *name;
7250 int old_errno = errno;
Fred Drake12c6e2d1999-12-14 21:25:03 +00007251
Victor Stinner8c62be82010-05-06 00:08:46 +00007252 errno = 0;
7253 name = getlogin();
7254 if (name == NULL) {
7255 if (errno)
Victor Stinnere039ffe2010-08-15 09:33:08 +00007256 posix_error();
Fred Drake12c6e2d1999-12-14 21:25:03 +00007257 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007258 PyErr_SetString(PyExc_OSError, "unable to determine login name");
Victor Stinner8c62be82010-05-06 00:08:46 +00007259 }
7260 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007261 result = PyUnicode_DecodeFSDefault(name);
Victor Stinner8c62be82010-05-06 00:08:46 +00007262 errno = old_errno;
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007263#endif
Fred Drake12c6e2d1999-12-14 21:25:03 +00007264 return result;
7265}
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007266#endif /* HAVE_GETLOGIN */
Fred Drake12c6e2d1999-12-14 21:25:03 +00007267
Larry Hastings2f936352014-08-05 14:04:04 +10007268
Guido van Rossumad0ee831995-03-01 10:34:45 +00007269#ifdef HAVE_GETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007270/*[clinic input]
7271os.getuid
7272
7273Return the current process's user id.
7274[clinic start generated code]*/
7275
Larry Hastings2f936352014-08-05 14:04:04 +10007276static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007277os_getuid_impl(PyObject *module)
7278/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00007279{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007280 return _PyLong_FromUid(getuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00007281}
Larry Hastings2f936352014-08-05 14:04:04 +10007282#endif /* HAVE_GETUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00007283
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007284
Brian Curtineb24d742010-04-12 17:16:38 +00007285#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007286#define HAVE_KILL
7287#endif /* MS_WINDOWS */
7288
7289#ifdef HAVE_KILL
7290/*[clinic input]
7291os.kill
7292
7293 pid: pid_t
7294 signal: Py_ssize_t
7295 /
7296
7297Kill a process with a signal.
7298[clinic start generated code]*/
7299
Larry Hastings2f936352014-08-05 14:04:04 +10007300static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007301os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
7302/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007303#ifndef MS_WINDOWS
7304{
7305 if (kill(pid, (int)signal) == -1)
7306 return posix_error();
7307 Py_RETURN_NONE;
7308}
7309#else /* !MS_WINDOWS */
Brian Curtineb24d742010-04-12 17:16:38 +00007310{
Amaury Forgeot d'Arc0a589c92010-05-15 20:35:12 +00007311 PyObject *result;
Larry Hastings2f936352014-08-05 14:04:04 +10007312 DWORD sig = (DWORD)signal;
7313 DWORD err;
Victor Stinner8c62be82010-05-06 00:08:46 +00007314 HANDLE handle;
Brian Curtineb24d742010-04-12 17:16:38 +00007315
Victor Stinner8c62be82010-05-06 00:08:46 +00007316 /* Console processes which share a common console can be sent CTRL+C or
7317 CTRL+BREAK events, provided they handle said events. */
7318 if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007319 if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007320 err = GetLastError();
7321 PyErr_SetFromWindowsErr(err);
7322 }
7323 else
7324 Py_RETURN_NONE;
7325 }
Brian Curtineb24d742010-04-12 17:16:38 +00007326
Victor Stinner8c62be82010-05-06 00:08:46 +00007327 /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
7328 attempt to open and terminate the process. */
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007329 handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007330 if (handle == NULL) {
7331 err = GetLastError();
7332 return PyErr_SetFromWindowsErr(err);
7333 }
Brian Curtineb24d742010-04-12 17:16:38 +00007334
Victor Stinner8c62be82010-05-06 00:08:46 +00007335 if (TerminateProcess(handle, sig) == 0) {
7336 err = GetLastError();
7337 result = PyErr_SetFromWindowsErr(err);
7338 } else {
7339 Py_INCREF(Py_None);
7340 result = Py_None;
7341 }
Brian Curtineb24d742010-04-12 17:16:38 +00007342
Victor Stinner8c62be82010-05-06 00:08:46 +00007343 CloseHandle(handle);
7344 return result;
Brian Curtineb24d742010-04-12 17:16:38 +00007345}
Larry Hastings2f936352014-08-05 14:04:04 +10007346#endif /* !MS_WINDOWS */
7347#endif /* HAVE_KILL */
7348
7349
7350#ifdef HAVE_KILLPG
7351/*[clinic input]
7352os.killpg
7353
7354 pgid: pid_t
7355 signal: int
7356 /
7357
7358Kill a process group with a signal.
7359[clinic start generated code]*/
7360
Larry Hastings2f936352014-08-05 14:04:04 +10007361static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007362os_killpg_impl(PyObject *module, pid_t pgid, int signal)
7363/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007364{
7365 /* XXX some man pages make the `pgid` parameter an int, others
7366 a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
7367 take the same type. Moreover, pid_t is always at least as wide as
7368 int (else compilation of this module fails), which is safe. */
7369 if (killpg(pgid, signal) == -1)
7370 return posix_error();
7371 Py_RETURN_NONE;
7372}
7373#endif /* HAVE_KILLPG */
7374
Brian Curtineb24d742010-04-12 17:16:38 +00007375
Guido van Rossumc0125471996-06-28 18:55:32 +00007376#ifdef HAVE_PLOCK
Guido van Rossumc0125471996-06-28 18:55:32 +00007377#ifdef HAVE_SYS_LOCK_H
7378#include <sys/lock.h>
7379#endif
7380
Larry Hastings2f936352014-08-05 14:04:04 +10007381/*[clinic input]
7382os.plock
7383 op: int
7384 /
7385
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007386Lock program segments into memory.");
Larry Hastings2f936352014-08-05 14:04:04 +10007387[clinic start generated code]*/
7388
Larry Hastings2f936352014-08-05 14:04:04 +10007389static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007390os_plock_impl(PyObject *module, int op)
7391/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007392{
Victor Stinner8c62be82010-05-06 00:08:46 +00007393 if (plock(op) == -1)
7394 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007395 Py_RETURN_NONE;
Guido van Rossumc0125471996-06-28 18:55:32 +00007396}
Larry Hastings2f936352014-08-05 14:04:04 +10007397#endif /* HAVE_PLOCK */
7398
Guido van Rossumc0125471996-06-28 18:55:32 +00007399
Guido van Rossumb6775db1994-08-01 11:34:53 +00007400#ifdef HAVE_SETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007401/*[clinic input]
7402os.setuid
7403
7404 uid: uid_t
7405 /
7406
7407Set the current process's user id.
7408[clinic start generated code]*/
7409
Larry Hastings2f936352014-08-05 14:04:04 +10007410static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007411os_setuid_impl(PyObject *module, uid_t uid)
7412/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007413{
Victor Stinner8c62be82010-05-06 00:08:46 +00007414 if (setuid(uid) < 0)
7415 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007416 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007417}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007418#endif /* HAVE_SETUID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007419
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007420
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007421#ifdef HAVE_SETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10007422/*[clinic input]
7423os.seteuid
7424
7425 euid: uid_t
7426 /
7427
7428Set the current process's effective user id.
7429[clinic start generated code]*/
7430
Larry Hastings2f936352014-08-05 14:04:04 +10007431static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007432os_seteuid_impl(PyObject *module, uid_t euid)
7433/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007434{
7435 if (seteuid(euid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007436 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007437 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007438}
7439#endif /* HAVE_SETEUID */
7440
Larry Hastings2f936352014-08-05 14:04:04 +10007441
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007442#ifdef HAVE_SETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10007443/*[clinic input]
7444os.setegid
7445
7446 egid: gid_t
7447 /
7448
7449Set the current process's effective group id.
7450[clinic start generated code]*/
7451
Larry Hastings2f936352014-08-05 14:04:04 +10007452static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007453os_setegid_impl(PyObject *module, gid_t egid)
7454/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007455{
7456 if (setegid(egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007457 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007458 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007459}
7460#endif /* HAVE_SETEGID */
7461
Larry Hastings2f936352014-08-05 14:04:04 +10007462
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007463#ifdef HAVE_SETREUID
Larry Hastings2f936352014-08-05 14:04:04 +10007464/*[clinic input]
7465os.setreuid
7466
7467 ruid: uid_t
7468 euid: uid_t
7469 /
7470
7471Set the current process's real and effective user ids.
7472[clinic start generated code]*/
7473
Larry Hastings2f936352014-08-05 14:04:04 +10007474static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007475os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
7476/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007477{
Victor Stinner8c62be82010-05-06 00:08:46 +00007478 if (setreuid(ruid, euid) < 0) {
7479 return posix_error();
7480 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007481 Py_RETURN_NONE;
Victor Stinner8c62be82010-05-06 00:08:46 +00007482 }
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007483}
7484#endif /* HAVE_SETREUID */
7485
Larry Hastings2f936352014-08-05 14:04:04 +10007486
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007487#ifdef HAVE_SETREGID
Larry Hastings2f936352014-08-05 14:04:04 +10007488/*[clinic input]
7489os.setregid
7490
7491 rgid: gid_t
7492 egid: gid_t
7493 /
7494
7495Set the current process's real and effective group ids.
7496[clinic start generated code]*/
7497
Larry Hastings2f936352014-08-05 14:04:04 +10007498static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007499os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
7500/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007501{
7502 if (setregid(rgid, egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007503 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007504 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007505}
7506#endif /* HAVE_SETREGID */
7507
Larry Hastings2f936352014-08-05 14:04:04 +10007508
Guido van Rossumb6775db1994-08-01 11:34:53 +00007509#ifdef HAVE_SETGID
Larry Hastings2f936352014-08-05 14:04:04 +10007510/*[clinic input]
7511os.setgid
7512 gid: gid_t
7513 /
7514
7515Set the current process's group id.
7516[clinic start generated code]*/
7517
Larry Hastings2f936352014-08-05 14:04:04 +10007518static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007519os_setgid_impl(PyObject *module, gid_t gid)
7520/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007521{
Victor Stinner8c62be82010-05-06 00:08:46 +00007522 if (setgid(gid) < 0)
7523 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007524 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007525}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007526#endif /* HAVE_SETGID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007527
Larry Hastings2f936352014-08-05 14:04:04 +10007528
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007529#ifdef HAVE_SETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007530/*[clinic input]
7531os.setgroups
7532
7533 groups: object
7534 /
7535
7536Set the groups of the current process to list.
7537[clinic start generated code]*/
7538
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007539static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007540os_setgroups(PyObject *module, PyObject *groups)
7541/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007542{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007543 Py_ssize_t i, len;
Victor Stinner8c62be82010-05-06 00:08:46 +00007544 gid_t grouplist[MAX_GROUPS];
Tim Peters5aa91602002-01-30 05:46:57 +00007545
Victor Stinner8c62be82010-05-06 00:08:46 +00007546 if (!PySequence_Check(groups)) {
7547 PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
7548 return NULL;
7549 }
7550 len = PySequence_Size(groups);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007551 if (len < 0) {
7552 return NULL;
7553 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007554 if (len > MAX_GROUPS) {
7555 PyErr_SetString(PyExc_ValueError, "too many groups");
7556 return NULL;
7557 }
7558 for(i = 0; i < len; i++) {
7559 PyObject *elem;
7560 elem = PySequence_GetItem(groups, i);
7561 if (!elem)
7562 return NULL;
7563 if (!PyLong_Check(elem)) {
7564 PyErr_SetString(PyExc_TypeError,
7565 "groups must be integers");
7566 Py_DECREF(elem);
7567 return NULL;
7568 } else {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007569 if (!_Py_Gid_Converter(elem, &grouplist[i])) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007570 Py_DECREF(elem);
7571 return NULL;
7572 }
7573 }
7574 Py_DECREF(elem);
7575 }
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007576
Victor Stinner8c62be82010-05-06 00:08:46 +00007577 if (setgroups(len, grouplist) < 0)
7578 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007579 Py_RETURN_NONE;
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007580}
7581#endif /* HAVE_SETGROUPS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007582
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007583#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
7584static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +01007585wait_helper(pid_t pid, int status, struct rusage *ru)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007586{
Victor Stinner8c62be82010-05-06 00:08:46 +00007587 PyObject *result;
Eddie Elizondob3966632019-11-05 07:16:14 -08007588 PyObject *struct_rusage;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007589
Victor Stinner8c62be82010-05-06 00:08:46 +00007590 if (pid == -1)
7591 return posix_error();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007592
Zackery Spytz682107c2019-09-09 09:48:32 -06007593 // If wait succeeded but no child was ready to report status, ru will not
7594 // have been populated.
7595 if (pid == 0) {
7596 memset(ru, 0, sizeof(*ru));
7597 }
7598
Eddie Elizondob3966632019-11-05 07:16:14 -08007599 PyObject *m = PyImport_ImportModuleNoBlock("resource");
7600 if (m == NULL)
7601 return NULL;
7602 struct_rusage = PyObject_GetAttr(m, _posixstate_global->struct_rusage);
7603 Py_DECREF(m);
7604 if (struct_rusage == NULL)
7605 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007606
Victor Stinner8c62be82010-05-06 00:08:46 +00007607 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
7608 result = PyStructSequence_New((PyTypeObject*) struct_rusage);
Eddie Elizondoe4db1f02019-11-25 19:07:37 -08007609 Py_DECREF(struct_rusage);
Victor Stinner8c62be82010-05-06 00:08:46 +00007610 if (!result)
7611 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007612
7613#ifndef doubletime
7614#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
7615#endif
7616
Victor Stinner8c62be82010-05-06 00:08:46 +00007617 PyStructSequence_SET_ITEM(result, 0,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007618 PyFloat_FromDouble(doubletime(ru->ru_utime)));
Victor Stinner8c62be82010-05-06 00:08:46 +00007619 PyStructSequence_SET_ITEM(result, 1,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007620 PyFloat_FromDouble(doubletime(ru->ru_stime)));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007621#define SET_INT(result, index, value)\
Victor Stinner8c62be82010-05-06 00:08:46 +00007622 PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
7623 SET_INT(result, 2, ru->ru_maxrss);
7624 SET_INT(result, 3, ru->ru_ixrss);
7625 SET_INT(result, 4, ru->ru_idrss);
7626 SET_INT(result, 5, ru->ru_isrss);
7627 SET_INT(result, 6, ru->ru_minflt);
7628 SET_INT(result, 7, ru->ru_majflt);
7629 SET_INT(result, 8, ru->ru_nswap);
7630 SET_INT(result, 9, ru->ru_inblock);
7631 SET_INT(result, 10, ru->ru_oublock);
7632 SET_INT(result, 11, ru->ru_msgsnd);
7633 SET_INT(result, 12, ru->ru_msgrcv);
7634 SET_INT(result, 13, ru->ru_nsignals);
7635 SET_INT(result, 14, ru->ru_nvcsw);
7636 SET_INT(result, 15, ru->ru_nivcsw);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007637#undef SET_INT
7638
Victor Stinner8c62be82010-05-06 00:08:46 +00007639 if (PyErr_Occurred()) {
7640 Py_DECREF(result);
7641 return NULL;
7642 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007643
Victor Stinner8c62be82010-05-06 00:08:46 +00007644 return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007645}
7646#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
7647
Larry Hastings2f936352014-08-05 14:04:04 +10007648
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007649#ifdef HAVE_WAIT3
Larry Hastings2f936352014-08-05 14:04:04 +10007650/*[clinic input]
7651os.wait3
7652
7653 options: int
7654Wait for completion of a child process.
7655
7656Returns a tuple of information about the child process:
7657 (pid, status, rusage)
7658[clinic start generated code]*/
7659
Larry Hastings2f936352014-08-05 14:04:04 +10007660static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007661os_wait3_impl(PyObject *module, int options)
7662/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007663{
Victor Stinner8c62be82010-05-06 00:08:46 +00007664 pid_t pid;
Victor Stinner8c62be82010-05-06 00:08:46 +00007665 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007666 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007667 WAIT_TYPE status;
7668 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007669
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007670 do {
7671 Py_BEGIN_ALLOW_THREADS
7672 pid = wait3(&status, options, &ru);
7673 Py_END_ALLOW_THREADS
7674 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7675 if (pid < 0)
7676 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007677
Victor Stinner4195b5c2012-02-08 23:03:19 +01007678 return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007679}
7680#endif /* HAVE_WAIT3 */
7681
Larry Hastings2f936352014-08-05 14:04:04 +10007682
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007683#ifdef HAVE_WAIT4
Larry Hastings2f936352014-08-05 14:04:04 +10007684/*[clinic input]
7685
7686os.wait4
7687
7688 pid: pid_t
7689 options: int
7690
7691Wait for completion of a specific child process.
7692
7693Returns a tuple of information about the child process:
7694 (pid, status, rusage)
7695[clinic start generated code]*/
7696
Larry Hastings2f936352014-08-05 14:04:04 +10007697static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007698os_wait4_impl(PyObject *module, pid_t pid, int options)
7699/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007700{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007701 pid_t res;
Victor Stinner8c62be82010-05-06 00:08:46 +00007702 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007703 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007704 WAIT_TYPE status;
7705 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007706
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007707 do {
7708 Py_BEGIN_ALLOW_THREADS
7709 res = wait4(pid, &status, options, &ru);
7710 Py_END_ALLOW_THREADS
7711 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7712 if (res < 0)
7713 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007714
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007715 return wait_helper(res, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007716}
7717#endif /* HAVE_WAIT4 */
7718
Larry Hastings2f936352014-08-05 14:04:04 +10007719
Ross Lagerwall7807c352011-03-17 20:20:30 +02007720#if defined(HAVE_WAITID) && !defined(__APPLE__)
Larry Hastings2f936352014-08-05 14:04:04 +10007721/*[clinic input]
7722os.waitid
7723
7724 idtype: idtype_t
7725 Must be one of be P_PID, P_PGID or P_ALL.
7726 id: id_t
7727 The id to wait on.
7728 options: int
7729 Constructed from the ORing of one or more of WEXITED, WSTOPPED
7730 or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
7731 /
7732
7733Returns the result of waiting for a process or processes.
7734
7735Returns either waitid_result or None if WNOHANG is specified and there are
7736no children in a waitable state.
7737[clinic start generated code]*/
7738
Larry Hastings2f936352014-08-05 14:04:04 +10007739static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007740os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
7741/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007742{
7743 PyObject *result;
7744 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007745 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007746 siginfo_t si;
7747 si.si_pid = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007748
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007749 do {
7750 Py_BEGIN_ALLOW_THREADS
7751 res = waitid(idtype, id, &si, options);
7752 Py_END_ALLOW_THREADS
7753 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7754 if (res < 0)
7755 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007756
7757 if (si.si_pid == 0)
7758 Py_RETURN_NONE;
7759
Eddie Elizondob3966632019-11-05 07:16:14 -08007760 PyObject *WaitidResultType = _posixstate(module)->WaitidResultType;
7761 result = PyStructSequence_New((PyTypeObject *)WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +02007762 if (!result)
7763 return NULL;
7764
7765 PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007766 PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
Ross Lagerwall7807c352011-03-17 20:20:30 +02007767 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
7768 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
7769 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
7770 if (PyErr_Occurred()) {
7771 Py_DECREF(result);
7772 return NULL;
7773 }
7774
7775 return result;
7776}
Larry Hastings2f936352014-08-05 14:04:04 +10007777#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
Ross Lagerwall7807c352011-03-17 20:20:30 +02007778
Larry Hastings2f936352014-08-05 14:04:04 +10007779
7780#if defined(HAVE_WAITPID)
7781/*[clinic input]
7782os.waitpid
7783 pid: pid_t
7784 options: int
7785 /
7786
7787Wait for completion of a given child process.
7788
7789Returns a tuple of information regarding the child process:
7790 (pid, status)
7791
7792The options argument is ignored on Windows.
7793[clinic start generated code]*/
7794
Larry Hastings2f936352014-08-05 14:04:04 +10007795static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007796os_waitpid_impl(PyObject *module, pid_t pid, int options)
7797/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007798{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007799 pid_t res;
7800 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007801 WAIT_TYPE status;
7802 WAIT_STATUS_INT(status) = 0;
Guido van Rossum54ecc3d1999-01-27 17:53:11 +00007803
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007804 do {
7805 Py_BEGIN_ALLOW_THREADS
7806 res = waitpid(pid, &status, options);
7807 Py_END_ALLOW_THREADS
7808 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7809 if (res < 0)
7810 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007811
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007812 return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
Guido van Rossum21803b81992-08-09 12:55:27 +00007813}
Tim Petersab034fa2002-02-01 11:27:43 +00007814#elif defined(HAVE_CWAIT)
Tim Petersab034fa2002-02-01 11:27:43 +00007815/* MS C has a variant of waitpid() that's usable for most purposes. */
Larry Hastings2f936352014-08-05 14:04:04 +10007816/*[clinic input]
7817os.waitpid
Benjamin Petersonca470632016-09-06 13:47:26 -07007818 pid: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +10007819 options: int
7820 /
7821
7822Wait for completion of a given process.
7823
7824Returns a tuple of information regarding the process:
7825 (pid, status << 8)
7826
7827The options argument is ignored on Windows.
7828[clinic start generated code]*/
7829
Larry Hastings2f936352014-08-05 14:04:04 +10007830static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -07007831os_waitpid_impl(PyObject *module, intptr_t pid, int options)
Victor Stinner581139c2016-09-06 15:54:20 -07007832/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007833{
7834 int status;
Benjamin Petersonca470632016-09-06 13:47:26 -07007835 intptr_t res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007836 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007837
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007838 do {
7839 Py_BEGIN_ALLOW_THREADS
Steve Dower11f43262016-11-19 18:33:39 -08007840 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007841 res = _cwait(&status, pid, options);
Steve Dower11f43262016-11-19 18:33:39 -08007842 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007843 Py_END_ALLOW_THREADS
7844 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinnerd3ffd322015-09-15 10:11:03 +02007845 if (res < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007846 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007847
Victor Stinner8c62be82010-05-06 00:08:46 +00007848 /* shift the status left a byte so this is more like the POSIX waitpid */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007849 return Py_BuildValue(_Py_PARSE_INTPTR "i", res, status << 8);
Tim Petersab034fa2002-02-01 11:27:43 +00007850}
Larry Hastings2f936352014-08-05 14:04:04 +10007851#endif
7852
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007853
Guido van Rossumad0ee831995-03-01 10:34:45 +00007854#ifdef HAVE_WAIT
Larry Hastings2f936352014-08-05 14:04:04 +10007855/*[clinic input]
7856os.wait
7857
7858Wait for completion of a child process.
7859
7860Returns a tuple of information about the child process:
7861 (pid, status)
7862[clinic start generated code]*/
7863
Larry Hastings2f936352014-08-05 14:04:04 +10007864static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007865os_wait_impl(PyObject *module)
7866/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
Guido van Rossum21803b81992-08-09 12:55:27 +00007867{
Victor Stinner8c62be82010-05-06 00:08:46 +00007868 pid_t pid;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007869 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007870 WAIT_TYPE status;
7871 WAIT_STATUS_INT(status) = 0;
Neal Norwitze241ce82003-02-17 18:17:05 +00007872
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007873 do {
7874 Py_BEGIN_ALLOW_THREADS
7875 pid = wait(&status);
7876 Py_END_ALLOW_THREADS
7877 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7878 if (pid < 0)
7879 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007880
Victor Stinner8c62be82010-05-06 00:08:46 +00007881 return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
Guido van Rossum85e3b011991-06-03 12:42:10 +00007882}
Larry Hastings2f936352014-08-05 14:04:04 +10007883#endif /* HAVE_WAIT */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007884
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -08007885#if defined(__linux__) && defined(__NR_pidfd_open)
7886/*[clinic input]
7887os.pidfd_open
7888 pid: pid_t
7889 flags: unsigned_int = 0
7890
7891Return a file descriptor referring to the process *pid*.
7892
7893The descriptor can be used to perform process management without races and
7894signals.
7895[clinic start generated code]*/
7896
7897static PyObject *
7898os_pidfd_open_impl(PyObject *module, pid_t pid, unsigned int flags)
7899/*[clinic end generated code: output=5c7252698947dc41 input=c3fd99ce947ccfef]*/
7900{
7901 int fd = syscall(__NR_pidfd_open, pid, flags);
7902 if (fd < 0) {
7903 return posix_error();
7904 }
7905 return PyLong_FromLong(fd);
7906}
7907#endif
7908
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007909
Larry Hastings9cf065c2012-06-22 16:30:09 -07007910#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007911/*[clinic input]
7912os.readlink
7913
7914 path: path_t
7915 *
7916 dir_fd: dir_fd(requires='readlinkat') = None
7917
7918Return a string representing the path to which the symbolic link points.
7919
7920If dir_fd is not None, it should be a file descriptor open to a directory,
7921and path should be relative; path will then be relative to that directory.
7922
7923dir_fd may not be implemented on your platform. If it is unavailable,
7924using it will raise a NotImplementedError.
7925[clinic start generated code]*/
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007926
Barry Warsaw53699e91996-12-10 23:23:01 +00007927static PyObject *
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007928os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
7929/*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00007930{
Berker Peksage0b5b202018-08-15 13:03:41 +03007931#if defined(HAVE_READLINK)
Christian Heimes3cb091e2016-09-23 20:24:28 +02007932 char buffer[MAXPATHLEN+1];
Larry Hastings9cf065c2012-06-22 16:30:09 -07007933 ssize_t length;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007934
7935 Py_BEGIN_ALLOW_THREADS
7936#ifdef HAVE_READLINKAT
7937 if (dir_fd != DEFAULT_DIR_FD)
7938 length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
7939 else
7940#endif
7941 length = readlink(path->narrow, buffer, MAXPATHLEN);
7942 Py_END_ALLOW_THREADS
7943
7944 if (length < 0) {
7945 return path_error(path);
7946 }
7947 buffer[length] = '\0';
7948
7949 if (PyUnicode_Check(path->object))
7950 return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
7951 else
7952 return PyBytes_FromStringAndSize(buffer, length);
Berker Peksage0b5b202018-08-15 13:03:41 +03007953#elif defined(MS_WINDOWS)
7954 DWORD n_bytes_returned;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007955 DWORD io_result = 0;
Berker Peksage0b5b202018-08-15 13:03:41 +03007956 HANDLE reparse_point_handle;
Berker Peksage0b5b202018-08-15 13:03:41 +03007957 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
7958 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Steve Dower993ac922019-09-03 12:50:51 -07007959 PyObject *result = NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00007960
Larry Hastings2f936352014-08-05 14:04:04 +10007961 /* First get a handle to the reparse point */
7962 Py_BEGIN_ALLOW_THREADS
7963 reparse_point_handle = CreateFileW(
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007964 path->wide,
Larry Hastings2f936352014-08-05 14:04:04 +10007965 0,
7966 0,
7967 0,
7968 OPEN_EXISTING,
7969 FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
7970 0);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007971 if (reparse_point_handle != INVALID_HANDLE_VALUE) {
7972 /* New call DeviceIoControl to read the reparse point */
7973 io_result = DeviceIoControl(
7974 reparse_point_handle,
7975 FSCTL_GET_REPARSE_POINT,
7976 0, 0, /* in buffer */
7977 target_buffer, sizeof(target_buffer),
7978 &n_bytes_returned,
7979 0 /* we're not using OVERLAPPED_IO */
7980 );
7981 CloseHandle(reparse_point_handle);
Berker Peksage0b5b202018-08-15 13:03:41 +03007982 }
Larry Hastings2f936352014-08-05 14:04:04 +10007983 Py_END_ALLOW_THREADS
7984
Berker Peksage0b5b202018-08-15 13:03:41 +03007985 if (io_result == 0) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007986 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03007987 }
Larry Hastings2f936352014-08-05 14:04:04 +10007988
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007989 wchar_t *name = NULL;
7990 Py_ssize_t nameLen = 0;
7991 if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
Larry Hastings2f936352014-08-05 14:04:04 +10007992 {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007993 name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
7994 rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
7995 nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
Larry Hastings2f936352014-08-05 14:04:04 +10007996 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007997 else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
7998 {
7999 name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
8000 rdb->MountPointReparseBuffer.SubstituteNameOffset);
8001 nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
8002 }
8003 else
8004 {
8005 PyErr_SetString(PyExc_ValueError, "not a symbolic link");
8006 }
8007 if (name) {
8008 if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
8009 /* Our buffer is mutable, so this is okay */
8010 name[1] = L'\\';
8011 }
8012 result = PyUnicode_FromWideChar(name, nameLen);
Steve Dower993ac922019-09-03 12:50:51 -07008013 if (result && path->narrow) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008014 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
8015 }
Berker Peksage0b5b202018-08-15 13:03:41 +03008016 }
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008017 return result;
Berker Peksage0b5b202018-08-15 13:03:41 +03008018#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008019}
Berker Peksage0b5b202018-08-15 13:03:41 +03008020#endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008021
Larry Hastings9cf065c2012-06-22 16:30:09 -07008022#ifdef HAVE_SYMLINK
Larry Hastings9cf065c2012-06-22 16:30:09 -07008023
8024#if defined(MS_WINDOWS)
8025
Steve Dower6921e732018-03-05 14:26:08 -08008026/* Remove the last portion of the path - return 0 on success */
8027static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008028_dirnameW(WCHAR *path)
8029{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008030 WCHAR *ptr;
Steve Dower6921e732018-03-05 14:26:08 -08008031 size_t length = wcsnlen_s(path, MAX_PATH);
8032 if (length == MAX_PATH) {
8033 return -1;
8034 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008035
8036 /* walk the path from the end until a backslash is encountered */
Steve Dower6921e732018-03-05 14:26:08 -08008037 for(ptr = path + length; ptr != path; ptr--) {
8038 if (*ptr == L'\\' || *ptr == L'/') {
Jason R. Coombs3a092862013-05-27 23:21:28 -04008039 break;
Steve Dower6921e732018-03-05 14:26:08 -08008040 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008041 }
8042 *ptr = 0;
Steve Dower6921e732018-03-05 14:26:08 -08008043 return 0;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008044}
8045
Victor Stinner31b3b922013-06-05 01:49:17 +02008046/* Is this path absolute? */
8047static int
8048_is_absW(const WCHAR *path)
8049{
Steve Dower6921e732018-03-05 14:26:08 -08008050 return path[0] == L'\\' || path[0] == L'/' ||
8051 (path[0] && path[1] == L':');
Jason R. Coombs3a092862013-05-27 23:21:28 -04008052}
8053
Steve Dower6921e732018-03-05 14:26:08 -08008054/* join root and rest with a backslash - return 0 on success */
8055static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008056_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
8057{
Victor Stinner31b3b922013-06-05 01:49:17 +02008058 if (_is_absW(rest)) {
Steve Dower6921e732018-03-05 14:26:08 -08008059 return wcscpy_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008060 }
8061
Steve Dower6921e732018-03-05 14:26:08 -08008062 if (wcscpy_s(dest_path, MAX_PATH, root)) {
8063 return -1;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008064 }
Steve Dower6921e732018-03-05 14:26:08 -08008065
8066 if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
8067 return -1;
8068 }
8069
8070 return wcscat_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008071}
8072
Victor Stinner31b3b922013-06-05 01:49:17 +02008073/* Return True if the path at src relative to dest is a directory */
8074static int
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03008075_check_dirW(LPCWSTR src, LPCWSTR dest)
Jason R. Coombs3a092862013-05-27 23:21:28 -04008076{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008077 WIN32_FILE_ATTRIBUTE_DATA src_info;
8078 WCHAR dest_parent[MAX_PATH];
8079 WCHAR src_resolved[MAX_PATH] = L"";
8080
8081 /* dest_parent = os.path.dirname(dest) */
Steve Dower6921e732018-03-05 14:26:08 -08008082 if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
8083 _dirnameW(dest_parent)) {
8084 return 0;
8085 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008086 /* src_resolved = os.path.join(dest_parent, src) */
Steve Dower6921e732018-03-05 14:26:08 -08008087 if (_joinW(src_resolved, dest_parent, src)) {
8088 return 0;
8089 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008090 return (
8091 GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
8092 && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
8093 );
8094}
Larry Hastings9cf065c2012-06-22 16:30:09 -07008095#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008096
Larry Hastings2f936352014-08-05 14:04:04 +10008097
8098/*[clinic input]
8099os.symlink
8100 src: path_t
8101 dst: path_t
8102 target_is_directory: bool = False
8103 *
8104 dir_fd: dir_fd(requires='symlinkat')=None
8105
8106# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
8107
8108Create a symbolic link pointing to src named dst.
8109
8110target_is_directory is required on Windows if the target is to be
8111 interpreted as a directory. (On Windows, symlink requires
8112 Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
8113 target_is_directory is ignored on non-Windows platforms.
8114
8115If dir_fd is not None, it should be a file descriptor open to a directory,
8116 and path should be relative; path will then be relative to that directory.
8117dir_fd may not be implemented on your platform.
8118 If it is unavailable, using it will raise a NotImplementedError.
8119
8120[clinic start generated code]*/
8121
Larry Hastings2f936352014-08-05 14:04:04 +10008122static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008123os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
Larry Hastings89964c42015-04-14 18:07:59 -04008124 int target_is_directory, int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008125/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008126{
Larry Hastings9cf065c2012-06-22 16:30:09 -07008127#ifdef MS_WINDOWS
8128 DWORD result;
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008129 DWORD flags = 0;
8130
8131 /* Assumed true, set to false if detected to not be available. */
8132 static int windows_has_symlink_unprivileged_flag = TRUE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008133#else
8134 int result;
8135#endif
8136
Larry Hastings9cf065c2012-06-22 16:30:09 -07008137#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008138
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008139 if (windows_has_symlink_unprivileged_flag) {
8140 /* Allow non-admin symlinks if system allows it. */
8141 flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
8142 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008143
Larry Hastings9cf065c2012-06-22 16:30:09 -07008144 Py_BEGIN_ALLOW_THREADS
Steve Dower6921e732018-03-05 14:26:08 -08008145 _Py_BEGIN_SUPPRESS_IPH
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008146 /* if src is a directory, ensure flags==1 (target_is_directory bit) */
8147 if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
8148 flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
8149 }
8150
8151 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
Steve Dower6921e732018-03-05 14:26:08 -08008152 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07008153 Py_END_ALLOW_THREADS
8154
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008155 if (windows_has_symlink_unprivileged_flag && !result &&
8156 ERROR_INVALID_PARAMETER == GetLastError()) {
8157
8158 Py_BEGIN_ALLOW_THREADS
8159 _Py_BEGIN_SUPPRESS_IPH
8160 /* This error might be caused by
8161 SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
8162 Try again, and update windows_has_symlink_unprivileged_flag if we
8163 are successful this time.
8164
8165 NOTE: There is a risk of a race condition here if there are other
8166 conditions than the flag causing ERROR_INVALID_PARAMETER, and
8167 another process (or thread) changes that condition in between our
8168 calls to CreateSymbolicLink.
8169 */
8170 flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
8171 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
8172 _Py_END_SUPPRESS_IPH
8173 Py_END_ALLOW_THREADS
8174
8175 if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
8176 windows_has_symlink_unprivileged_flag = FALSE;
8177 }
8178 }
8179
Larry Hastings2f936352014-08-05 14:04:04 +10008180 if (!result)
8181 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008182
8183#else
8184
Steve Dower6921e732018-03-05 14:26:08 -08008185 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
8186 PyErr_SetString(PyExc_ValueError,
8187 "symlink: src and dst must be the same type");
8188 return NULL;
8189 }
8190
Larry Hastings9cf065c2012-06-22 16:30:09 -07008191 Py_BEGIN_ALLOW_THREADS
8192#if HAVE_SYMLINKAT
8193 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10008194 result = symlinkat(src->narrow, dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008195 else
8196#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008197 result = symlink(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008198 Py_END_ALLOW_THREADS
8199
Larry Hastings2f936352014-08-05 14:04:04 +10008200 if (result)
8201 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008202#endif
8203
Larry Hastings2f936352014-08-05 14:04:04 +10008204 Py_RETURN_NONE;
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008205}
8206#endif /* HAVE_SYMLINK */
8207
Larry Hastings9cf065c2012-06-22 16:30:09 -07008208
Brian Curtind40e6f72010-07-08 21:39:08 +00008209
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008210
Larry Hastings605a62d2012-06-24 04:33:36 -07008211static PyStructSequence_Field times_result_fields[] = {
8212 {"user", "user time"},
8213 {"system", "system time"},
8214 {"children_user", "user time of children"},
8215 {"children_system", "system time of children"},
8216 {"elapsed", "elapsed time since an arbitrary point in the past"},
8217 {NULL}
8218};
8219
8220PyDoc_STRVAR(times_result__doc__,
8221"times_result: Result from os.times().\n\n\
8222This object may be accessed either as a tuple of\n\
8223 (user, system, children_user, children_system, elapsed),\n\
8224or via the attributes user, system, children_user, children_system,\n\
8225and elapsed.\n\
8226\n\
8227See os.times for more information.");
8228
8229static PyStructSequence_Desc times_result_desc = {
8230 "times_result", /* name */
8231 times_result__doc__, /* doc */
8232 times_result_fields,
8233 5
8234};
8235
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008236#ifdef MS_WINDOWS
8237#define HAVE_TIMES /* mandatory, for the method table */
8238#endif
Larry Hastings605a62d2012-06-24 04:33:36 -07008239
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008240#ifdef HAVE_TIMES
Larry Hastings605a62d2012-06-24 04:33:36 -07008241
8242static PyObject *
8243build_times_result(double user, double system,
8244 double children_user, double children_system,
8245 double elapsed)
8246{
Eddie Elizondob3966632019-11-05 07:16:14 -08008247 PyObject *TimesResultType = _posixstate_global->TimesResultType;
8248 PyObject *value = PyStructSequence_New((PyTypeObject *)TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07008249 if (value == NULL)
8250 return NULL;
8251
8252#define SET(i, field) \
8253 { \
8254 PyObject *o = PyFloat_FromDouble(field); \
8255 if (!o) { \
8256 Py_DECREF(value); \
8257 return NULL; \
8258 } \
8259 PyStructSequence_SET_ITEM(value, i, o); \
8260 } \
8261
8262 SET(0, user);
8263 SET(1, system);
8264 SET(2, children_user);
8265 SET(3, children_system);
8266 SET(4, elapsed);
8267
8268#undef SET
8269
8270 return value;
8271}
8272
Larry Hastings605a62d2012-06-24 04:33:36 -07008273
Larry Hastings2f936352014-08-05 14:04:04 +10008274#ifndef MS_WINDOWS
8275#define NEED_TICKS_PER_SECOND
8276static long ticks_per_second = -1;
8277#endif /* MS_WINDOWS */
8278
8279/*[clinic input]
8280os.times
8281
8282Return a collection containing process timing information.
8283
8284The object returned behaves like a named tuple with these fields:
8285 (utime, stime, cutime, cstime, elapsed_time)
8286All fields are floating point numbers.
8287[clinic start generated code]*/
8288
Larry Hastings2f936352014-08-05 14:04:04 +10008289static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008290os_times_impl(PyObject *module)
8291/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008292#ifdef MS_WINDOWS
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008293{
Victor Stinner8c62be82010-05-06 00:08:46 +00008294 FILETIME create, exit, kernel, user;
8295 HANDLE hProc;
8296 hProc = GetCurrentProcess();
8297 GetProcessTimes(hProc, &create, &exit, &kernel, &user);
8298 /* The fields of a FILETIME structure are the hi and lo part
8299 of a 64-bit value expressed in 100 nanosecond units.
8300 1e7 is one second in such units; 1e-7 the inverse.
8301 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
8302 */
Larry Hastings605a62d2012-06-24 04:33:36 -07008303 return build_times_result(
Victor Stinner8c62be82010-05-06 00:08:46 +00008304 (double)(user.dwHighDateTime*429.4967296 +
8305 user.dwLowDateTime*1e-7),
8306 (double)(kernel.dwHighDateTime*429.4967296 +
8307 kernel.dwLowDateTime*1e-7),
8308 (double)0,
8309 (double)0,
8310 (double)0);
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008311}
Larry Hastings2f936352014-08-05 14:04:04 +10008312#else /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008313{
Larry Hastings2f936352014-08-05 14:04:04 +10008314
8315
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008316 struct tms t;
8317 clock_t c;
8318 errno = 0;
8319 c = times(&t);
8320 if (c == (clock_t) -1)
8321 return posix_error();
8322 return build_times_result(
8323 (double)t.tms_utime / ticks_per_second,
8324 (double)t.tms_stime / ticks_per_second,
8325 (double)t.tms_cutime / ticks_per_second,
8326 (double)t.tms_cstime / ticks_per_second,
8327 (double)c / ticks_per_second);
8328}
Larry Hastings2f936352014-08-05 14:04:04 +10008329#endif /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008330#endif /* HAVE_TIMES */
8331
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008332
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008333#ifdef HAVE_GETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008334/*[clinic input]
8335os.getsid
8336
8337 pid: pid_t
8338 /
8339
8340Call the system call getsid(pid) and return the result.
8341[clinic start generated code]*/
8342
Larry Hastings2f936352014-08-05 14:04:04 +10008343static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008344os_getsid_impl(PyObject *module, pid_t pid)
8345/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008346{
Victor Stinner8c62be82010-05-06 00:08:46 +00008347 int sid;
Victor Stinner8c62be82010-05-06 00:08:46 +00008348 sid = getsid(pid);
8349 if (sid < 0)
8350 return posix_error();
8351 return PyLong_FromLong((long)sid);
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008352}
8353#endif /* HAVE_GETSID */
8354
8355
Guido van Rossumb6775db1994-08-01 11:34:53 +00008356#ifdef HAVE_SETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008357/*[clinic input]
8358os.setsid
8359
8360Call the system call setsid().
8361[clinic start generated code]*/
8362
Larry Hastings2f936352014-08-05 14:04:04 +10008363static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008364os_setsid_impl(PyObject *module)
8365/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00008366{
Victor Stinner8c62be82010-05-06 00:08:46 +00008367 if (setsid() < 0)
8368 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008369 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008370}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008371#endif /* HAVE_SETSID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008372
Larry Hastings2f936352014-08-05 14:04:04 +10008373
Guido van Rossumb6775db1994-08-01 11:34:53 +00008374#ifdef HAVE_SETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10008375/*[clinic input]
8376os.setpgid
8377
8378 pid: pid_t
8379 pgrp: pid_t
8380 /
8381
8382Call the system call setpgid(pid, pgrp).
8383[clinic start generated code]*/
8384
Larry Hastings2f936352014-08-05 14:04:04 +10008385static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008386os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
8387/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008388{
Victor Stinner8c62be82010-05-06 00:08:46 +00008389 if (setpgid(pid, pgrp) < 0)
8390 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008391 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008392}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008393#endif /* HAVE_SETPGID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008394
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008395
Guido van Rossumb6775db1994-08-01 11:34:53 +00008396#ifdef HAVE_TCGETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008397/*[clinic input]
8398os.tcgetpgrp
8399
8400 fd: int
8401 /
8402
8403Return the process group associated with the terminal specified by fd.
8404[clinic start generated code]*/
8405
Larry Hastings2f936352014-08-05 14:04:04 +10008406static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008407os_tcgetpgrp_impl(PyObject *module, int fd)
8408/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008409{
8410 pid_t pgid = tcgetpgrp(fd);
Victor Stinner8c62be82010-05-06 00:08:46 +00008411 if (pgid < 0)
8412 return posix_error();
8413 return PyLong_FromPid(pgid);
Guido van Rossum7066dd71992-09-17 17:54:56 +00008414}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008415#endif /* HAVE_TCGETPGRP */
Guido van Rossum7066dd71992-09-17 17:54:56 +00008416
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008417
Guido van Rossumb6775db1994-08-01 11:34:53 +00008418#ifdef HAVE_TCSETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008419/*[clinic input]
8420os.tcsetpgrp
8421
8422 fd: int
8423 pgid: pid_t
8424 /
8425
8426Set the process group associated with the terminal specified by fd.
8427[clinic start generated code]*/
8428
Larry Hastings2f936352014-08-05 14:04:04 +10008429static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008430os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
8431/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008432{
Victor Stinner8c62be82010-05-06 00:08:46 +00008433 if (tcsetpgrp(fd, pgid) < 0)
8434 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008435 Py_RETURN_NONE;
Guido van Rossum7066dd71992-09-17 17:54:56 +00008436}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008437#endif /* HAVE_TCSETPGRP */
Guido van Rossum22db57e1992-04-05 14:25:30 +00008438
Guido van Rossum687dd131993-05-17 08:34:16 +00008439/* Functions acting on file descriptors */
8440
Victor Stinnerdaf45552013-08-28 00:53:59 +02008441#ifdef O_CLOEXEC
8442extern int _Py_open_cloexec_works;
8443#endif
8444
Larry Hastings2f936352014-08-05 14:04:04 +10008445
8446/*[clinic input]
8447os.open -> int
8448 path: path_t
8449 flags: int
8450 mode: int = 0o777
8451 *
8452 dir_fd: dir_fd(requires='openat') = None
8453
8454# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
8455
8456Open a file for low level IO. Returns a file descriptor (integer).
8457
8458If dir_fd is not None, it should be a file descriptor open to a directory,
8459 and path should be relative; path will then be relative to that directory.
8460dir_fd may not be implemented on your platform.
8461 If it is unavailable, using it will raise a NotImplementedError.
8462[clinic start generated code]*/
8463
Larry Hastings2f936352014-08-05 14:04:04 +10008464static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008465os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
8466/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008467{
8468 int fd;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008469 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008470
Victor Stinnerdaf45552013-08-28 00:53:59 +02008471#ifdef O_CLOEXEC
8472 int *atomic_flag_works = &_Py_open_cloexec_works;
8473#elif !defined(MS_WINDOWS)
8474 int *atomic_flag_works = NULL;
8475#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +00008476
Victor Stinnerdaf45552013-08-28 00:53:59 +02008477#ifdef MS_WINDOWS
8478 flags |= O_NOINHERIT;
8479#elif defined(O_CLOEXEC)
8480 flags |= O_CLOEXEC;
8481#endif
8482
Steve Dowerb82e17e2019-05-23 08:45:22 -07008483 if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
8484 return -1;
8485 }
8486
Steve Dower8fc89802015-04-12 00:26:27 -04008487 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008488 do {
8489 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008490#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07008491 fd = _wopen(path->wide, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008492#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07008493#ifdef HAVE_OPENAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008494 if (dir_fd != DEFAULT_DIR_FD)
8495 fd = openat(dir_fd, path->narrow, flags, mode);
8496 else
Steve Dower6230aaf2016-09-09 09:03:15 -07008497#endif /* HAVE_OPENAT */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008498 fd = open(path->narrow, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008499#endif /* !MS_WINDOWS */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008500 Py_END_ALLOW_THREADS
8501 } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04008502 _Py_END_SUPPRESS_IPH
Guido van Rossum687dd131993-05-17 08:34:16 +00008503
Victor Stinnerd3ffd322015-09-15 10:11:03 +02008504 if (fd < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008505 if (!async_err)
8506 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Larry Hastings2f936352014-08-05 14:04:04 +10008507 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008508 }
8509
Victor Stinnerdaf45552013-08-28 00:53:59 +02008510#ifndef MS_WINDOWS
8511 if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
8512 close(fd);
Larry Hastings2f936352014-08-05 14:04:04 +10008513 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008514 }
8515#endif
8516
Larry Hastings2f936352014-08-05 14:04:04 +10008517 return fd;
8518}
8519
8520
8521/*[clinic input]
8522os.close
8523
8524 fd: int
8525
8526Close a file descriptor.
8527[clinic start generated code]*/
8528
Barry Warsaw53699e91996-12-10 23:23:01 +00008529static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008530os_close_impl(PyObject *module, int fd)
8531/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00008532{
Larry Hastings2f936352014-08-05 14:04:04 +10008533 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008534 /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
8535 * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
8536 * for more details.
8537 */
Victor Stinner8c62be82010-05-06 00:08:46 +00008538 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008539 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008540 res = close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04008541 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008542 Py_END_ALLOW_THREADS
8543 if (res < 0)
8544 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008545 Py_RETURN_NONE;
Guido van Rossum687dd131993-05-17 08:34:16 +00008546}
8547
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008548
Jakub Kulíke20134f2019-09-11 17:11:57 +02008549#ifdef HAVE_FDWALK
8550static int
8551_fdwalk_close_func(void *lohi, int fd)
8552{
8553 int lo = ((int *)lohi)[0];
8554 int hi = ((int *)lohi)[1];
8555
8556 if (fd >= hi)
8557 return 1;
8558 else if (fd >= lo)
8559 close(fd);
8560 return 0;
8561}
8562#endif /* HAVE_FDWALK */
8563
Larry Hastings2f936352014-08-05 14:04:04 +10008564/*[clinic input]
8565os.closerange
8566
8567 fd_low: int
8568 fd_high: int
8569 /
8570
8571Closes all file descriptors in [fd_low, fd_high), ignoring errors.
8572[clinic start generated code]*/
8573
Larry Hastings2f936352014-08-05 14:04:04 +10008574static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008575os_closerange_impl(PyObject *module, int fd_low, int fd_high)
8576/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008577{
Jakub Kulíke20134f2019-09-11 17:11:57 +02008578#ifdef HAVE_FDWALK
8579 int lohi[2];
8580#else
Larry Hastings2f936352014-08-05 14:04:04 +10008581 int i;
Jakub Kulíke20134f2019-09-11 17:11:57 +02008582#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00008583 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008584 _Py_BEGIN_SUPPRESS_IPH
Jakub Kulíke20134f2019-09-11 17:11:57 +02008585#ifdef HAVE_FDWALK
8586 lohi[0] = Py_MAX(fd_low, 0);
8587 lohi[1] = fd_high;
8588 fdwalk(_fdwalk_close_func, lohi);
8589#else
Benjamin Peterson207116b2016-09-08 11:28:06 -07008590 for (i = Py_MAX(fd_low, 0); i < fd_high; i++)
Steve Dower940f33a2016-09-08 11:21:54 -07008591 close(i);
Jakub Kulíke20134f2019-09-11 17:11:57 +02008592#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008593 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008594 Py_END_ALLOW_THREADS
8595 Py_RETURN_NONE;
Christian Heimesfdab48e2008-01-20 09:06:41 +00008596}
8597
8598
Larry Hastings2f936352014-08-05 14:04:04 +10008599/*[clinic input]
8600os.dup -> int
8601
8602 fd: int
8603 /
8604
8605Return a duplicate of a file descriptor.
8606[clinic start generated code]*/
8607
Larry Hastings2f936352014-08-05 14:04:04 +10008608static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008609os_dup_impl(PyObject *module, int fd)
8610/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008611{
8612 return _Py_dup(fd);
Guido van Rossum687dd131993-05-17 08:34:16 +00008613}
8614
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008615
Larry Hastings2f936352014-08-05 14:04:04 +10008616/*[clinic input]
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008617os.dup2 -> int
Larry Hastings2f936352014-08-05 14:04:04 +10008618 fd: int
8619 fd2: int
8620 inheritable: bool=True
8621
8622Duplicate file descriptor.
8623[clinic start generated code]*/
8624
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008625static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008626os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008627/*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008628{
Stéphane Wirtel3d86e482018-01-30 07:04:36 +01008629 int res = 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008630#if defined(HAVE_DUP3) && \
8631 !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
8632 /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
Alexey Izbyshevb3caf382018-02-20 10:25:46 +03008633 static int dup3_works = -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008634#endif
8635
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008636 if (fd < 0 || fd2 < 0) {
8637 posix_error();
8638 return -1;
8639 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008640
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008641 /* dup2() can fail with EINTR if the target FD is already open, because it
8642 * then has to be closed. See os_close_impl() for why we don't handle EINTR
8643 * upon close(), and therefore below.
8644 */
Victor Stinnerdaf45552013-08-28 00:53:59 +02008645#ifdef MS_WINDOWS
8646 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008647 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008648 res = dup2(fd, fd2);
Steve Dower8fc89802015-04-12 00:26:27 -04008649 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02008650 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008651 if (res < 0) {
8652 posix_error();
8653 return -1;
8654 }
8655 res = fd2; // msvcrt dup2 returns 0 on success.
Victor Stinnerdaf45552013-08-28 00:53:59 +02008656
8657 /* Character files like console cannot be make non-inheritable */
8658 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8659 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008660 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008661 }
8662
8663#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
8664 Py_BEGIN_ALLOW_THREADS
8665 if (!inheritable)
8666 res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
8667 else
8668 res = dup2(fd, fd2);
8669 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008670 if (res < 0) {
8671 posix_error();
8672 return -1;
8673 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008674
8675#else
8676
8677#ifdef HAVE_DUP3
8678 if (!inheritable && dup3_works != 0) {
8679 Py_BEGIN_ALLOW_THREADS
8680 res = dup3(fd, fd2, O_CLOEXEC);
8681 Py_END_ALLOW_THREADS
8682 if (res < 0) {
8683 if (dup3_works == -1)
8684 dup3_works = (errno != ENOSYS);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008685 if (dup3_works) {
8686 posix_error();
8687 return -1;
8688 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008689 }
8690 }
8691
8692 if (inheritable || dup3_works == 0)
8693 {
8694#endif
8695 Py_BEGIN_ALLOW_THREADS
8696 res = dup2(fd, fd2);
8697 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008698 if (res < 0) {
8699 posix_error();
8700 return -1;
8701 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008702
8703 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8704 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008705 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008706 }
8707#ifdef HAVE_DUP3
8708 }
8709#endif
8710
8711#endif
8712
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008713 return res;
Guido van Rossum687dd131993-05-17 08:34:16 +00008714}
8715
Larry Hastings2f936352014-08-05 14:04:04 +10008716
Ross Lagerwall7807c352011-03-17 20:20:30 +02008717#ifdef HAVE_LOCKF
Larry Hastings2f936352014-08-05 14:04:04 +10008718/*[clinic input]
8719os.lockf
8720
8721 fd: int
8722 An open file descriptor.
8723 command: int
8724 One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
8725 length: Py_off_t
8726 The number of bytes to lock, starting at the current position.
8727 /
8728
8729Apply, test or remove a POSIX lock on an open file descriptor.
8730
8731[clinic start generated code]*/
8732
Larry Hastings2f936352014-08-05 14:04:04 +10008733static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008734os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
8735/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008736{
8737 int res;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008738
8739 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008740 res = lockf(fd, command, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008741 Py_END_ALLOW_THREADS
8742
8743 if (res < 0)
8744 return posix_error();
8745
8746 Py_RETURN_NONE;
8747}
Larry Hastings2f936352014-08-05 14:04:04 +10008748#endif /* HAVE_LOCKF */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008749
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008750
Larry Hastings2f936352014-08-05 14:04:04 +10008751/*[clinic input]
8752os.lseek -> Py_off_t
8753
8754 fd: int
8755 position: Py_off_t
8756 how: int
8757 /
8758
8759Set the position of a file descriptor. Return the new position.
8760
8761Return the new cursor position in number of bytes
8762relative to the beginning of the file.
8763[clinic start generated code]*/
8764
Larry Hastings2f936352014-08-05 14:04:04 +10008765static Py_off_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008766os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
8767/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008768{
8769 Py_off_t result;
8770
Guido van Rossum687dd131993-05-17 08:34:16 +00008771#ifdef SEEK_SET
Victor Stinner8c62be82010-05-06 00:08:46 +00008772 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
8773 switch (how) {
Larry Hastings2f936352014-08-05 14:04:04 +10008774 case 0: how = SEEK_SET; break;
8775 case 1: how = SEEK_CUR; break;
8776 case 2: how = SEEK_END; break;
Victor Stinner8c62be82010-05-06 00:08:46 +00008777 }
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00008778#endif /* SEEK_END */
Guido van Rossum94f6f721999-01-06 18:42:14 +00008779
Victor Stinner8c62be82010-05-06 00:08:46 +00008780 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008781 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner14b9b112013-06-25 00:37:25 +02008782#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10008783 result = _lseeki64(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008784#else
Larry Hastings2f936352014-08-05 14:04:04 +10008785 result = lseek(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008786#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008787 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008788 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008789 if (result < 0)
8790 posix_error();
Guido van Rossum94f6f721999-01-06 18:42:14 +00008791
Larry Hastings2f936352014-08-05 14:04:04 +10008792 return result;
Guido van Rossum687dd131993-05-17 08:34:16 +00008793}
8794
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008795
Larry Hastings2f936352014-08-05 14:04:04 +10008796/*[clinic input]
8797os.read
8798 fd: int
8799 length: Py_ssize_t
8800 /
8801
8802Read from a file descriptor. Returns a bytes object.
8803[clinic start generated code]*/
8804
Larry Hastings2f936352014-08-05 14:04:04 +10008805static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008806os_read_impl(PyObject *module, int fd, Py_ssize_t length)
8807/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008808{
Victor Stinner8c62be82010-05-06 00:08:46 +00008809 Py_ssize_t n;
8810 PyObject *buffer;
Larry Hastings2f936352014-08-05 14:04:04 +10008811
8812 if (length < 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008813 errno = EINVAL;
8814 return posix_error();
8815 }
Larry Hastings2f936352014-08-05 14:04:04 +10008816
Victor Stinner9a0d7a72018-11-22 15:03:40 +01008817 length = Py_MIN(length, _PY_READ_MAX);
Larry Hastings2f936352014-08-05 14:04:04 +10008818
8819 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Victor Stinner8c62be82010-05-06 00:08:46 +00008820 if (buffer == NULL)
8821 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008822
Victor Stinner66aab0c2015-03-19 22:53:20 +01008823 n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
8824 if (n == -1) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008825 Py_DECREF(buffer);
Victor Stinner66aab0c2015-03-19 22:53:20 +01008826 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00008827 }
Larry Hastings2f936352014-08-05 14:04:04 +10008828
8829 if (n != length)
Victor Stinner8c62be82010-05-06 00:08:46 +00008830 _PyBytes_Resize(&buffer, n);
Larry Hastings2f936352014-08-05 14:04:04 +10008831
Victor Stinner8c62be82010-05-06 00:08:46 +00008832 return buffer;
Guido van Rossum687dd131993-05-17 08:34:16 +00008833}
8834
Ross Lagerwall7807c352011-03-17 20:20:30 +02008835#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008836 || defined(__APPLE__))) \
8837 || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
8838 || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
8839static int
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008840iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008841{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008842 Py_ssize_t i, j;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008843
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008844 *iov = PyMem_New(struct iovec, cnt);
8845 if (*iov == NULL) {
8846 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008847 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008848 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008849
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008850 *buf = PyMem_New(Py_buffer, cnt);
8851 if (*buf == NULL) {
8852 PyMem_Del(*iov);
8853 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008854 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008855 }
8856
8857 for (i = 0; i < cnt; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008858 PyObject *item = PySequence_GetItem(seq, i);
8859 if (item == NULL)
8860 goto fail;
8861 if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
8862 Py_DECREF(item);
8863 goto fail;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008864 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008865 Py_DECREF(item);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008866 (*iov)[i].iov_base = (*buf)[i].buf;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008867 (*iov)[i].iov_len = (*buf)[i].len;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008868 }
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008869 return 0;
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008870
8871fail:
8872 PyMem_Del(*iov);
8873 for (j = 0; j < i; j++) {
8874 PyBuffer_Release(&(*buf)[j]);
8875 }
8876 PyMem_Del(*buf);
Victor Stinner57ddf782014-01-08 15:21:28 +01008877 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008878}
8879
8880static void
8881iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
8882{
8883 int i;
8884 PyMem_Del(iov);
8885 for (i = 0; i < cnt; i++) {
8886 PyBuffer_Release(&buf[i]);
8887 }
8888 PyMem_Del(buf);
8889}
8890#endif
8891
Larry Hastings2f936352014-08-05 14:04:04 +10008892
Ross Lagerwall7807c352011-03-17 20:20:30 +02008893#ifdef HAVE_READV
Larry Hastings2f936352014-08-05 14:04:04 +10008894/*[clinic input]
8895os.readv -> Py_ssize_t
8896
8897 fd: int
8898 buffers: object
8899 /
8900
8901Read from a file descriptor fd into an iterable of buffers.
8902
8903The buffers should be mutable buffers accepting bytes.
8904readv will transfer data into each buffer until it is full
8905and then move on to the next buffer in the sequence to hold
8906the rest of the data.
8907
8908readv returns the total number of bytes read,
8909which may be less than the total capacity of all the buffers.
8910[clinic start generated code]*/
8911
Larry Hastings2f936352014-08-05 14:04:04 +10008912static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008913os_readv_impl(PyObject *module, int fd, PyObject *buffers)
8914/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008915{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008916 Py_ssize_t cnt, n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008917 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008918 struct iovec *iov;
8919 Py_buffer *buf;
8920
Larry Hastings2f936352014-08-05 14:04:04 +10008921 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008922 PyErr_SetString(PyExc_TypeError,
8923 "readv() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10008924 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008925 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02008926
Larry Hastings2f936352014-08-05 14:04:04 +10008927 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008928 if (cnt < 0)
8929 return -1;
Larry Hastings2f936352014-08-05 14:04:04 +10008930
8931 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
8932 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008933
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008934 do {
8935 Py_BEGIN_ALLOW_THREADS
8936 n = readv(fd, iov, cnt);
8937 Py_END_ALLOW_THREADS
8938 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02008939
8940 iov_cleanup(iov, buf, cnt);
Larry Hastings2f936352014-08-05 14:04:04 +10008941 if (n < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008942 if (!async_err)
8943 posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008944 return -1;
8945 }
Victor Stinner57ddf782014-01-08 15:21:28 +01008946
Larry Hastings2f936352014-08-05 14:04:04 +10008947 return n;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008948}
Larry Hastings2f936352014-08-05 14:04:04 +10008949#endif /* HAVE_READV */
8950
Ross Lagerwall7807c352011-03-17 20:20:30 +02008951
8952#ifdef HAVE_PREAD
Larry Hastings2f936352014-08-05 14:04:04 +10008953/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10008954os.pread
8955
8956 fd: int
Dong-hee Naad7736f2019-09-25 14:47:04 +09008957 length: Py_ssize_t
Larry Hastings2f936352014-08-05 14:04:04 +10008958 offset: Py_off_t
8959 /
8960
8961Read a number of bytes from a file descriptor starting at a particular offset.
8962
8963Read length bytes from file descriptor fd, starting at offset bytes from
8964the beginning of the file. The file offset remains unchanged.
8965[clinic start generated code]*/
8966
Larry Hastings2f936352014-08-05 14:04:04 +10008967static PyObject *
Dong-hee Naad7736f2019-09-25 14:47:04 +09008968os_pread_impl(PyObject *module, int fd, Py_ssize_t length, Py_off_t offset)
8969/*[clinic end generated code: output=3f875c1eef82e32f input=85cb4a5589627144]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008970{
Ross Lagerwall7807c352011-03-17 20:20:30 +02008971 Py_ssize_t n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008972 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008973 PyObject *buffer;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008974
Larry Hastings2f936352014-08-05 14:04:04 +10008975 if (length < 0) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008976 errno = EINVAL;
8977 return posix_error();
8978 }
Larry Hastings2f936352014-08-05 14:04:04 +10008979 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008980 if (buffer == NULL)
8981 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008982
8983 do {
8984 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008985 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008986 n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04008987 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008988 Py_END_ALLOW_THREADS
8989 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8990
Ross Lagerwall7807c352011-03-17 20:20:30 +02008991 if (n < 0) {
8992 Py_DECREF(buffer);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008993 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008994 }
Larry Hastings2f936352014-08-05 14:04:04 +10008995 if (n != length)
Ross Lagerwall7807c352011-03-17 20:20:30 +02008996 _PyBytes_Resize(&buffer, n);
8997 return buffer;
8998}
Larry Hastings2f936352014-08-05 14:04:04 +10008999#endif /* HAVE_PREAD */
Ross Lagerwall7807c352011-03-17 20:20:30 +02009000
Pablo Galindo4defba32018-01-27 16:16:37 +00009001#if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
9002/*[clinic input]
9003os.preadv -> Py_ssize_t
9004
9005 fd: int
9006 buffers: object
9007 offset: Py_off_t
9008 flags: int = 0
9009 /
9010
9011Reads from a file descriptor into a number of mutable bytes-like objects.
9012
9013Combines the functionality of readv() and pread(). As readv(), it will
9014transfer data into each buffer until it is full and then move on to the next
9015buffer in the sequence to hold the rest of the data. Its fourth argument,
9016specifies the file offset at which the input operation is to be performed. It
9017will return the total number of bytes read (which can be less than the total
9018capacity of all the objects).
9019
9020The flags argument contains a bitwise OR of zero or more of the following flags:
9021
9022- RWF_HIPRI
9023- RWF_NOWAIT
9024
9025Using non-zero flags requires Linux 4.6 or newer.
9026[clinic start generated code]*/
9027
9028static Py_ssize_t
9029os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9030 int flags)
9031/*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
9032{
9033 Py_ssize_t cnt, n;
9034 int async_err = 0;
9035 struct iovec *iov;
9036 Py_buffer *buf;
9037
9038 if (!PySequence_Check(buffers)) {
9039 PyErr_SetString(PyExc_TypeError,
9040 "preadv2() arg 2 must be a sequence");
9041 return -1;
9042 }
9043
9044 cnt = PySequence_Size(buffers);
9045 if (cnt < 0) {
9046 return -1;
9047 }
9048
9049#ifndef HAVE_PREADV2
9050 if(flags != 0) {
9051 argument_unavailable_error("preadv2", "flags");
9052 return -1;
9053 }
9054#endif
9055
9056 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
9057 return -1;
9058 }
9059#ifdef HAVE_PREADV2
9060 do {
9061 Py_BEGIN_ALLOW_THREADS
9062 _Py_BEGIN_SUPPRESS_IPH
9063 n = preadv2(fd, iov, cnt, offset, flags);
9064 _Py_END_SUPPRESS_IPH
9065 Py_END_ALLOW_THREADS
9066 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9067#else
9068 do {
9069 Py_BEGIN_ALLOW_THREADS
9070 _Py_BEGIN_SUPPRESS_IPH
9071 n = preadv(fd, iov, cnt, offset);
9072 _Py_END_SUPPRESS_IPH
9073 Py_END_ALLOW_THREADS
9074 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9075#endif
9076
9077 iov_cleanup(iov, buf, cnt);
9078 if (n < 0) {
9079 if (!async_err) {
9080 posix_error();
9081 }
9082 return -1;
9083 }
9084
9085 return n;
9086}
9087#endif /* HAVE_PREADV */
9088
Larry Hastings2f936352014-08-05 14:04:04 +10009089
9090/*[clinic input]
9091os.write -> Py_ssize_t
9092
9093 fd: int
9094 data: Py_buffer
9095 /
9096
9097Write a bytes object to a file descriptor.
9098[clinic start generated code]*/
9099
Larry Hastings2f936352014-08-05 14:04:04 +10009100static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009101os_write_impl(PyObject *module, int fd, Py_buffer *data)
9102/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009103{
Victor Stinner66aab0c2015-03-19 22:53:20 +01009104 return _Py_write(fd, data->buf, data->len);
Ross Lagerwall7807c352011-03-17 20:20:30 +02009105}
9106
9107#ifdef HAVE_SENDFILE
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009108PyDoc_STRVAR(posix_sendfile__doc__,
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009109"sendfile(out_fd, in_fd, offset, count) -> byteswritten\n\
9110sendfile(out_fd, in_fd, offset, count[, headers][, trailers], flags=0)\n\
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009111 -> byteswritten\n\
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009112Copy count bytes from file descriptor in_fd to file descriptor out_fd.");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009113
Larry Hastings2f936352014-08-05 14:04:04 +10009114/* AC 3.5: don't bother converting, has optional group*/
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009115static PyObject *
9116posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict)
9117{
9118 int in, out;
9119 Py_ssize_t ret;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009120 int async_err = 0;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009121 off_t offset;
9122
9123#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
9124#ifndef __APPLE__
9125 Py_ssize_t len;
9126#endif
9127 PyObject *headers = NULL, *trailers = NULL;
9128 Py_buffer *hbuf, *tbuf;
9129 off_t sbytes;
9130 struct sf_hdtr sf;
9131 int flags = 0;
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009132 static char *keywords[] = {"out_fd", "in_fd",
Benjamin Petersond8a43b42011-02-26 21:35:16 +00009133 "offset", "count",
9134 "headers", "trailers", "flags", NULL};
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009135
Victor Stinner6ce0dbf2013-07-07 16:32:36 +02009136 sf.headers = NULL;
9137 sf.trailers = NULL;
9138
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009139#ifdef __APPLE__
9140 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&O&|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10009141 keywords, &out, &in, Py_off_t_converter, &offset, Py_off_t_converter, &sbytes,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009142#else
9143 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&n|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10009144 keywords, &out, &in, Py_off_t_converter, &offset, &len,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009145#endif
9146 &headers, &trailers, &flags))
9147 return NULL;
9148 if (headers != NULL) {
9149 if (!PySequence_Check(headers)) {
9150 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009151 "sendfile() headers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009152 return NULL;
9153 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009154 Py_ssize_t i = PySequence_Size(headers);
9155 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009156 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009157 if (i > INT_MAX) {
9158 PyErr_SetString(PyExc_OverflowError,
9159 "sendfile() header is too large");
9160 return NULL;
9161 }
9162 if (i > 0) {
9163 sf.hdr_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009164 if (iov_setup(&(sf.headers), &hbuf,
9165 headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009166 return NULL;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009167#ifdef __APPLE__
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009168 for (i = 0; i < sf.hdr_cnt; i++) {
9169 Py_ssize_t blen = sf.headers[i].iov_len;
9170# define OFF_T_MAX 0x7fffffffffffffff
9171 if (sbytes >= OFF_T_MAX - blen) {
9172 PyErr_SetString(PyExc_OverflowError,
9173 "sendfile() header is too large");
9174 return NULL;
9175 }
9176 sbytes += blen;
9177 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009178#endif
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009179 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009180 }
9181 }
9182 if (trailers != NULL) {
9183 if (!PySequence_Check(trailers)) {
9184 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009185 "sendfile() trailers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009186 return NULL;
9187 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009188 Py_ssize_t i = PySequence_Size(trailers);
9189 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009190 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009191 if (i > INT_MAX) {
9192 PyErr_SetString(PyExc_OverflowError,
9193 "sendfile() trailer is too large");
9194 return NULL;
9195 }
9196 if (i > 0) {
9197 sf.trl_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009198 if (iov_setup(&(sf.trailers), &tbuf,
9199 trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009200 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009201 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009202 }
9203 }
9204
Steve Dower8fc89802015-04-12 00:26:27 -04009205 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009206 do {
9207 Py_BEGIN_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009208#ifdef __APPLE__
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009209 ret = sendfile(in, out, offset, &sbytes, &sf, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009210#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009211 ret = sendfile(in, out, offset, len, &sf, &sbytes, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009212#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009213 Py_END_ALLOW_THREADS
9214 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04009215 _Py_END_SUPPRESS_IPH
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009216
9217 if (sf.headers != NULL)
9218 iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
9219 if (sf.trailers != NULL)
9220 iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
9221
9222 if (ret < 0) {
9223 if ((errno == EAGAIN) || (errno == EBUSY)) {
9224 if (sbytes != 0) {
9225 // some data has been sent
9226 goto done;
9227 }
9228 else {
9229 // no data has been sent; upper application is supposed
9230 // to retry on EAGAIN or EBUSY
9231 return posix_error();
9232 }
9233 }
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009234 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009235 }
9236 goto done;
9237
9238done:
9239 #if !defined(HAVE_LARGEFILE_SUPPORT)
9240 return Py_BuildValue("l", sbytes);
9241 #else
9242 return Py_BuildValue("L", sbytes);
9243 #endif
9244
9245#else
9246 Py_ssize_t count;
9247 PyObject *offobj;
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009248 static char *keywords[] = {"out_fd", "in_fd",
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009249 "offset", "count", NULL};
9250 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiOn:sendfile",
9251 keywords, &out, &in, &offobj, &count))
9252 return NULL;
Benjamin Peterson840ef8f2016-09-07 14:45:10 -07009253#ifdef __linux__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009254 if (offobj == Py_None) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009255 do {
9256 Py_BEGIN_ALLOW_THREADS
9257 ret = sendfile(out, in, NULL, count);
9258 Py_END_ALLOW_THREADS
9259 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009260 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009261 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodola'ff1a7352011-04-19 09:47:16 +02009262 return Py_BuildValue("n", ret);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009263 }
9264#endif
Larry Hastings2f936352014-08-05 14:04:04 +10009265 if (!Py_off_t_converter(offobj, &offset))
Antoine Pitroudcc20b82011-02-26 13:38:35 +00009266 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009267
9268 do {
9269 Py_BEGIN_ALLOW_THREADS
9270 ret = sendfile(out, in, &offset, count);
9271 Py_END_ALLOW_THREADS
9272 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009273 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009274 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009275 return Py_BuildValue("n", ret);
9276#endif
9277}
Larry Hastings2f936352014-08-05 14:04:04 +10009278#endif /* HAVE_SENDFILE */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009279
Larry Hastings2f936352014-08-05 14:04:04 +10009280
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009281#if defined(__APPLE__)
9282/*[clinic input]
9283os._fcopyfile
9284
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009285 in_fd: int
9286 out_fd: int
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009287 flags: int
9288 /
9289
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009290Efficiently copy content or metadata of 2 regular file descriptors (macOS).
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009291[clinic start generated code]*/
9292
9293static PyObject *
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009294os__fcopyfile_impl(PyObject *module, int in_fd, int out_fd, int flags)
9295/*[clinic end generated code: output=c9d1a35a992e401b input=1e34638a86948795]*/
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009296{
9297 int ret;
9298
9299 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009300 ret = fcopyfile(in_fd, out_fd, NULL, flags);
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009301 Py_END_ALLOW_THREADS
9302 if (ret < 0)
9303 return posix_error();
9304 Py_RETURN_NONE;
9305}
9306#endif
9307
9308
Larry Hastings2f936352014-08-05 14:04:04 +10009309/*[clinic input]
9310os.fstat
9311
9312 fd : int
9313
9314Perform a stat system call on the given file descriptor.
9315
9316Like stat(), but for an open file descriptor.
9317Equivalent to os.stat(fd).
9318[clinic start generated code]*/
9319
Larry Hastings2f936352014-08-05 14:04:04 +10009320static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009321os_fstat_impl(PyObject *module, int fd)
9322/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009323{
Victor Stinner8c62be82010-05-06 00:08:46 +00009324 STRUCT_STAT st;
9325 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009326 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009327
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009328 do {
9329 Py_BEGIN_ALLOW_THREADS
9330 res = FSTAT(fd, &st);
9331 Py_END_ALLOW_THREADS
9332 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner8c62be82010-05-06 00:08:46 +00009333 if (res != 0) {
Martin v. Löwis14694662006-02-03 12:54:16 +00009334#ifdef MS_WINDOWS
Victor Stinnerb024e842012-10-31 22:24:06 +01009335 return PyErr_SetFromWindowsErr(0);
Martin v. Löwis14694662006-02-03 12:54:16 +00009336#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009337 return (!async_err) ? posix_error() : NULL;
Martin v. Löwis14694662006-02-03 12:54:16 +00009338#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00009339 }
Tim Peters5aa91602002-01-30 05:46:57 +00009340
Victor Stinner4195b5c2012-02-08 23:03:19 +01009341 return _pystat_fromstructstat(&st);
Guido van Rossum687dd131993-05-17 08:34:16 +00009342}
9343
Larry Hastings2f936352014-08-05 14:04:04 +10009344
9345/*[clinic input]
9346os.isatty -> bool
9347 fd: int
9348 /
9349
9350Return True if the fd is connected to a terminal.
9351
9352Return True if the file descriptor is an open file descriptor
9353connected to the slave end of a terminal.
9354[clinic start generated code]*/
9355
Larry Hastings2f936352014-08-05 14:04:04 +10009356static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009357os_isatty_impl(PyObject *module, int fd)
9358/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009359{
Steve Dower8fc89802015-04-12 00:26:27 -04009360 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -04009361 _Py_BEGIN_SUPPRESS_IPH
9362 return_value = isatty(fd);
9363 _Py_END_SUPPRESS_IPH
9364 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +10009365}
9366
9367
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009368#ifdef HAVE_PIPE
Larry Hastings2f936352014-08-05 14:04:04 +10009369/*[clinic input]
9370os.pipe
9371
9372Create a pipe.
9373
9374Returns a tuple of two file descriptors:
9375 (read_fd, write_fd)
9376[clinic start generated code]*/
9377
Larry Hastings2f936352014-08-05 14:04:04 +10009378static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009379os_pipe_impl(PyObject *module)
9380/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00009381{
Victor Stinner8c62be82010-05-06 00:08:46 +00009382 int fds[2];
Victor Stinnerdaf45552013-08-28 00:53:59 +02009383#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00009384 HANDLE read, write;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009385 SECURITY_ATTRIBUTES attr;
Victor Stinner8c62be82010-05-06 00:08:46 +00009386 BOOL ok;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009387#else
9388 int res;
9389#endif
9390
9391#ifdef MS_WINDOWS
9392 attr.nLength = sizeof(attr);
9393 attr.lpSecurityDescriptor = NULL;
9394 attr.bInheritHandle = FALSE;
9395
9396 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08009397 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009398 ok = CreatePipe(&read, &write, &attr, 0);
9399 if (ok) {
Benjamin Petersonca470632016-09-06 13:47:26 -07009400 fds[0] = _open_osfhandle((intptr_t)read, _O_RDONLY);
9401 fds[1] = _open_osfhandle((intptr_t)write, _O_WRONLY);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009402 if (fds[0] == -1 || fds[1] == -1) {
9403 CloseHandle(read);
9404 CloseHandle(write);
9405 ok = 0;
9406 }
9407 }
Steve Dowerc3630612016-11-19 18:41:16 -08009408 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009409 Py_END_ALLOW_THREADS
9410
Victor Stinner8c62be82010-05-06 00:08:46 +00009411 if (!ok)
Victor Stinnerb024e842012-10-31 22:24:06 +01009412 return PyErr_SetFromWindowsErr(0);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009413#else
9414
9415#ifdef HAVE_PIPE2
9416 Py_BEGIN_ALLOW_THREADS
9417 res = pipe2(fds, O_CLOEXEC);
9418 Py_END_ALLOW_THREADS
9419
9420 if (res != 0 && errno == ENOSYS)
9421 {
9422#endif
9423 Py_BEGIN_ALLOW_THREADS
9424 res = pipe(fds);
9425 Py_END_ALLOW_THREADS
9426
9427 if (res == 0) {
9428 if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
9429 close(fds[0]);
9430 close(fds[1]);
9431 return NULL;
9432 }
9433 if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
9434 close(fds[0]);
9435 close(fds[1]);
9436 return NULL;
9437 }
9438 }
9439#ifdef HAVE_PIPE2
9440 }
9441#endif
9442
9443 if (res != 0)
9444 return PyErr_SetFromErrno(PyExc_OSError);
9445#endif /* !MS_WINDOWS */
9446 return Py_BuildValue("(ii)", fds[0], fds[1]);
Guido van Rossum687dd131993-05-17 08:34:16 +00009447}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009448#endif /* HAVE_PIPE */
9449
Larry Hastings2f936352014-08-05 14:04:04 +10009450
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009451#ifdef HAVE_PIPE2
Larry Hastings2f936352014-08-05 14:04:04 +10009452/*[clinic input]
9453os.pipe2
9454
9455 flags: int
9456 /
9457
9458Create a pipe with flags set atomically.
9459
9460Returns a tuple of two file descriptors:
9461 (read_fd, write_fd)
9462
9463flags can be constructed by ORing together one or more of these values:
9464O_NONBLOCK, O_CLOEXEC.
9465[clinic start generated code]*/
9466
Larry Hastings2f936352014-08-05 14:04:04 +10009467static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009468os_pipe2_impl(PyObject *module, int flags)
9469/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009470{
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009471 int fds[2];
9472 int res;
9473
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009474 res = pipe2(fds, flags);
9475 if (res != 0)
9476 return posix_error();
9477 return Py_BuildValue("(ii)", fds[0], fds[1]);
9478}
9479#endif /* HAVE_PIPE2 */
9480
Larry Hastings2f936352014-08-05 14:04:04 +10009481
Ross Lagerwall7807c352011-03-17 20:20:30 +02009482#ifdef HAVE_WRITEV
Larry Hastings2f936352014-08-05 14:04:04 +10009483/*[clinic input]
9484os.writev -> Py_ssize_t
9485 fd: int
9486 buffers: object
9487 /
9488
9489Iterate over buffers, and write the contents of each to a file descriptor.
9490
9491Returns the total number of bytes written.
9492buffers must be a sequence of bytes-like objects.
9493[clinic start generated code]*/
9494
Larry Hastings2f936352014-08-05 14:04:04 +10009495static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009496os_writev_impl(PyObject *module, int fd, PyObject *buffers)
9497/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009498{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009499 Py_ssize_t cnt;
Larry Hastings2f936352014-08-05 14:04:04 +10009500 Py_ssize_t result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009501 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009502 struct iovec *iov;
9503 Py_buffer *buf;
Larry Hastings2f936352014-08-05 14:04:04 +10009504
9505 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009506 PyErr_SetString(PyExc_TypeError,
9507 "writev() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009508 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009509 }
Larry Hastings2f936352014-08-05 14:04:04 +10009510 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009511 if (cnt < 0)
9512 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009513
Larry Hastings2f936352014-08-05 14:04:04 +10009514 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9515 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009516 }
9517
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009518 do {
9519 Py_BEGIN_ALLOW_THREADS
9520 result = writev(fd, iov, cnt);
9521 Py_END_ALLOW_THREADS
9522 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009523
9524 iov_cleanup(iov, buf, cnt);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009525 if (result < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009526 posix_error();
Victor Stinner57ddf782014-01-08 15:21:28 +01009527
Georg Brandl306336b2012-06-24 12:55:33 +02009528 return result;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009529}
Larry Hastings2f936352014-08-05 14:04:04 +10009530#endif /* HAVE_WRITEV */
9531
9532
9533#ifdef HAVE_PWRITE
9534/*[clinic input]
9535os.pwrite -> Py_ssize_t
9536
9537 fd: int
9538 buffer: Py_buffer
9539 offset: Py_off_t
9540 /
9541
9542Write bytes to a file descriptor starting at a particular offset.
9543
9544Write buffer to fd, starting at offset bytes from the beginning of
9545the file. Returns the number of bytes writte. Does not change the
9546current file offset.
9547[clinic start generated code]*/
9548
Larry Hastings2f936352014-08-05 14:04:04 +10009549static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009550os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
9551/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009552{
9553 Py_ssize_t size;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009554 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009555
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009556 do {
9557 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009558 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009559 size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009560 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009561 Py_END_ALLOW_THREADS
9562 } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +10009563
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009564 if (size < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009565 posix_error();
9566 return size;
9567}
9568#endif /* HAVE_PWRITE */
9569
Pablo Galindo4defba32018-01-27 16:16:37 +00009570#if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
9571/*[clinic input]
9572os.pwritev -> Py_ssize_t
9573
9574 fd: int
9575 buffers: object
9576 offset: Py_off_t
9577 flags: int = 0
9578 /
9579
9580Writes the contents of bytes-like objects to a file descriptor at a given offset.
9581
9582Combines the functionality of writev() and pwrite(). All buffers must be a sequence
9583of bytes-like objects. Buffers are processed in array order. Entire contents of first
9584buffer is written before proceeding to second, and so on. The operating system may
9585set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
9586This function writes the contents of each object to the file descriptor and returns
9587the total number of bytes written.
9588
9589The flags argument contains a bitwise OR of zero or more of the following flags:
9590
9591- RWF_DSYNC
9592- RWF_SYNC
9593
9594Using non-zero flags requires Linux 4.7 or newer.
9595[clinic start generated code]*/
9596
9597static Py_ssize_t
9598os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9599 int flags)
9600/*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=803dc5ddbf0cfd3b]*/
9601{
9602 Py_ssize_t cnt;
9603 Py_ssize_t result;
9604 int async_err = 0;
9605 struct iovec *iov;
9606 Py_buffer *buf;
9607
9608 if (!PySequence_Check(buffers)) {
9609 PyErr_SetString(PyExc_TypeError,
9610 "pwritev() arg 2 must be a sequence");
9611 return -1;
9612 }
9613
9614 cnt = PySequence_Size(buffers);
9615 if (cnt < 0) {
9616 return -1;
9617 }
9618
9619#ifndef HAVE_PWRITEV2
9620 if(flags != 0) {
9621 argument_unavailable_error("pwritev2", "flags");
9622 return -1;
9623 }
9624#endif
9625
9626 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9627 return -1;
9628 }
9629#ifdef HAVE_PWRITEV2
9630 do {
9631 Py_BEGIN_ALLOW_THREADS
9632 _Py_BEGIN_SUPPRESS_IPH
9633 result = pwritev2(fd, iov, cnt, offset, flags);
9634 _Py_END_SUPPRESS_IPH
9635 Py_END_ALLOW_THREADS
9636 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9637#else
9638 do {
9639 Py_BEGIN_ALLOW_THREADS
9640 _Py_BEGIN_SUPPRESS_IPH
9641 result = pwritev(fd, iov, cnt, offset);
9642 _Py_END_SUPPRESS_IPH
9643 Py_END_ALLOW_THREADS
9644 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9645#endif
9646
9647 iov_cleanup(iov, buf, cnt);
9648 if (result < 0) {
9649 if (!async_err) {
9650 posix_error();
9651 }
9652 return -1;
9653 }
9654
9655 return result;
9656}
9657#endif /* HAVE_PWRITEV */
9658
Pablo Galindoaac4d032019-05-31 19:39:47 +01009659#ifdef HAVE_COPY_FILE_RANGE
9660/*[clinic input]
9661
9662os.copy_file_range
9663 src: int
9664 Source file descriptor.
9665 dst: int
9666 Destination file descriptor.
9667 count: Py_ssize_t
9668 Number of bytes to copy.
9669 offset_src: object = None
9670 Starting offset in src.
9671 offset_dst: object = None
9672 Starting offset in dst.
9673
9674Copy count bytes from one file descriptor to another.
9675
9676If offset_src is None, then src is read from the current position;
9677respectively for offset_dst.
9678[clinic start generated code]*/
9679
9680static PyObject *
9681os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
9682 PyObject *offset_src, PyObject *offset_dst)
9683/*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
9684{
9685 off_t offset_src_val, offset_dst_val;
9686 off_t *p_offset_src = NULL;
9687 off_t *p_offset_dst = NULL;
9688 Py_ssize_t ret;
9689 int async_err = 0;
9690 /* The flags argument is provided to allow
9691 * for future extensions and currently must be to 0. */
9692 int flags = 0;
Pablo Galindo4defba32018-01-27 16:16:37 +00009693
9694
Pablo Galindoaac4d032019-05-31 19:39:47 +01009695 if (count < 0) {
9696 PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
9697 return NULL;
9698 }
9699
9700 if (offset_src != Py_None) {
9701 if (!Py_off_t_converter(offset_src, &offset_src_val)) {
9702 return NULL;
9703 }
9704 p_offset_src = &offset_src_val;
9705 }
9706
9707 if (offset_dst != Py_None) {
9708 if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
9709 return NULL;
9710 }
9711 p_offset_dst = &offset_dst_val;
9712 }
9713
9714 do {
9715 Py_BEGIN_ALLOW_THREADS
9716 ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
9717 Py_END_ALLOW_THREADS
9718 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9719
9720 if (ret < 0) {
9721 return (!async_err) ? posix_error() : NULL;
9722 }
9723
9724 return PyLong_FromSsize_t(ret);
9725}
9726#endif /* HAVE_COPY_FILE_RANGE*/
Larry Hastings2f936352014-08-05 14:04:04 +10009727
9728#ifdef HAVE_MKFIFO
9729/*[clinic input]
9730os.mkfifo
9731
9732 path: path_t
9733 mode: int=0o666
9734 *
9735 dir_fd: dir_fd(requires='mkfifoat')=None
9736
9737Create a "fifo" (a POSIX named pipe).
9738
9739If dir_fd is not None, it should be a file descriptor open to a directory,
9740 and path should be relative; path will then be relative to that directory.
9741dir_fd may not be implemented on your platform.
9742 If it is unavailable, using it will raise a NotImplementedError.
9743[clinic start generated code]*/
9744
Larry Hastings2f936352014-08-05 14:04:04 +10009745static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009746os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
9747/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009748{
9749 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009750 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009751
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009752 do {
9753 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009754#ifdef HAVE_MKFIFOAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009755 if (dir_fd != DEFAULT_DIR_FD)
9756 result = mkfifoat(dir_fd, path->narrow, mode);
9757 else
Ross Lagerwall7807c352011-03-17 20:20:30 +02009758#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009759 result = mkfifo(path->narrow, mode);
9760 Py_END_ALLOW_THREADS
9761 } while (result != 0 && errno == EINTR &&
9762 !(async_err = PyErr_CheckSignals()));
9763 if (result != 0)
9764 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009765
9766 Py_RETURN_NONE;
9767}
9768#endif /* HAVE_MKFIFO */
9769
9770
9771#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
9772/*[clinic input]
9773os.mknod
9774
9775 path: path_t
9776 mode: int=0o600
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009777 device: dev_t=0
Larry Hastings2f936352014-08-05 14:04:04 +10009778 *
9779 dir_fd: dir_fd(requires='mknodat')=None
9780
9781Create a node in the file system.
9782
9783Create a node in the file system (file, device special file or named pipe)
9784at path. mode specifies both the permissions to use and the
9785type of node to be created, being combined (bitwise OR) with one of
9786S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
9787device defines the newly created device special file (probably using
9788os.makedev()). Otherwise device is ignored.
9789
9790If dir_fd is not None, it should be a file descriptor open to a directory,
9791 and path should be relative; path will then be relative to that directory.
9792dir_fd may not be implemented on your platform.
9793 If it is unavailable, using it will raise a NotImplementedError.
9794[clinic start generated code]*/
9795
Larry Hastings2f936352014-08-05 14:04:04 +10009796static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009797os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
Larry Hastings89964c42015-04-14 18:07:59 -04009798 int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009799/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009800{
9801 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009802 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009803
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009804 do {
9805 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009806#ifdef HAVE_MKNODAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009807 if (dir_fd != DEFAULT_DIR_FD)
9808 result = mknodat(dir_fd, path->narrow, mode, device);
9809 else
Larry Hastings2f936352014-08-05 14:04:04 +10009810#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009811 result = mknod(path->narrow, mode, device);
9812 Py_END_ALLOW_THREADS
9813 } while (result != 0 && errno == EINTR &&
9814 !(async_err = PyErr_CheckSignals()));
9815 if (result != 0)
9816 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009817
9818 Py_RETURN_NONE;
9819}
9820#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
9821
9822
9823#ifdef HAVE_DEVICE_MACROS
9824/*[clinic input]
9825os.major -> unsigned_int
9826
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009827 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009828 /
9829
9830Extracts a device major number from a raw device number.
9831[clinic start generated code]*/
9832
Larry Hastings2f936352014-08-05 14:04:04 +10009833static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009834os_major_impl(PyObject *module, dev_t device)
9835/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009836{
9837 return major(device);
9838}
9839
9840
9841/*[clinic input]
9842os.minor -> unsigned_int
9843
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009844 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009845 /
9846
9847Extracts a device minor number from a raw device number.
9848[clinic start generated code]*/
9849
Larry Hastings2f936352014-08-05 14:04:04 +10009850static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009851os_minor_impl(PyObject *module, dev_t device)
9852/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009853{
9854 return minor(device);
9855}
9856
9857
9858/*[clinic input]
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009859os.makedev -> dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009860
9861 major: int
9862 minor: int
9863 /
9864
9865Composes a raw device number from the major and minor device numbers.
9866[clinic start generated code]*/
9867
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009868static dev_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009869os_makedev_impl(PyObject *module, int major, int minor)
9870/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009871{
9872 return makedev(major, minor);
9873}
9874#endif /* HAVE_DEVICE_MACROS */
9875
9876
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009877#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009878/*[clinic input]
9879os.ftruncate
9880
9881 fd: int
9882 length: Py_off_t
9883 /
9884
9885Truncate a file, specified by file descriptor, to a specific length.
9886[clinic start generated code]*/
9887
Larry Hastings2f936352014-08-05 14:04:04 +10009888static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009889os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
9890/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009891{
9892 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009893 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009894
Steve Dowerb82e17e2019-05-23 08:45:22 -07009895 if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
9896 return NULL;
9897 }
9898
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009899 do {
9900 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009901 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009902#ifdef MS_WINDOWS
9903 result = _chsize_s(fd, length);
9904#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009905 result = ftruncate(fd, length);
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009906#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009907 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009908 Py_END_ALLOW_THREADS
9909 } while (result != 0 && errno == EINTR &&
9910 !(async_err = PyErr_CheckSignals()));
9911 if (result != 0)
9912 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009913 Py_RETURN_NONE;
9914}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009915#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009916
9917
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009918#if defined HAVE_TRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009919/*[clinic input]
9920os.truncate
9921 path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
9922 length: Py_off_t
9923
9924Truncate a file, specified by path, to a specific length.
9925
9926On some platforms, path may also be specified as an open file descriptor.
9927 If this functionality is unavailable, using it raises an exception.
9928[clinic start generated code]*/
9929
Larry Hastings2f936352014-08-05 14:04:04 +10009930static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009931os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
9932/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009933{
9934 int result;
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009935#ifdef MS_WINDOWS
9936 int fd;
9937#endif
9938
9939 if (path->fd != -1)
9940 return os_ftruncate_impl(module, path->fd, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009941
Steve Dowerb82e17e2019-05-23 08:45:22 -07009942 if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
9943 return NULL;
9944 }
9945
Larry Hastings2f936352014-08-05 14:04:04 +10009946 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009947 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009948#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07009949 fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
Victor Stinnercc0bbbc2015-04-25 00:21:52 +02009950 if (fd < 0)
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009951 result = -1;
9952 else {
9953 result = _chsize_s(fd, length);
9954 close(fd);
9955 if (result < 0)
9956 errno = result;
9957 }
9958#else
9959 result = truncate(path->narrow, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009960#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009961 _Py_END_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10009962 Py_END_ALLOW_THREADS
9963 if (result < 0)
Alexey Izbyshev83460312018-10-20 03:28:22 +03009964 return posix_path_error(path);
Larry Hastings2f936352014-08-05 14:04:04 +10009965
9966 Py_RETURN_NONE;
9967}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009968#endif /* HAVE_TRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009969
Ross Lagerwall7807c352011-03-17 20:20:30 +02009970
Victor Stinnerd6b17692014-09-30 12:20:05 +02009971/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
9972 and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
9973 defined, which is the case in Python on AIX. AIX bug report:
9974 http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
9975#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
9976# define POSIX_FADVISE_AIX_BUG
9977#endif
9978
Victor Stinnerec39e262014-09-30 12:35:58 +02009979
Victor Stinnerd6b17692014-09-30 12:20:05 +02009980#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +10009981/*[clinic input]
9982os.posix_fallocate
9983
9984 fd: int
9985 offset: Py_off_t
9986 length: Py_off_t
9987 /
9988
9989Ensure a file has allocated at least a particular number of bytes on disk.
9990
9991Ensure that the file specified by fd encompasses a range of bytes
9992starting at offset bytes from the beginning and continuing for length bytes.
9993[clinic start generated code]*/
9994
Larry Hastings2f936352014-08-05 14:04:04 +10009995static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009996os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -04009997 Py_off_t length)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009998/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009999{
10000 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010001 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010002
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010003 do {
10004 Py_BEGIN_ALLOW_THREADS
10005 result = posix_fallocate(fd, offset, length);
10006 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010007 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10008
10009 if (result == 0)
10010 Py_RETURN_NONE;
10011
10012 if (async_err)
10013 return NULL;
10014
10015 errno = result;
10016 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010017}
Victor Stinnerec39e262014-09-30 12:35:58 +020010018#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
Larry Hastings2f936352014-08-05 14:04:04 +100010019
Ross Lagerwall7807c352011-03-17 20:20:30 +020010020
Victor Stinnerd6b17692014-09-30 12:20:05 +020010021#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +100010022/*[clinic input]
10023os.posix_fadvise
10024
10025 fd: int
10026 offset: Py_off_t
10027 length: Py_off_t
10028 advice: int
10029 /
10030
10031Announce an intention to access data in a specific pattern.
10032
10033Announce an intention to access data in a specific pattern, thus allowing
10034the kernel to make optimizations.
10035The advice applies to the region of the file specified by fd starting at
10036offset and continuing for length bytes.
10037advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
10038POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
10039POSIX_FADV_DONTNEED.
10040[clinic start generated code]*/
10041
Larry Hastings2f936352014-08-05 14:04:04 +100010042static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010043os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -040010044 Py_off_t length, int advice)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010045/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010046{
10047 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010048 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010049
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010050 do {
10051 Py_BEGIN_ALLOW_THREADS
10052 result = posix_fadvise(fd, offset, length, advice);
10053 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010054 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10055
10056 if (result == 0)
10057 Py_RETURN_NONE;
10058
10059 if (async_err)
10060 return NULL;
10061
10062 errno = result;
10063 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010064}
Victor Stinnerec39e262014-09-30 12:35:58 +020010065#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
Ross Lagerwall7807c352011-03-17 20:20:30 +020010066
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000010067
Victor Stinner623ed612020-01-21 19:25:32 +010010068#ifdef PY_PUTENV_DICT
Larry Hastings2f936352014-08-05 14:04:04 +100010069static void
Victor Stinner623ed612020-01-21 19:25:32 +010010070posix_putenv_dict_setitem(PyObject *name, PyObject *value)
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010071{
Victor Stinner623ed612020-01-21 19:25:32 +010010072 /* Install the first arg and newstr in putenv_dict;
Larry Hastings2f936352014-08-05 14:04:04 +100010073 * this will cause previous value to be collected. This has to
10074 * happen after the real putenv() call because the old value
10075 * was still accessible until then. */
Victor Stinner623ed612020-01-21 19:25:32 +010010076 if (PyDict_SetItem(_posixstate_global->putenv_dict, name, value))
Larry Hastings2f936352014-08-05 14:04:04 +100010077 /* really not much we can do; just leak */
10078 PyErr_Clear();
10079 else
10080 Py_DECREF(value);
10081}
Victor Stinner623ed612020-01-21 19:25:32 +010010082#endif /* PY_PUTENV_DICT */
Larry Hastings2f936352014-08-05 14:04:04 +100010083
10084
Thomas Hellerf78f12a2007-11-08 19:33:05 +000010085#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010086/*[clinic input]
10087os.putenv
10088
10089 name: unicode
10090 value: unicode
10091 /
10092
10093Change or add an environment variable.
10094[clinic start generated code]*/
10095
Larry Hastings2f936352014-08-05 14:04:04 +100010096static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010097os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10098/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010099{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030010100 const wchar_t *env;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +030010101 Py_ssize_t size;
Larry Hastings2f936352014-08-05 14:04:04 +100010102
Serhiy Storchaka77703942017-06-25 07:33:01 +030010103 /* Search from index 1 because on Windows starting '=' is allowed for
10104 defining hidden environment variables. */
10105 if (PyUnicode_GET_LENGTH(name) == 0 ||
10106 PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
10107 {
10108 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10109 return NULL;
10110 }
Larry Hastings2f936352014-08-05 14:04:04 +100010111 PyObject *unicode = PyUnicode_FromFormat("%U=%U", name, value);
10112 if (unicode == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010113 return NULL;
Victor Stinner84ae1182010-05-06 22:05:07 +000010114 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +030010115
10116 env = PyUnicode_AsUnicodeAndSize(unicode, &size);
10117 if (env == NULL)
10118 goto error;
10119 if (size > _MAX_ENV) {
Victor Stinner65170952011-11-22 22:16:17 +010010120 PyErr_Format(PyExc_ValueError,
10121 "the environment variable is longer than %u characters",
10122 _MAX_ENV);
10123 goto error;
10124 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +030010125 if (wcslen(env) != (size_t)size) {
10126 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnereb5657a2011-09-30 01:44:27 +020010127 goto error;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +030010128 }
10129
Larry Hastings2f936352014-08-05 14:04:04 +100010130 if (_wputenv(env)) {
Victor Stinner8c62be82010-05-06 00:08:46 +000010131 posix_error();
Victor Stinner84ae1182010-05-06 22:05:07 +000010132 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +000010133 }
Victor Stinner0852c7d2020-01-22 21:53:26 +010010134 Py_DECREF(unicode);
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010135
Victor Stinner84ae1182010-05-06 22:05:07 +000010136 Py_RETURN_NONE;
10137
10138error:
Larry Hastings2f936352014-08-05 14:04:04 +100010139 Py_DECREF(unicode);
Victor Stinner84ae1182010-05-06 22:05:07 +000010140 return NULL;
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010141}
Victor Stinnerb477d192020-01-22 22:48:16 +010010142/* repeat !defined(MS_WINDOWS) to workaround an Argument Clinic issue */
10143#elif (defined(HAVE_SETENV) || defined(HAVE_PUTENV)) && !defined(MS_WINDOWS)
Larry Hastings2f936352014-08-05 14:04:04 +100010144/*[clinic input]
10145os.putenv
Guido van Rossumb6a47161997-09-15 22:54:34 +000010146
Larry Hastings2f936352014-08-05 14:04:04 +100010147 name: FSConverter
10148 value: FSConverter
10149 /
10150
10151Change or add an environment variable.
10152[clinic start generated code]*/
10153
Larry Hastings2f936352014-08-05 14:04:04 +100010154static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010155os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10156/*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010157{
Serhiy Storchaka77703942017-06-25 07:33:01 +030010158 const char *name_string = PyBytes_AS_STRING(name);
10159 const char *value_string = PyBytes_AS_STRING(value);
Larry Hastings2f936352014-08-05 14:04:04 +100010160
Serhiy Storchaka77703942017-06-25 07:33:01 +030010161 if (strchr(name_string, '=') != NULL) {
10162 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10163 return NULL;
10164 }
Victor Stinnerb477d192020-01-22 22:48:16 +010010165
10166#ifdef HAVE_SETENV
10167 if (setenv(name_string, value_string, 1)) {
10168 return posix_error();
10169 }
10170#else
10171 PyObject *bytes = PyBytes_FromFormat("%s=%s", name_string, value_string);
Larry Hastings2f936352014-08-05 14:04:04 +100010172 if (bytes == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010173 return NULL;
10174 }
10175
Victor Stinnerb477d192020-01-22 22:48:16 +010010176 char *env = PyBytes_AS_STRING(bytes);
Larry Hastings2f936352014-08-05 14:04:04 +100010177 if (putenv(env)) {
10178 Py_DECREF(bytes);
10179 return posix_error();
10180 }
10181
Victor Stinner623ed612020-01-21 19:25:32 +010010182 posix_putenv_dict_setitem(name, bytes);
Victor Stinnerb477d192020-01-22 22:48:16 +010010183#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010184 Py_RETURN_NONE;
10185}
Victor Stinnerb477d192020-01-22 22:48:16 +010010186#endif /* defined(HAVE_SETENV) || defined(HAVE_PUTENV) */
Larry Hastings2f936352014-08-05 14:04:04 +100010187
10188
Victor Stinnerb73dd022020-01-22 21:11:17 +010010189#ifdef HAVE_UNSETENV
Larry Hastings2f936352014-08-05 14:04:04 +100010190/*[clinic input]
10191os.unsetenv
10192 name: FSConverter
10193 /
10194
10195Delete an environment variable.
10196[clinic start generated code]*/
10197
Larry Hastings2f936352014-08-05 14:04:04 +100010198static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010199os_unsetenv_impl(PyObject *module, PyObject *name)
10200/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010201{
Victor Stinner984890f2011-11-24 13:53:38 +010010202#ifndef HAVE_BROKEN_UNSETENV
Victor Stinner60b385e2011-11-22 22:01:28 +010010203 int err;
Victor Stinner984890f2011-11-24 13:53:38 +010010204#endif
Victor Stinner84ae1182010-05-06 22:05:07 +000010205
Victor Stinner984890f2011-11-24 13:53:38 +010010206#ifdef HAVE_BROKEN_UNSETENV
10207 unsetenv(PyBytes_AS_STRING(name));
10208#else
Victor Stinner65170952011-11-22 22:16:17 +010010209 err = unsetenv(PyBytes_AS_STRING(name));
Larry Hastings2f936352014-08-05 14:04:04 +100010210 if (err)
Victor Stinner60b385e2011-11-22 22:01:28 +010010211 return posix_error();
Victor Stinner984890f2011-11-24 13:53:38 +010010212#endif
Guido van Rossumc524d952001-10-19 01:31:59 +000010213
Victor Stinner623ed612020-01-21 19:25:32 +010010214#ifdef PY_PUTENV_DICT
10215 /* Remove the key from putenv_dict;
Victor Stinner8c62be82010-05-06 00:08:46 +000010216 * this will cause it to be collected. This has to
10217 * happen after the real unsetenv() call because the
10218 * old value was still accessible until then.
10219 */
Victor Stinner623ed612020-01-21 19:25:32 +010010220 if (PyDict_DelItem(_posixstate(module)->putenv_dict, name)) {
Victor Stinner8c62be82010-05-06 00:08:46 +000010221 /* really not much we can do; just leak */
Serhiy Storchakaa24107b2019-02-25 17:59:46 +020010222 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
10223 return NULL;
10224 }
Victor Stinner8c62be82010-05-06 00:08:46 +000010225 PyErr_Clear();
10226 }
Victor Stinner623ed612020-01-21 19:25:32 +010010227#endif
10228
Victor Stinner84ae1182010-05-06 22:05:07 +000010229 Py_RETURN_NONE;
Guido van Rossumc524d952001-10-19 01:31:59 +000010230}
Larry Hastings2f936352014-08-05 14:04:04 +100010231#endif /* HAVE_UNSETENV */
Guido van Rossumc524d952001-10-19 01:31:59 +000010232
Larry Hastings2f936352014-08-05 14:04:04 +100010233
10234/*[clinic input]
10235os.strerror
10236
10237 code: int
10238 /
10239
10240Translate an error code to a message string.
10241[clinic start generated code]*/
10242
Larry Hastings2f936352014-08-05 14:04:04 +100010243static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010244os_strerror_impl(PyObject *module, int code)
10245/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010246{
10247 char *message = strerror(code);
Victor Stinner8c62be82010-05-06 00:08:46 +000010248 if (message == NULL) {
10249 PyErr_SetString(PyExc_ValueError,
10250 "strerror() argument out of range");
10251 return NULL;
10252 }
Victor Stinner1b579672011-12-17 05:47:23 +010010253 return PyUnicode_DecodeLocale(message, "surrogateescape");
Guido van Rossumb6a47161997-09-15 22:54:34 +000010254}
Guido van Rossumb6a47161997-09-15 22:54:34 +000010255
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010256
Guido van Rossumc9641791998-08-04 15:26:23 +000010257#ifdef HAVE_SYS_WAIT_H
Fred Drake106c1a02002-04-23 15:58:02 +000010258#ifdef WCOREDUMP
Larry Hastings2f936352014-08-05 14:04:04 +100010259/*[clinic input]
10260os.WCOREDUMP -> bool
10261
10262 status: int
10263 /
10264
10265Return True if the process returning status was dumped to a core file.
10266[clinic start generated code]*/
10267
Larry Hastings2f936352014-08-05 14:04:04 +100010268static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010269os_WCOREDUMP_impl(PyObject *module, int status)
10270/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010271{
10272 WAIT_TYPE wait_status;
10273 WAIT_STATUS_INT(wait_status) = status;
10274 return WCOREDUMP(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010275}
10276#endif /* WCOREDUMP */
10277
Larry Hastings2f936352014-08-05 14:04:04 +100010278
Fred Drake106c1a02002-04-23 15:58:02 +000010279#ifdef WIFCONTINUED
Larry Hastings2f936352014-08-05 14:04:04 +100010280/*[clinic input]
10281os.WIFCONTINUED -> bool
10282
10283 status: int
10284
10285Return True if a particular process was continued from a job control stop.
10286
10287Return True if the process returning status was continued from a
10288job control stop.
10289[clinic start generated code]*/
10290
Larry Hastings2f936352014-08-05 14:04:04 +100010291static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010292os_WIFCONTINUED_impl(PyObject *module, int status)
10293/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010294{
10295 WAIT_TYPE wait_status;
10296 WAIT_STATUS_INT(wait_status) = status;
10297 return WIFCONTINUED(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010298}
10299#endif /* WIFCONTINUED */
10300
Larry Hastings2f936352014-08-05 14:04:04 +100010301
Guido van Rossumc9641791998-08-04 15:26:23 +000010302#ifdef WIFSTOPPED
Larry Hastings2f936352014-08-05 14:04:04 +100010303/*[clinic input]
10304os.WIFSTOPPED -> bool
10305
10306 status: int
10307
10308Return True if the process returning status was stopped.
10309[clinic start generated code]*/
10310
Larry Hastings2f936352014-08-05 14:04:04 +100010311static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010312os_WIFSTOPPED_impl(PyObject *module, int status)
10313/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010314{
10315 WAIT_TYPE wait_status;
10316 WAIT_STATUS_INT(wait_status) = status;
10317 return WIFSTOPPED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010318}
10319#endif /* WIFSTOPPED */
10320
Larry Hastings2f936352014-08-05 14:04:04 +100010321
Guido van Rossumc9641791998-08-04 15:26:23 +000010322#ifdef WIFSIGNALED
Larry Hastings2f936352014-08-05 14:04:04 +100010323/*[clinic input]
10324os.WIFSIGNALED -> bool
10325
10326 status: int
10327
10328Return True if the process returning status was terminated by a signal.
10329[clinic start generated code]*/
10330
Larry Hastings2f936352014-08-05 14:04:04 +100010331static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010332os_WIFSIGNALED_impl(PyObject *module, int status)
10333/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010334{
10335 WAIT_TYPE wait_status;
10336 WAIT_STATUS_INT(wait_status) = status;
10337 return WIFSIGNALED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010338}
10339#endif /* WIFSIGNALED */
10340
Larry Hastings2f936352014-08-05 14:04:04 +100010341
Guido van Rossumc9641791998-08-04 15:26:23 +000010342#ifdef WIFEXITED
Larry Hastings2f936352014-08-05 14:04:04 +100010343/*[clinic input]
10344os.WIFEXITED -> bool
10345
10346 status: int
10347
10348Return True if the process returning status exited via the exit() system call.
10349[clinic start generated code]*/
10350
Larry Hastings2f936352014-08-05 14:04:04 +100010351static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010352os_WIFEXITED_impl(PyObject *module, int status)
10353/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010354{
10355 WAIT_TYPE wait_status;
10356 WAIT_STATUS_INT(wait_status) = status;
10357 return WIFEXITED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010358}
10359#endif /* WIFEXITED */
10360
Larry Hastings2f936352014-08-05 14:04:04 +100010361
Guido van Rossum54ecc3d1999-01-27 17:53:11 +000010362#ifdef WEXITSTATUS
Larry Hastings2f936352014-08-05 14:04:04 +100010363/*[clinic input]
10364os.WEXITSTATUS -> int
10365
10366 status: int
10367
10368Return the process return code from status.
10369[clinic start generated code]*/
10370
Larry Hastings2f936352014-08-05 14:04:04 +100010371static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010372os_WEXITSTATUS_impl(PyObject *module, int status)
10373/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010374{
10375 WAIT_TYPE wait_status;
10376 WAIT_STATUS_INT(wait_status) = status;
10377 return WEXITSTATUS(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010378}
10379#endif /* WEXITSTATUS */
10380
Larry Hastings2f936352014-08-05 14:04:04 +100010381
Guido van Rossumc9641791998-08-04 15:26:23 +000010382#ifdef WTERMSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010383/*[clinic input]
10384os.WTERMSIG -> int
10385
10386 status: int
10387
10388Return the signal that terminated the process that provided the status value.
10389[clinic start generated code]*/
10390
Larry Hastings2f936352014-08-05 14:04:04 +100010391static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010392os_WTERMSIG_impl(PyObject *module, int status)
10393/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010394{
10395 WAIT_TYPE wait_status;
10396 WAIT_STATUS_INT(wait_status) = status;
10397 return WTERMSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010398}
10399#endif /* WTERMSIG */
10400
Larry Hastings2f936352014-08-05 14:04:04 +100010401
Guido van Rossumc9641791998-08-04 15:26:23 +000010402#ifdef WSTOPSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010403/*[clinic input]
10404os.WSTOPSIG -> int
10405
10406 status: int
10407
10408Return the signal that stopped the process that provided the status value.
10409[clinic start generated code]*/
10410
Larry Hastings2f936352014-08-05 14:04:04 +100010411static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010412os_WSTOPSIG_impl(PyObject *module, int status)
10413/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010414{
10415 WAIT_TYPE wait_status;
10416 WAIT_STATUS_INT(wait_status) = status;
10417 return WSTOPSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010418}
10419#endif /* WSTOPSIG */
Guido van Rossumc9641791998-08-04 15:26:23 +000010420#endif /* HAVE_SYS_WAIT_H */
10421
10422
Thomas Wouters477c8d52006-05-27 19:21:47 +000010423#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossumd5753e11999-10-19 13:29:23 +000010424#ifdef _SCO_DS
10425/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
10426 needed definitions in sys/statvfs.h */
10427#define _SVID3
10428#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000010429#include <sys/statvfs.h>
10430
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010431static PyObject*
10432_pystatvfs_fromstructstatvfs(struct statvfs st) {
Eddie Elizondob3966632019-11-05 07:16:14 -080010433 PyObject *StatVFSResultType = _posixstate_global->StatVFSResultType;
10434 PyObject *v = PyStructSequence_New((PyTypeObject *)StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000010435 if (v == NULL)
10436 return NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010437
10438#if !defined(HAVE_LARGEFILE_SUPPORT)
Victor Stinner8c62be82010-05-06 00:08:46 +000010439 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10440 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10441 PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
10442 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
10443 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
10444 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
10445 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
10446 PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
10447 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10448 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010449#else
Victor Stinner8c62be82010-05-06 00:08:46 +000010450 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10451 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10452 PyStructSequence_SET_ITEM(v, 2,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010453 PyLong_FromLongLong((long long) st.f_blocks));
Victor Stinner8c62be82010-05-06 00:08:46 +000010454 PyStructSequence_SET_ITEM(v, 3,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010455 PyLong_FromLongLong((long long) st.f_bfree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010456 PyStructSequence_SET_ITEM(v, 4,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010457 PyLong_FromLongLong((long long) st.f_bavail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010458 PyStructSequence_SET_ITEM(v, 5,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010459 PyLong_FromLongLong((long long) st.f_files));
Victor Stinner8c62be82010-05-06 00:08:46 +000010460 PyStructSequence_SET_ITEM(v, 6,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010461 PyLong_FromLongLong((long long) st.f_ffree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010462 PyStructSequence_SET_ITEM(v, 7,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010463 PyLong_FromLongLong((long long) st.f_favail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010464 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10465 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010466#endif
Michael Felt502d5512018-01-05 13:01:58 +010010467/* The _ALL_SOURCE feature test macro defines f_fsid as a structure
10468 * (issue #32390). */
10469#if defined(_AIX) && defined(_ALL_SOURCE)
10470 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
10471#else
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +010010472 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid));
Michael Felt502d5512018-01-05 13:01:58 +010010473#endif
Victor Stinnerf0a7bac2013-10-30 18:55:24 +010010474 if (PyErr_Occurred()) {
10475 Py_DECREF(v);
10476 return NULL;
10477 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010478
Victor Stinner8c62be82010-05-06 00:08:46 +000010479 return v;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010480}
10481
Larry Hastings2f936352014-08-05 14:04:04 +100010482
10483/*[clinic input]
10484os.fstatvfs
10485 fd: int
10486 /
10487
10488Perform an fstatvfs system call on the given fd.
10489
10490Equivalent to statvfs(fd).
10491[clinic start generated code]*/
10492
Larry Hastings2f936352014-08-05 14:04:04 +100010493static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010494os_fstatvfs_impl(PyObject *module, int fd)
10495/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010496{
10497 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010498 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010499 struct statvfs st;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010500
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010501 do {
10502 Py_BEGIN_ALLOW_THREADS
10503 result = fstatvfs(fd, &st);
10504 Py_END_ALLOW_THREADS
10505 } while (result != 0 && errno == EINTR &&
10506 !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +100010507 if (result != 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010508 return (!async_err) ? posix_error() : NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010509
Victor Stinner8c62be82010-05-06 00:08:46 +000010510 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010511}
Larry Hastings2f936352014-08-05 14:04:04 +100010512#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
Guido van Rossum94f6f721999-01-06 18:42:14 +000010513
10514
Thomas Wouters477c8d52006-05-27 19:21:47 +000010515#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossum94f6f721999-01-06 18:42:14 +000010516#include <sys/statvfs.h>
Larry Hastings2f936352014-08-05 14:04:04 +100010517/*[clinic input]
10518os.statvfs
Guido van Rossum94f6f721999-01-06 18:42:14 +000010519
Larry Hastings2f936352014-08-05 14:04:04 +100010520 path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
10521
10522Perform a statvfs system call on the given path.
10523
10524path may always be specified as a string.
10525On some platforms, path may also be specified as an open file descriptor.
10526 If this functionality is unavailable, using it raises an exception.
10527[clinic start generated code]*/
10528
Larry Hastings2f936352014-08-05 14:04:04 +100010529static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010530os_statvfs_impl(PyObject *module, path_t *path)
10531/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010532{
10533 int result;
10534 struct statvfs st;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010535
10536 Py_BEGIN_ALLOW_THREADS
10537#ifdef HAVE_FSTATVFS
Larry Hastings2f936352014-08-05 14:04:04 +100010538 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -070010539#ifdef __APPLE__
10540 /* handle weak-linking on Mac OS X 10.3 */
10541 if (fstatvfs == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010542 fd_specified("statvfs", path->fd);
10543 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010544 }
10545#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010546 result = fstatvfs(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010547 }
10548 else
10549#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010550 result = statvfs(path->narrow, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010551 Py_END_ALLOW_THREADS
10552
10553 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100010554 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010555 }
10556
Larry Hastings2f936352014-08-05 14:04:04 +100010557 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010558}
Larry Hastings2f936352014-08-05 14:04:04 +100010559#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
10560
Guido van Rossum94f6f721999-01-06 18:42:14 +000010561
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010562#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010563/*[clinic input]
10564os._getdiskusage
10565
Steve Dower23ad6d02018-02-22 10:39:10 -080010566 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +100010567
10568Return disk usage statistics about the given path as a (total, free) tuple.
10569[clinic start generated code]*/
10570
Larry Hastings2f936352014-08-05 14:04:04 +100010571static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -080010572os__getdiskusage_impl(PyObject *module, path_t *path)
10573/*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010574{
10575 BOOL retval;
10576 ULARGE_INTEGER _, total, free;
Joe Pamerc8c02492018-09-25 10:57:36 -040010577 DWORD err = 0;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010578
10579 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -080010580 retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010581 Py_END_ALLOW_THREADS
Joe Pamerc8c02492018-09-25 10:57:36 -040010582 if (retval == 0) {
10583 if (GetLastError() == ERROR_DIRECTORY) {
10584 wchar_t *dir_path = NULL;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010585
Joe Pamerc8c02492018-09-25 10:57:36 -040010586 dir_path = PyMem_New(wchar_t, path->length + 1);
10587 if (dir_path == NULL) {
10588 return PyErr_NoMemory();
10589 }
10590
10591 wcscpy_s(dir_path, path->length + 1, path->wide);
10592
10593 if (_dirnameW(dir_path) != -1) {
10594 Py_BEGIN_ALLOW_THREADS
10595 retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
10596 Py_END_ALLOW_THREADS
10597 }
10598 /* Record the last error in case it's modified by PyMem_Free. */
10599 err = GetLastError();
10600 PyMem_Free(dir_path);
10601 if (retval) {
10602 goto success;
10603 }
10604 }
10605 return PyErr_SetFromWindowsErr(err);
10606 }
10607
10608success:
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010609 return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
10610}
Larry Hastings2f936352014-08-05 14:04:04 +100010611#endif /* MS_WINDOWS */
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010612
10613
Fred Drakec9680921999-12-13 16:37:25 +000010614/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
10615 * It maps strings representing configuration variable names to
10616 * integer values, allowing those functions to be called with the
Thomas Wouters7e474022000-07-16 12:04:32 +000010617 * magic names instead of polluting the module's namespace with tons of
Fred Drake12c6e2d1999-12-14 21:25:03 +000010618 * rarely-used constants. There are three separate tables that use
10619 * these definitions.
Fred Drakebec628d1999-12-15 18:31:10 +000010620 *
10621 * This code is always included, even if none of the interfaces that
10622 * need it are included. The #if hackery needed to avoid it would be
10623 * sufficiently pervasive that it's not worth the loss of readability.
Fred Drakec9680921999-12-13 16:37:25 +000010624 */
10625struct constdef {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020010626 const char *name;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010627 int value;
Fred Drakec9680921999-12-13 16:37:25 +000010628};
10629
Fred Drake12c6e2d1999-12-14 21:25:03 +000010630static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010631conv_confname(PyObject *arg, int *valuep, struct constdef *table,
Guido van Rossum7d5baac2007-08-27 23:24:46 +000010632 size_t tablesize)
Fred Drake12c6e2d1999-12-14 21:25:03 +000010633{
Christian Heimes217cfd12007-12-02 14:31:20 +000010634 if (PyLong_Check(arg)) {
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010635 int value = _PyLong_AsInt(arg);
10636 if (value == -1 && PyErr_Occurred())
10637 return 0;
10638 *valuep = value;
Stefan Krah0e803b32010-11-26 16:16:47 +000010639 return 1;
Fred Drake12c6e2d1999-12-14 21:25:03 +000010640 }
Guido van Rossumbce56a62007-05-10 18:04:33 +000010641 else {
Stefan Krah0e803b32010-11-26 16:16:47 +000010642 /* look up the value in the table using a binary search */
10643 size_t lo = 0;
10644 size_t mid;
10645 size_t hi = tablesize;
10646 int cmp;
10647 const char *confname;
10648 if (!PyUnicode_Check(arg)) {
10649 PyErr_SetString(PyExc_TypeError,
10650 "configuration names must be strings or integers");
10651 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010652 }
Serhiy Storchaka06515832016-11-20 09:13:07 +020010653 confname = PyUnicode_AsUTF8(arg);
Stefan Krah0e803b32010-11-26 16:16:47 +000010654 if (confname == NULL)
10655 return 0;
10656 while (lo < hi) {
10657 mid = (lo + hi) / 2;
10658 cmp = strcmp(confname, table[mid].name);
10659 if (cmp < 0)
10660 hi = mid;
10661 else if (cmp > 0)
10662 lo = mid + 1;
10663 else {
10664 *valuep = table[mid].value;
10665 return 1;
10666 }
10667 }
10668 PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
10669 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010670 }
Fred Drake12c6e2d1999-12-14 21:25:03 +000010671}
10672
10673
10674#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
10675static struct constdef posix_constants_pathconf[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010676#ifdef _PC_ABI_AIO_XFER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010677 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000010678#endif
10679#ifdef _PC_ABI_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010680 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010681#endif
Fred Drakec9680921999-12-13 16:37:25 +000010682#ifdef _PC_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010683 {"PC_ASYNC_IO", _PC_ASYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010684#endif
10685#ifdef _PC_CHOWN_RESTRICTED
Victor Stinner8c62be82010-05-06 00:08:46 +000010686 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
Fred Drakec9680921999-12-13 16:37:25 +000010687#endif
10688#ifdef _PC_FILESIZEBITS
Victor Stinner8c62be82010-05-06 00:08:46 +000010689 {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
Fred Drakec9680921999-12-13 16:37:25 +000010690#endif
10691#ifdef _PC_LAST
Victor Stinner8c62be82010-05-06 00:08:46 +000010692 {"PC_LAST", _PC_LAST},
Fred Drakec9680921999-12-13 16:37:25 +000010693#endif
10694#ifdef _PC_LINK_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010695 {"PC_LINK_MAX", _PC_LINK_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010696#endif
10697#ifdef _PC_MAX_CANON
Victor Stinner8c62be82010-05-06 00:08:46 +000010698 {"PC_MAX_CANON", _PC_MAX_CANON},
Fred Drakec9680921999-12-13 16:37:25 +000010699#endif
10700#ifdef _PC_MAX_INPUT
Victor Stinner8c62be82010-05-06 00:08:46 +000010701 {"PC_MAX_INPUT", _PC_MAX_INPUT},
Fred Drakec9680921999-12-13 16:37:25 +000010702#endif
10703#ifdef _PC_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010704 {"PC_NAME_MAX", _PC_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010705#endif
10706#ifdef _PC_NO_TRUNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010707 {"PC_NO_TRUNC", _PC_NO_TRUNC},
Fred Drakec9680921999-12-13 16:37:25 +000010708#endif
10709#ifdef _PC_PATH_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010710 {"PC_PATH_MAX", _PC_PATH_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010711#endif
10712#ifdef _PC_PIPE_BUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010713 {"PC_PIPE_BUF", _PC_PIPE_BUF},
Fred Drakec9680921999-12-13 16:37:25 +000010714#endif
10715#ifdef _PC_PRIO_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010716 {"PC_PRIO_IO", _PC_PRIO_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010717#endif
10718#ifdef _PC_SOCK_MAXBUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010719 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
Fred Drakec9680921999-12-13 16:37:25 +000010720#endif
10721#ifdef _PC_SYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010722 {"PC_SYNC_IO", _PC_SYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010723#endif
10724#ifdef _PC_VDISABLE
Victor Stinner8c62be82010-05-06 00:08:46 +000010725 {"PC_VDISABLE", _PC_VDISABLE},
Fred Drakec9680921999-12-13 16:37:25 +000010726#endif
Jesus Cea7e9065c2010-10-25 13:02:04 +000010727#ifdef _PC_ACL_ENABLED
10728 {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
10729#endif
10730#ifdef _PC_MIN_HOLE_SIZE
10731 {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
10732#endif
10733#ifdef _PC_ALLOC_SIZE_MIN
10734 {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
10735#endif
10736#ifdef _PC_REC_INCR_XFER_SIZE
10737 {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
10738#endif
10739#ifdef _PC_REC_MAX_XFER_SIZE
10740 {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
10741#endif
10742#ifdef _PC_REC_MIN_XFER_SIZE
10743 {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
10744#endif
10745#ifdef _PC_REC_XFER_ALIGN
10746 {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
10747#endif
10748#ifdef _PC_SYMLINK_MAX
10749 {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
10750#endif
10751#ifdef _PC_XATTR_ENABLED
10752 {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
10753#endif
10754#ifdef _PC_XATTR_EXISTS
10755 {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
10756#endif
10757#ifdef _PC_TIMESTAMP_RESOLUTION
10758 {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
10759#endif
Fred Drakec9680921999-12-13 16:37:25 +000010760};
10761
Fred Drakec9680921999-12-13 16:37:25 +000010762static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010763conv_path_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010764{
10765 return conv_confname(arg, valuep, posix_constants_pathconf,
10766 sizeof(posix_constants_pathconf)
10767 / sizeof(struct constdef));
10768}
10769#endif
10770
Larry Hastings2f936352014-08-05 14:04:04 +100010771
Fred Drakec9680921999-12-13 16:37:25 +000010772#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010773/*[clinic input]
10774os.fpathconf -> long
10775
10776 fd: int
10777 name: path_confname
10778 /
10779
10780Return the configuration limit name for the file descriptor fd.
10781
10782If there is no limit, return -1.
10783[clinic start generated code]*/
10784
Larry Hastings2f936352014-08-05 14:04:04 +100010785static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010786os_fpathconf_impl(PyObject *module, int fd, int name)
10787/*[clinic end generated code: output=d5b7042425fc3e21 input=5942a024d3777810]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010788{
10789 long limit;
10790
10791 errno = 0;
10792 limit = fpathconf(fd, name);
10793 if (limit == -1 && errno != 0)
10794 posix_error();
10795
10796 return limit;
10797}
10798#endif /* HAVE_FPATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010799
10800
10801#ifdef HAVE_PATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010802/*[clinic input]
10803os.pathconf -> long
10804 path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
10805 name: path_confname
10806
10807Return the configuration limit name for the file or directory path.
10808
10809If there is no limit, return -1.
10810On some platforms, path may also be specified as an open file descriptor.
10811 If this functionality is unavailable, using it raises an exception.
10812[clinic start generated code]*/
10813
Larry Hastings2f936352014-08-05 14:04:04 +100010814static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010815os_pathconf_impl(PyObject *module, path_t *path, int name)
10816/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010817{
Victor Stinner8c62be82010-05-06 00:08:46 +000010818 long limit;
Fred Drakec9680921999-12-13 16:37:25 +000010819
Victor Stinner8c62be82010-05-06 00:08:46 +000010820 errno = 0;
Georg Brandl306336b2012-06-24 12:55:33 +020010821#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010822 if (path->fd != -1)
10823 limit = fpathconf(path->fd, name);
Georg Brandl306336b2012-06-24 12:55:33 +020010824 else
10825#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010826 limit = pathconf(path->narrow, name);
Victor Stinner8c62be82010-05-06 00:08:46 +000010827 if (limit == -1 && errno != 0) {
10828 if (errno == EINVAL)
Stefan Krah99439262010-11-26 12:58:05 +000010829 /* could be a path or name problem */
10830 posix_error();
Fred Drakec9680921999-12-13 16:37:25 +000010831 else
Larry Hastings2f936352014-08-05 14:04:04 +100010832 path_error(path);
Victor Stinner8c62be82010-05-06 00:08:46 +000010833 }
Larry Hastings2f936352014-08-05 14:04:04 +100010834
10835 return limit;
Fred Drakec9680921999-12-13 16:37:25 +000010836}
Larry Hastings2f936352014-08-05 14:04:04 +100010837#endif /* HAVE_PATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010838
10839#ifdef HAVE_CONFSTR
10840static struct constdef posix_constants_confstr[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010841#ifdef _CS_ARCHITECTURE
Victor Stinner8c62be82010-05-06 00:08:46 +000010842 {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
Fred Draked86ed291999-12-15 15:34:33 +000010843#endif
Mark Dickinson876d7c82010-04-16 12:47:52 +000010844#ifdef _CS_GNU_LIBC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010845 {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010846#endif
10847#ifdef _CS_GNU_LIBPTHREAD_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010848 {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010849#endif
Fred Draked86ed291999-12-15 15:34:33 +000010850#ifdef _CS_HOSTNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010851 {"CS_HOSTNAME", _CS_HOSTNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010852#endif
10853#ifdef _CS_HW_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010854 {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010855#endif
10856#ifdef _CS_HW_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010857 {"CS_HW_SERIAL", _CS_HW_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010858#endif
10859#ifdef _CS_INITTAB_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010860 {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010861#endif
Fred Drakec9680921999-12-13 16:37:25 +000010862#ifdef _CS_LFS64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010863 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010864#endif
10865#ifdef _CS_LFS64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010866 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010867#endif
10868#ifdef _CS_LFS64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010869 {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010870#endif
10871#ifdef _CS_LFS64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010872 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010873#endif
10874#ifdef _CS_LFS_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010875 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010876#endif
10877#ifdef _CS_LFS_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010878 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010879#endif
10880#ifdef _CS_LFS_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010881 {"CS_LFS_LIBS", _CS_LFS_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010882#endif
10883#ifdef _CS_LFS_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010884 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010885#endif
Fred Draked86ed291999-12-15 15:34:33 +000010886#ifdef _CS_MACHINE
Victor Stinner8c62be82010-05-06 00:08:46 +000010887 {"CS_MACHINE", _CS_MACHINE},
Fred Draked86ed291999-12-15 15:34:33 +000010888#endif
Fred Drakec9680921999-12-13 16:37:25 +000010889#ifdef _CS_PATH
Victor Stinner8c62be82010-05-06 00:08:46 +000010890 {"CS_PATH", _CS_PATH},
Fred Drakec9680921999-12-13 16:37:25 +000010891#endif
Fred Draked86ed291999-12-15 15:34:33 +000010892#ifdef _CS_RELEASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010893 {"CS_RELEASE", _CS_RELEASE},
Fred Draked86ed291999-12-15 15:34:33 +000010894#endif
10895#ifdef _CS_SRPC_DOMAIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010896 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
Fred Draked86ed291999-12-15 15:34:33 +000010897#endif
10898#ifdef _CS_SYSNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010899 {"CS_SYSNAME", _CS_SYSNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010900#endif
10901#ifdef _CS_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010902 {"CS_VERSION", _CS_VERSION},
Fred Draked86ed291999-12-15 15:34:33 +000010903#endif
Fred Drakec9680921999-12-13 16:37:25 +000010904#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010905 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010906#endif
10907#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010908 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010909#endif
10910#ifdef _CS_XBS5_ILP32_OFF32_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010911 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010912#endif
10913#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010914 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010915#endif
10916#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010917 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010918#endif
10919#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010920 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010921#endif
10922#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010923 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010924#endif
10925#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010926 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010927#endif
10928#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010929 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010930#endif
10931#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010932 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010933#endif
10934#ifdef _CS_XBS5_LP64_OFF64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010935 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010936#endif
10937#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010938 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010939#endif
10940#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010941 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010942#endif
10943#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010944 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010945#endif
10946#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010947 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010948#endif
10949#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010950 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010951#endif
Fred Draked86ed291999-12-15 15:34:33 +000010952#ifdef _MIPS_CS_AVAIL_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010953 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010954#endif
10955#ifdef _MIPS_CS_BASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010956 {"MIPS_CS_BASE", _MIPS_CS_BASE},
Fred Draked86ed291999-12-15 15:34:33 +000010957#endif
10958#ifdef _MIPS_CS_HOSTID
Victor Stinner8c62be82010-05-06 00:08:46 +000010959 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
Fred Draked86ed291999-12-15 15:34:33 +000010960#endif
10961#ifdef _MIPS_CS_HW_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010962 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010963#endif
10964#ifdef _MIPS_CS_NUM_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010965 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010966#endif
10967#ifdef _MIPS_CS_OSREL_MAJ
Victor Stinner8c62be82010-05-06 00:08:46 +000010968 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
Fred Draked86ed291999-12-15 15:34:33 +000010969#endif
10970#ifdef _MIPS_CS_OSREL_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010971 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
Fred Draked86ed291999-12-15 15:34:33 +000010972#endif
10973#ifdef _MIPS_CS_OSREL_PATCH
Victor Stinner8c62be82010-05-06 00:08:46 +000010974 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
Fred Draked86ed291999-12-15 15:34:33 +000010975#endif
10976#ifdef _MIPS_CS_OS_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010977 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010978#endif
10979#ifdef _MIPS_CS_OS_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010980 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010981#endif
10982#ifdef _MIPS_CS_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010983 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010984#endif
10985#ifdef _MIPS_CS_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010986 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010987#endif
10988#ifdef _MIPS_CS_VENDOR
Victor Stinner8c62be82010-05-06 00:08:46 +000010989 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
Fred Draked86ed291999-12-15 15:34:33 +000010990#endif
Fred Drakec9680921999-12-13 16:37:25 +000010991};
10992
10993static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010994conv_confstr_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010995{
10996 return conv_confname(arg, valuep, posix_constants_confstr,
10997 sizeof(posix_constants_confstr)
10998 / sizeof(struct constdef));
10999}
11000
Larry Hastings2f936352014-08-05 14:04:04 +100011001
11002/*[clinic input]
11003os.confstr
11004
11005 name: confstr_confname
11006 /
11007
11008Return a string-valued system configuration variable.
11009[clinic start generated code]*/
11010
Larry Hastings2f936352014-08-05 14:04:04 +100011011static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011012os_confstr_impl(PyObject *module, int name)
11013/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
Fred Drakec9680921999-12-13 16:37:25 +000011014{
11015 PyObject *result = NULL;
Victor Stinnercb043522010-09-10 23:49:04 +000011016 char buffer[255];
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011017 size_t len;
Fred Drakec9680921999-12-13 16:37:25 +000011018
Victor Stinnercb043522010-09-10 23:49:04 +000011019 errno = 0;
11020 len = confstr(name, buffer, sizeof(buffer));
11021 if (len == 0) {
11022 if (errno) {
11023 posix_error();
11024 return NULL;
Fred Drakec9680921999-12-13 16:37:25 +000011025 }
11026 else {
Victor Stinnercb043522010-09-10 23:49:04 +000011027 Py_RETURN_NONE;
Fred Drakec9680921999-12-13 16:37:25 +000011028 }
11029 }
Victor Stinnercb043522010-09-10 23:49:04 +000011030
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011031 if (len >= sizeof(buffer)) {
Victor Stinnercbc18f32014-12-05 22:51:51 +010011032 size_t len2;
Victor Stinnercb043522010-09-10 23:49:04 +000011033 char *buf = PyMem_Malloc(len);
11034 if (buf == NULL)
11035 return PyErr_NoMemory();
Victor Stinnercbc18f32014-12-05 22:51:51 +010011036 len2 = confstr(name, buf, len);
11037 assert(len == len2);
Christian Heimes8714cfd2015-04-21 10:57:41 +020011038 result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
Victor Stinnercb043522010-09-10 23:49:04 +000011039 PyMem_Free(buf);
11040 }
11041 else
11042 result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
Fred Drakec9680921999-12-13 16:37:25 +000011043 return result;
11044}
Larry Hastings2f936352014-08-05 14:04:04 +100011045#endif /* HAVE_CONFSTR */
Fred Drakec9680921999-12-13 16:37:25 +000011046
11047
11048#ifdef HAVE_SYSCONF
11049static struct constdef posix_constants_sysconf[] = {
11050#ifdef _SC_2_CHAR_TERM
Victor Stinner8c62be82010-05-06 00:08:46 +000011051 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
Fred Drakec9680921999-12-13 16:37:25 +000011052#endif
11053#ifdef _SC_2_C_BIND
Victor Stinner8c62be82010-05-06 00:08:46 +000011054 {"SC_2_C_BIND", _SC_2_C_BIND},
Fred Drakec9680921999-12-13 16:37:25 +000011055#endif
11056#ifdef _SC_2_C_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011057 {"SC_2_C_DEV", _SC_2_C_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011058#endif
11059#ifdef _SC_2_C_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011060 {"SC_2_C_VERSION", _SC_2_C_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011061#endif
11062#ifdef _SC_2_FORT_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011063 {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011064#endif
11065#ifdef _SC_2_FORT_RUN
Victor Stinner8c62be82010-05-06 00:08:46 +000011066 {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
Fred Drakec9680921999-12-13 16:37:25 +000011067#endif
11068#ifdef _SC_2_LOCALEDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000011069 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
Fred Drakec9680921999-12-13 16:37:25 +000011070#endif
11071#ifdef _SC_2_SW_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011072 {"SC_2_SW_DEV", _SC_2_SW_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011073#endif
11074#ifdef _SC_2_UPE
Victor Stinner8c62be82010-05-06 00:08:46 +000011075 {"SC_2_UPE", _SC_2_UPE},
Fred Drakec9680921999-12-13 16:37:25 +000011076#endif
11077#ifdef _SC_2_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011078 {"SC_2_VERSION", _SC_2_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011079#endif
Fred Draked86ed291999-12-15 15:34:33 +000011080#ifdef _SC_ABI_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011081 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
Fred Draked86ed291999-12-15 15:34:33 +000011082#endif
11083#ifdef _SC_ACL
Victor Stinner8c62be82010-05-06 00:08:46 +000011084 {"SC_ACL", _SC_ACL},
Fred Draked86ed291999-12-15 15:34:33 +000011085#endif
Fred Drakec9680921999-12-13 16:37:25 +000011086#ifdef _SC_AIO_LISTIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011087 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011088#endif
Fred Drakec9680921999-12-13 16:37:25 +000011089#ifdef _SC_AIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011090 {"SC_AIO_MAX", _SC_AIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011091#endif
11092#ifdef _SC_AIO_PRIO_DELTA_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011093 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011094#endif
11095#ifdef _SC_ARG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011096 {"SC_ARG_MAX", _SC_ARG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011097#endif
11098#ifdef _SC_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011099 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011100#endif
11101#ifdef _SC_ATEXIT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011102 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011103#endif
Fred Draked86ed291999-12-15 15:34:33 +000011104#ifdef _SC_AUDIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011105 {"SC_AUDIT", _SC_AUDIT},
Fred Draked86ed291999-12-15 15:34:33 +000011106#endif
Fred Drakec9680921999-12-13 16:37:25 +000011107#ifdef _SC_AVPHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011108 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011109#endif
11110#ifdef _SC_BC_BASE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011111 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011112#endif
11113#ifdef _SC_BC_DIM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011114 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011115#endif
11116#ifdef _SC_BC_SCALE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011117 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011118#endif
11119#ifdef _SC_BC_STRING_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011120 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011121#endif
Fred Draked86ed291999-12-15 15:34:33 +000011122#ifdef _SC_CAP
Victor Stinner8c62be82010-05-06 00:08:46 +000011123 {"SC_CAP", _SC_CAP},
Fred Draked86ed291999-12-15 15:34:33 +000011124#endif
Fred Drakec9680921999-12-13 16:37:25 +000011125#ifdef _SC_CHARCLASS_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011126 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011127#endif
11128#ifdef _SC_CHAR_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011129 {"SC_CHAR_BIT", _SC_CHAR_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011130#endif
11131#ifdef _SC_CHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011132 {"SC_CHAR_MAX", _SC_CHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011133#endif
11134#ifdef _SC_CHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011135 {"SC_CHAR_MIN", _SC_CHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011136#endif
11137#ifdef _SC_CHILD_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011138 {"SC_CHILD_MAX", _SC_CHILD_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011139#endif
11140#ifdef _SC_CLK_TCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011141 {"SC_CLK_TCK", _SC_CLK_TCK},
Fred Drakec9680921999-12-13 16:37:25 +000011142#endif
11143#ifdef _SC_COHER_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011144 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011145#endif
11146#ifdef _SC_COLL_WEIGHTS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011147 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011148#endif
11149#ifdef _SC_DCACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011150 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011151#endif
11152#ifdef _SC_DCACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011153 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011154#endif
11155#ifdef _SC_DCACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011156 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011157#endif
11158#ifdef _SC_DCACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011159 {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011160#endif
11161#ifdef _SC_DCACHE_TBLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011162 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011163#endif
11164#ifdef _SC_DELAYTIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011165 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011166#endif
11167#ifdef _SC_EQUIV_CLASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011168 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011169#endif
11170#ifdef _SC_EXPR_NEST_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011171 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011172#endif
11173#ifdef _SC_FSYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000011174 {"SC_FSYNC", _SC_FSYNC},
Fred Drakec9680921999-12-13 16:37:25 +000011175#endif
11176#ifdef _SC_GETGR_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011177 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011178#endif
11179#ifdef _SC_GETPW_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011180 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011181#endif
11182#ifdef _SC_ICACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011183 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011184#endif
11185#ifdef _SC_ICACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011186 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011187#endif
11188#ifdef _SC_ICACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011189 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011190#endif
11191#ifdef _SC_ICACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011192 {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011193#endif
Fred Draked86ed291999-12-15 15:34:33 +000011194#ifdef _SC_INF
Victor Stinner8c62be82010-05-06 00:08:46 +000011195 {"SC_INF", _SC_INF},
Fred Draked86ed291999-12-15 15:34:33 +000011196#endif
Fred Drakec9680921999-12-13 16:37:25 +000011197#ifdef _SC_INT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011198 {"SC_INT_MAX", _SC_INT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011199#endif
11200#ifdef _SC_INT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011201 {"SC_INT_MIN", _SC_INT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011202#endif
11203#ifdef _SC_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011204 {"SC_IOV_MAX", _SC_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011205#endif
Fred Draked86ed291999-12-15 15:34:33 +000011206#ifdef _SC_IP_SECOPTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011207 {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
Fred Draked86ed291999-12-15 15:34:33 +000011208#endif
Fred Drakec9680921999-12-13 16:37:25 +000011209#ifdef _SC_JOB_CONTROL
Victor Stinner8c62be82010-05-06 00:08:46 +000011210 {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
Fred Drakec9680921999-12-13 16:37:25 +000011211#endif
Fred Draked86ed291999-12-15 15:34:33 +000011212#ifdef _SC_KERN_POINTERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011213 {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
Fred Draked86ed291999-12-15 15:34:33 +000011214#endif
11215#ifdef _SC_KERN_SIM
Victor Stinner8c62be82010-05-06 00:08:46 +000011216 {"SC_KERN_SIM", _SC_KERN_SIM},
Fred Draked86ed291999-12-15 15:34:33 +000011217#endif
Fred Drakec9680921999-12-13 16:37:25 +000011218#ifdef _SC_LINE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011219 {"SC_LINE_MAX", _SC_LINE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011220#endif
11221#ifdef _SC_LOGIN_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011222 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011223#endif
11224#ifdef _SC_LOGNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011225 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011226#endif
11227#ifdef _SC_LONG_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011228 {"SC_LONG_BIT", _SC_LONG_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011229#endif
Fred Draked86ed291999-12-15 15:34:33 +000011230#ifdef _SC_MAC
Victor Stinner8c62be82010-05-06 00:08:46 +000011231 {"SC_MAC", _SC_MAC},
Fred Draked86ed291999-12-15 15:34:33 +000011232#endif
Fred Drakec9680921999-12-13 16:37:25 +000011233#ifdef _SC_MAPPED_FILES
Victor Stinner8c62be82010-05-06 00:08:46 +000011234 {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
Fred Drakec9680921999-12-13 16:37:25 +000011235#endif
11236#ifdef _SC_MAXPID
Victor Stinner8c62be82010-05-06 00:08:46 +000011237 {"SC_MAXPID", _SC_MAXPID},
Fred Drakec9680921999-12-13 16:37:25 +000011238#endif
11239#ifdef _SC_MB_LEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011240 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011241#endif
11242#ifdef _SC_MEMLOCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011243 {"SC_MEMLOCK", _SC_MEMLOCK},
Fred Drakec9680921999-12-13 16:37:25 +000011244#endif
11245#ifdef _SC_MEMLOCK_RANGE
Victor Stinner8c62be82010-05-06 00:08:46 +000011246 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
Fred Drakec9680921999-12-13 16:37:25 +000011247#endif
11248#ifdef _SC_MEMORY_PROTECTION
Victor Stinner8c62be82010-05-06 00:08:46 +000011249 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
Fred Drakec9680921999-12-13 16:37:25 +000011250#endif
11251#ifdef _SC_MESSAGE_PASSING
Victor Stinner8c62be82010-05-06 00:08:46 +000011252 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
Fred Drakec9680921999-12-13 16:37:25 +000011253#endif
Fred Draked86ed291999-12-15 15:34:33 +000011254#ifdef _SC_MMAP_FIXED_ALIGNMENT
Victor Stinner8c62be82010-05-06 00:08:46 +000011255 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
Fred Draked86ed291999-12-15 15:34:33 +000011256#endif
Fred Drakec9680921999-12-13 16:37:25 +000011257#ifdef _SC_MQ_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011258 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011259#endif
11260#ifdef _SC_MQ_PRIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011261 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011262#endif
Fred Draked86ed291999-12-15 15:34:33 +000011263#ifdef _SC_NACLS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011264 {"SC_NACLS_MAX", _SC_NACLS_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000011265#endif
Fred Drakec9680921999-12-13 16:37:25 +000011266#ifdef _SC_NGROUPS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011267 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011268#endif
11269#ifdef _SC_NL_ARGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011270 {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011271#endif
11272#ifdef _SC_NL_LANGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011273 {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011274#endif
11275#ifdef _SC_NL_MSGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011276 {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011277#endif
11278#ifdef _SC_NL_NMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011279 {"SC_NL_NMAX", _SC_NL_NMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011280#endif
11281#ifdef _SC_NL_SETMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011282 {"SC_NL_SETMAX", _SC_NL_SETMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011283#endif
11284#ifdef _SC_NL_TEXTMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011285 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011286#endif
11287#ifdef _SC_NPROCESSORS_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011288 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
Fred Drakec9680921999-12-13 16:37:25 +000011289#endif
11290#ifdef _SC_NPROCESSORS_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011291 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
Fred Drakec9680921999-12-13 16:37:25 +000011292#endif
Fred Draked86ed291999-12-15 15:34:33 +000011293#ifdef _SC_NPROC_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011294 {"SC_NPROC_CONF", _SC_NPROC_CONF},
Fred Draked86ed291999-12-15 15:34:33 +000011295#endif
11296#ifdef _SC_NPROC_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011297 {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
Fred Draked86ed291999-12-15 15:34:33 +000011298#endif
Fred Drakec9680921999-12-13 16:37:25 +000011299#ifdef _SC_NZERO
Victor Stinner8c62be82010-05-06 00:08:46 +000011300 {"SC_NZERO", _SC_NZERO},
Fred Drakec9680921999-12-13 16:37:25 +000011301#endif
11302#ifdef _SC_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011303 {"SC_OPEN_MAX", _SC_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011304#endif
11305#ifdef _SC_PAGESIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011306 {"SC_PAGESIZE", _SC_PAGESIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011307#endif
11308#ifdef _SC_PAGE_SIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011309 {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011310#endif
11311#ifdef _SC_PASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011312 {"SC_PASS_MAX", _SC_PASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011313#endif
11314#ifdef _SC_PHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011315 {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011316#endif
11317#ifdef _SC_PII
Victor Stinner8c62be82010-05-06 00:08:46 +000011318 {"SC_PII", _SC_PII},
Fred Drakec9680921999-12-13 16:37:25 +000011319#endif
11320#ifdef _SC_PII_INTERNET
Victor Stinner8c62be82010-05-06 00:08:46 +000011321 {"SC_PII_INTERNET", _SC_PII_INTERNET},
Fred Drakec9680921999-12-13 16:37:25 +000011322#endif
11323#ifdef _SC_PII_INTERNET_DGRAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011324 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
Fred Drakec9680921999-12-13 16:37:25 +000011325#endif
11326#ifdef _SC_PII_INTERNET_STREAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011327 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
Fred Drakec9680921999-12-13 16:37:25 +000011328#endif
11329#ifdef _SC_PII_OSI
Victor Stinner8c62be82010-05-06 00:08:46 +000011330 {"SC_PII_OSI", _SC_PII_OSI},
Fred Drakec9680921999-12-13 16:37:25 +000011331#endif
11332#ifdef _SC_PII_OSI_CLTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011333 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
Fred Drakec9680921999-12-13 16:37:25 +000011334#endif
11335#ifdef _SC_PII_OSI_COTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011336 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
Fred Drakec9680921999-12-13 16:37:25 +000011337#endif
11338#ifdef _SC_PII_OSI_M
Victor Stinner8c62be82010-05-06 00:08:46 +000011339 {"SC_PII_OSI_M", _SC_PII_OSI_M},
Fred Drakec9680921999-12-13 16:37:25 +000011340#endif
11341#ifdef _SC_PII_SOCKET
Victor Stinner8c62be82010-05-06 00:08:46 +000011342 {"SC_PII_SOCKET", _SC_PII_SOCKET},
Fred Drakec9680921999-12-13 16:37:25 +000011343#endif
11344#ifdef _SC_PII_XTI
Victor Stinner8c62be82010-05-06 00:08:46 +000011345 {"SC_PII_XTI", _SC_PII_XTI},
Fred Drakec9680921999-12-13 16:37:25 +000011346#endif
11347#ifdef _SC_POLL
Victor Stinner8c62be82010-05-06 00:08:46 +000011348 {"SC_POLL", _SC_POLL},
Fred Drakec9680921999-12-13 16:37:25 +000011349#endif
11350#ifdef _SC_PRIORITIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011351 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011352#endif
11353#ifdef _SC_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011354 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011355#endif
11356#ifdef _SC_REALTIME_SIGNALS
Victor Stinner8c62be82010-05-06 00:08:46 +000011357 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
Fred Drakec9680921999-12-13 16:37:25 +000011358#endif
11359#ifdef _SC_RE_DUP_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011360 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011361#endif
11362#ifdef _SC_RTSIG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011363 {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011364#endif
11365#ifdef _SC_SAVED_IDS
Victor Stinner8c62be82010-05-06 00:08:46 +000011366 {"SC_SAVED_IDS", _SC_SAVED_IDS},
Fred Drakec9680921999-12-13 16:37:25 +000011367#endif
11368#ifdef _SC_SCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011369 {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011370#endif
11371#ifdef _SC_SCHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011372 {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011373#endif
11374#ifdef _SC_SELECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011375 {"SC_SELECT", _SC_SELECT},
Fred Drakec9680921999-12-13 16:37:25 +000011376#endif
11377#ifdef _SC_SEMAPHORES
Victor Stinner8c62be82010-05-06 00:08:46 +000011378 {"SC_SEMAPHORES", _SC_SEMAPHORES},
Fred Drakec9680921999-12-13 16:37:25 +000011379#endif
11380#ifdef _SC_SEM_NSEMS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011381 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011382#endif
11383#ifdef _SC_SEM_VALUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011384 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011385#endif
11386#ifdef _SC_SHARED_MEMORY_OBJECTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011387 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
Fred Drakec9680921999-12-13 16:37:25 +000011388#endif
11389#ifdef _SC_SHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011390 {"SC_SHRT_MAX", _SC_SHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011391#endif
11392#ifdef _SC_SHRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011393 {"SC_SHRT_MIN", _SC_SHRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011394#endif
11395#ifdef _SC_SIGQUEUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011396 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011397#endif
11398#ifdef _SC_SIGRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011399 {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011400#endif
11401#ifdef _SC_SIGRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011402 {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011403#endif
Fred Draked86ed291999-12-15 15:34:33 +000011404#ifdef _SC_SOFTPOWER
Victor Stinner8c62be82010-05-06 00:08:46 +000011405 {"SC_SOFTPOWER", _SC_SOFTPOWER},
Fred Draked86ed291999-12-15 15:34:33 +000011406#endif
Fred Drakec9680921999-12-13 16:37:25 +000011407#ifdef _SC_SPLIT_CACHE
Victor Stinner8c62be82010-05-06 00:08:46 +000011408 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
Fred Drakec9680921999-12-13 16:37:25 +000011409#endif
11410#ifdef _SC_SSIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011411 {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011412#endif
11413#ifdef _SC_STACK_PROT
Victor Stinner8c62be82010-05-06 00:08:46 +000011414 {"SC_STACK_PROT", _SC_STACK_PROT},
Fred Drakec9680921999-12-13 16:37:25 +000011415#endif
11416#ifdef _SC_STREAM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011417 {"SC_STREAM_MAX", _SC_STREAM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011418#endif
11419#ifdef _SC_SYNCHRONIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011420 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011421#endif
11422#ifdef _SC_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011423 {"SC_THREADS", _SC_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011424#endif
11425#ifdef _SC_THREAD_ATTR_STACKADDR
Victor Stinner8c62be82010-05-06 00:08:46 +000011426 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
Fred Drakec9680921999-12-13 16:37:25 +000011427#endif
11428#ifdef _SC_THREAD_ATTR_STACKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011429 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011430#endif
11431#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011432 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011433#endif
11434#ifdef _SC_THREAD_KEYS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011435 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011436#endif
11437#ifdef _SC_THREAD_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011438 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011439#endif
11440#ifdef _SC_THREAD_PRIO_INHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011441 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
Fred Drakec9680921999-12-13 16:37:25 +000011442#endif
11443#ifdef _SC_THREAD_PRIO_PROTECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011444 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
Fred Drakec9680921999-12-13 16:37:25 +000011445#endif
11446#ifdef _SC_THREAD_PROCESS_SHARED
Victor Stinner8c62be82010-05-06 00:08:46 +000011447 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
Fred Drakec9680921999-12-13 16:37:25 +000011448#endif
11449#ifdef _SC_THREAD_SAFE_FUNCTIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011450 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011451#endif
11452#ifdef _SC_THREAD_STACK_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011453 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011454#endif
11455#ifdef _SC_THREAD_THREADS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011456 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011457#endif
11458#ifdef _SC_TIMERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011459 {"SC_TIMERS", _SC_TIMERS},
Fred Drakec9680921999-12-13 16:37:25 +000011460#endif
11461#ifdef _SC_TIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011462 {"SC_TIMER_MAX", _SC_TIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011463#endif
11464#ifdef _SC_TTY_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011465 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011466#endif
11467#ifdef _SC_TZNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011468 {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011469#endif
11470#ifdef _SC_T_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011471 {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011472#endif
11473#ifdef _SC_UCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011474 {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011475#endif
11476#ifdef _SC_UINT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011477 {"SC_UINT_MAX", _SC_UINT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011478#endif
11479#ifdef _SC_UIO_MAXIOV
Victor Stinner8c62be82010-05-06 00:08:46 +000011480 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
Fred Drakec9680921999-12-13 16:37:25 +000011481#endif
11482#ifdef _SC_ULONG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011483 {"SC_ULONG_MAX", _SC_ULONG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011484#endif
11485#ifdef _SC_USHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011486 {"SC_USHRT_MAX", _SC_USHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011487#endif
11488#ifdef _SC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011489 {"SC_VERSION", _SC_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011490#endif
11491#ifdef _SC_WORD_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011492 {"SC_WORD_BIT", _SC_WORD_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011493#endif
11494#ifdef _SC_XBS5_ILP32_OFF32
Victor Stinner8c62be82010-05-06 00:08:46 +000011495 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
Fred Drakec9680921999-12-13 16:37:25 +000011496#endif
11497#ifdef _SC_XBS5_ILP32_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011498 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011499#endif
11500#ifdef _SC_XBS5_LP64_OFF64
Victor Stinner8c62be82010-05-06 00:08:46 +000011501 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
Fred Drakec9680921999-12-13 16:37:25 +000011502#endif
11503#ifdef _SC_XBS5_LPBIG_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011504 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011505#endif
11506#ifdef _SC_XOPEN_CRYPT
Victor Stinner8c62be82010-05-06 00:08:46 +000011507 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
Fred Drakec9680921999-12-13 16:37:25 +000011508#endif
11509#ifdef _SC_XOPEN_ENH_I18N
Victor Stinner8c62be82010-05-06 00:08:46 +000011510 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
Fred Drakec9680921999-12-13 16:37:25 +000011511#endif
11512#ifdef _SC_XOPEN_LEGACY
Victor Stinner8c62be82010-05-06 00:08:46 +000011513 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
Fred Drakec9680921999-12-13 16:37:25 +000011514#endif
11515#ifdef _SC_XOPEN_REALTIME
Victor Stinner8c62be82010-05-06 00:08:46 +000011516 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
Fred Drakec9680921999-12-13 16:37:25 +000011517#endif
11518#ifdef _SC_XOPEN_REALTIME_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011519 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011520#endif
11521#ifdef _SC_XOPEN_SHM
Victor Stinner8c62be82010-05-06 00:08:46 +000011522 {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
Fred Drakec9680921999-12-13 16:37:25 +000011523#endif
11524#ifdef _SC_XOPEN_UNIX
Victor Stinner8c62be82010-05-06 00:08:46 +000011525 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
Fred Drakec9680921999-12-13 16:37:25 +000011526#endif
11527#ifdef _SC_XOPEN_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011528 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011529#endif
11530#ifdef _SC_XOPEN_XCU_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011531 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011532#endif
11533#ifdef _SC_XOPEN_XPG2
Victor Stinner8c62be82010-05-06 00:08:46 +000011534 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
Fred Drakec9680921999-12-13 16:37:25 +000011535#endif
11536#ifdef _SC_XOPEN_XPG3
Victor Stinner8c62be82010-05-06 00:08:46 +000011537 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
Fred Drakec9680921999-12-13 16:37:25 +000011538#endif
11539#ifdef _SC_XOPEN_XPG4
Victor Stinner8c62be82010-05-06 00:08:46 +000011540 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
Fred Drakec9680921999-12-13 16:37:25 +000011541#endif
11542};
11543
11544static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011545conv_sysconf_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011546{
11547 return conv_confname(arg, valuep, posix_constants_sysconf,
11548 sizeof(posix_constants_sysconf)
11549 / sizeof(struct constdef));
11550}
11551
Larry Hastings2f936352014-08-05 14:04:04 +100011552
11553/*[clinic input]
11554os.sysconf -> long
11555 name: sysconf_confname
11556 /
11557
11558Return an integer-valued system configuration variable.
11559[clinic start generated code]*/
11560
Larry Hastings2f936352014-08-05 14:04:04 +100011561static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011562os_sysconf_impl(PyObject *module, int name)
11563/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011564{
11565 long value;
11566
11567 errno = 0;
11568 value = sysconf(name);
11569 if (value == -1 && errno != 0)
11570 posix_error();
11571 return value;
11572}
11573#endif /* HAVE_SYSCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011574
11575
Fred Drakebec628d1999-12-15 18:31:10 +000011576/* This code is used to ensure that the tables of configuration value names
Serhiy Storchaka56a6d852014-12-01 18:28:43 +020011577 * are in sorted order as required by conv_confname(), and also to build
Fred Drakebec628d1999-12-15 18:31:10 +000011578 * the exported dictionaries that are used to publish information about the
11579 * names available on the host platform.
11580 *
11581 * Sorting the table at runtime ensures that the table is properly ordered
11582 * when used, even for platforms we're not able to test on. It also makes
11583 * it easier to add additional entries to the tables.
Fred Draked86ed291999-12-15 15:34:33 +000011584 */
Fred Drakebec628d1999-12-15 18:31:10 +000011585
11586static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011587cmp_constdefs(const void *v1, const void *v2)
Fred Drakebec628d1999-12-15 18:31:10 +000011588{
11589 const struct constdef *c1 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011590 (const struct constdef *) v1;
Fred Drakebec628d1999-12-15 18:31:10 +000011591 const struct constdef *c2 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011592 (const struct constdef *) v2;
Fred Drakebec628d1999-12-15 18:31:10 +000011593
11594 return strcmp(c1->name, c2->name);
11595}
11596
11597static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011598setup_confname_table(struct constdef *table, size_t tablesize,
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011599 const char *tablename, PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011600{
Fred Drakebec628d1999-12-15 18:31:10 +000011601 PyObject *d = NULL;
Barry Warsaw3155db32000-04-13 15:20:40 +000011602 size_t i;
Fred Drakebec628d1999-12-15 18:31:10 +000011603
11604 qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
11605 d = PyDict_New();
Barry Warsaw3155db32000-04-13 15:20:40 +000011606 if (d == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +000011607 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011608
Barry Warsaw3155db32000-04-13 15:20:40 +000011609 for (i=0; i < tablesize; ++i) {
Victor Stinner8c62be82010-05-06 00:08:46 +000011610 PyObject *o = PyLong_FromLong(table[i].value);
11611 if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
11612 Py_XDECREF(o);
11613 Py_DECREF(d);
11614 return -1;
11615 }
11616 Py_DECREF(o);
Fred Draked86ed291999-12-15 15:34:33 +000011617 }
Fred Drake4d1e64b2002-04-15 19:40:07 +000011618 return PyModule_AddObject(module, tablename, d);
Fred Draked86ed291999-12-15 15:34:33 +000011619}
11620
Fred Drakebec628d1999-12-15 18:31:10 +000011621/* Return -1 on failure, 0 on success. */
11622static int
Fred Drake4d1e64b2002-04-15 19:40:07 +000011623setup_confname_tables(PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011624{
11625#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
Fred Drakebec628d1999-12-15 18:31:10 +000011626 if (setup_confname_table(posix_constants_pathconf,
Fred Draked86ed291999-12-15 15:34:33 +000011627 sizeof(posix_constants_pathconf)
11628 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011629 "pathconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011630 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011631#endif
11632#ifdef HAVE_CONFSTR
Fred Drakebec628d1999-12-15 18:31:10 +000011633 if (setup_confname_table(posix_constants_confstr,
Fred Draked86ed291999-12-15 15:34:33 +000011634 sizeof(posix_constants_confstr)
11635 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011636 "confstr_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011637 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011638#endif
11639#ifdef HAVE_SYSCONF
Fred Drakebec628d1999-12-15 18:31:10 +000011640 if (setup_confname_table(posix_constants_sysconf,
Fred Draked86ed291999-12-15 15:34:33 +000011641 sizeof(posix_constants_sysconf)
11642 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011643 "sysconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011644 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011645#endif
Fred Drakebec628d1999-12-15 18:31:10 +000011646 return 0;
Fred Draked86ed291999-12-15 15:34:33 +000011647}
Fred Draked86ed291999-12-15 15:34:33 +000011648
11649
Larry Hastings2f936352014-08-05 14:04:04 +100011650/*[clinic input]
11651os.abort
11652
11653Abort the interpreter immediately.
11654
11655This function 'dumps core' or otherwise fails in the hardest way possible
11656on the hosting operating system. This function never returns.
11657[clinic start generated code]*/
11658
Larry Hastings2f936352014-08-05 14:04:04 +100011659static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011660os_abort_impl(PyObject *module)
11661/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011662{
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011663 abort();
11664 /*NOTREACHED*/
Victor Stinner9a2329f2016-12-05 17:56:36 +010011665#ifndef __clang__
11666 /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
11667 GCC emits a warning without "return NULL;" (compiler bug?), but Clang
11668 is smarter and emits a warning on the return. */
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011669 Py_FatalError("abort() called from Python code didn't abort!");
11670 return NULL;
Victor Stinner9a2329f2016-12-05 17:56:36 +010011671#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011672}
Fred Drakebec628d1999-12-15 18:31:10 +000011673
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011674#ifdef MS_WINDOWS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011675/* Grab ShellExecute dynamically from shell32 */
11676static int has_ShellExecute = -1;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011677static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
11678 LPCWSTR, INT);
11679static int
11680check_ShellExecute()
11681{
11682 HINSTANCE hShell32;
11683
11684 /* only recheck */
11685 if (-1 == has_ShellExecute) {
11686 Py_BEGIN_ALLOW_THREADS
Victor Stinnera9912152017-10-13 13:46:57 -070011687 /* Security note: this call is not vulnerable to "DLL hijacking".
11688 SHELL32 is part of "KnownDLLs" and so Windows always load
11689 the system SHELL32.DLL, even if there is another SHELL32.DLL
11690 in the DLL search path. */
Steve Dower7d0e0c92015-01-24 08:18:24 -080011691 hShell32 = LoadLibraryW(L"SHELL32");
Steve Dower7d0e0c92015-01-24 08:18:24 -080011692 if (hShell32) {
Steve Dower7d0e0c92015-01-24 08:18:24 -080011693 *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
11694 "ShellExecuteW");
Steve Dowercc16be82016-09-08 10:35:16 -070011695 has_ShellExecute = Py_ShellExecuteW != NULL;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011696 } else {
11697 has_ShellExecute = 0;
11698 }
Tony Roberts4860f012019-02-02 18:16:42 +010011699 Py_END_ALLOW_THREADS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011700 }
11701 return has_ShellExecute;
11702}
11703
11704
Steve Dowercc16be82016-09-08 10:35:16 -070011705/*[clinic input]
11706os.startfile
11707 filepath: path_t
11708 operation: Py_UNICODE = NULL
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +000011709
Steve Dowercc16be82016-09-08 10:35:16 -070011710Start a file with its associated application.
11711
11712When "operation" is not specified or "open", this acts like
11713double-clicking the file in Explorer, or giving the file name as an
11714argument to the DOS "start" command: the file is opened with whatever
11715application (if any) its extension is associated.
11716When another "operation" is given, it specifies what should be done with
11717the file. A typical operation is "print".
11718
11719startfile returns as soon as the associated application is launched.
11720There is no option to wait for the application to close, and no way
11721to retrieve the application's exit status.
11722
11723The filepath is relative to the current directory. If you want to use
11724an absolute path, make sure the first character is not a slash ("/");
11725the underlying Win32 ShellExecute function doesn't work if it is.
11726[clinic start generated code]*/
11727
11728static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +020011729os_startfile_impl(PyObject *module, path_t *filepath,
11730 const Py_UNICODE *operation)
Serhiy Storchaka279f4462019-09-14 12:24:05 +030011731/*[clinic end generated code: output=66dc311c94d50797 input=c940888a5390f039]*/
Steve Dowercc16be82016-09-08 10:35:16 -070011732{
11733 HINSTANCE rc;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011734
11735 if(!check_ShellExecute()) {
11736 /* If the OS doesn't have ShellExecute, return a
11737 NotImplementedError. */
11738 return PyErr_Format(PyExc_NotImplementedError,
11739 "startfile not available on this platform");
11740 }
11741
Victor Stinner8c62be82010-05-06 00:08:46 +000011742 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -070011743 rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
Steve Dower7d0e0c92015-01-24 08:18:24 -080011744 NULL, NULL, SW_SHOWNORMAL);
Victor Stinner8c62be82010-05-06 00:08:46 +000011745 Py_END_ALLOW_THREADS
11746
Victor Stinner8c62be82010-05-06 00:08:46 +000011747 if (rc <= (HINSTANCE)32) {
Steve Dowercc16be82016-09-08 10:35:16 -070011748 win32_error_object("startfile", filepath->object);
Victor Stinnereb5657a2011-09-30 01:44:27 +020011749 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000011750 }
Steve Dowercc16be82016-09-08 10:35:16 -070011751 Py_RETURN_NONE;
Tim Petersf58a7aa2000-09-22 10:05:54 +000011752}
Larry Hastings2f936352014-08-05 14:04:04 +100011753#endif /* MS_WINDOWS */
11754
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011755
Martin v. Löwis438b5342002-12-27 10:16:42 +000011756#ifdef HAVE_GETLOADAVG
Larry Hastings2f936352014-08-05 14:04:04 +100011757/*[clinic input]
11758os.getloadavg
11759
11760Return average recent system load information.
11761
11762Return the number of processes in the system run queue averaged over
11763the last 1, 5, and 15 minutes as a tuple of three floats.
11764Raises OSError if the load average was unobtainable.
11765[clinic start generated code]*/
11766
Larry Hastings2f936352014-08-05 14:04:04 +100011767static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011768os_getloadavg_impl(PyObject *module)
11769/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
Martin v. Löwis438b5342002-12-27 10:16:42 +000011770{
11771 double loadavg[3];
Martin v. Löwis438b5342002-12-27 10:16:42 +000011772 if (getloadavg(loadavg, 3)!=3) {
Stefan Krah0e803b32010-11-26 16:16:47 +000011773 PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
11774 return NULL;
Martin v. Löwis438b5342002-12-27 10:16:42 +000011775 } else
Stefan Krah0e803b32010-11-26 16:16:47 +000011776 return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
Martin v. Löwis438b5342002-12-27 10:16:42 +000011777}
Larry Hastings2f936352014-08-05 14:04:04 +100011778#endif /* HAVE_GETLOADAVG */
Martin v. Löwis438b5342002-12-27 10:16:42 +000011779
Larry Hastings2f936352014-08-05 14:04:04 +100011780
11781/*[clinic input]
11782os.device_encoding
11783 fd: int
11784
11785Return a string describing the encoding of a terminal's file descriptor.
11786
11787The file descriptor must be attached to a terminal.
11788If the device is not a terminal, return None.
11789[clinic start generated code]*/
11790
Larry Hastings2f936352014-08-05 14:04:04 +100011791static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011792os_device_encoding_impl(PyObject *module, int fd)
11793/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011794{
Brett Cannonefb00c02012-02-29 18:31:31 -050011795 return _Py_device_encoding(fd);
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +000011796}
11797
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011798
Larry Hastings2f936352014-08-05 14:04:04 +100011799#ifdef HAVE_SETRESUID
11800/*[clinic input]
11801os.setresuid
11802
11803 ruid: uid_t
11804 euid: uid_t
11805 suid: uid_t
11806 /
11807
11808Set the current process's real, effective, and saved user ids.
11809[clinic start generated code]*/
11810
Larry Hastings2f936352014-08-05 14:04:04 +100011811static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011812os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
11813/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011814{
Victor Stinner8c62be82010-05-06 00:08:46 +000011815 if (setresuid(ruid, euid, suid) < 0)
11816 return posix_error();
11817 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011818}
Larry Hastings2f936352014-08-05 14:04:04 +100011819#endif /* HAVE_SETRESUID */
11820
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011821
11822#ifdef HAVE_SETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011823/*[clinic input]
11824os.setresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011825
Larry Hastings2f936352014-08-05 14:04:04 +100011826 rgid: gid_t
11827 egid: gid_t
11828 sgid: gid_t
11829 /
11830
11831Set the current process's real, effective, and saved group ids.
11832[clinic start generated code]*/
11833
Larry Hastings2f936352014-08-05 14:04:04 +100011834static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011835os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
11836/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011837{
Victor Stinner8c62be82010-05-06 00:08:46 +000011838 if (setresgid(rgid, egid, sgid) < 0)
11839 return posix_error();
11840 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011841}
Larry Hastings2f936352014-08-05 14:04:04 +100011842#endif /* HAVE_SETRESGID */
11843
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011844
11845#ifdef HAVE_GETRESUID
Larry Hastings2f936352014-08-05 14:04:04 +100011846/*[clinic input]
11847os.getresuid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011848
Larry Hastings2f936352014-08-05 14:04:04 +100011849Return a tuple of the current process's real, effective, and saved user ids.
11850[clinic start generated code]*/
11851
Larry Hastings2f936352014-08-05 14:04:04 +100011852static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011853os_getresuid_impl(PyObject *module)
11854/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011855{
Victor Stinner8c62be82010-05-06 00:08:46 +000011856 uid_t ruid, euid, suid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011857 if (getresuid(&ruid, &euid, &suid) < 0)
11858 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011859 return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
11860 _PyLong_FromUid(euid),
11861 _PyLong_FromUid(suid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011862}
Larry Hastings2f936352014-08-05 14:04:04 +100011863#endif /* HAVE_GETRESUID */
11864
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011865
11866#ifdef HAVE_GETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011867/*[clinic input]
11868os.getresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011869
Larry Hastings2f936352014-08-05 14:04:04 +100011870Return a tuple of the current process's real, effective, and saved group ids.
11871[clinic start generated code]*/
11872
Larry Hastings2f936352014-08-05 14:04:04 +100011873static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011874os_getresgid_impl(PyObject *module)
11875/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011876{
11877 gid_t rgid, egid, sgid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011878 if (getresgid(&rgid, &egid, &sgid) < 0)
11879 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011880 return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
11881 _PyLong_FromGid(egid),
11882 _PyLong_FromGid(sgid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011883}
Larry Hastings2f936352014-08-05 14:04:04 +100011884#endif /* HAVE_GETRESGID */
11885
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011886
Benjamin Peterson9428d532011-09-14 11:45:52 -040011887#ifdef USE_XATTRS
Larry Hastings2f936352014-08-05 14:04:04 +100011888/*[clinic input]
11889os.getxattr
Benjamin Peterson799bd802011-08-31 22:15:17 -040011890
Larry Hastings2f936352014-08-05 14:04:04 +100011891 path: path_t(allow_fd=True)
11892 attribute: path_t
11893 *
11894 follow_symlinks: bool = True
11895
11896Return the value of extended attribute attribute on path.
11897
BNMetricsb9427072018-11-02 15:20:19 +000011898path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011899If follow_symlinks is False, and the last element of the path is a symbolic
11900 link, getxattr will examine the symbolic link itself instead of the file
11901 the link points to.
11902
11903[clinic start generated code]*/
11904
Larry Hastings2f936352014-08-05 14:04:04 +100011905static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011906os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011907 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011908/*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011909{
11910 Py_ssize_t i;
11911 PyObject *buffer = NULL;
11912
11913 if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
11914 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011915
Larry Hastings9cf065c2012-06-22 16:30:09 -070011916 for (i = 0; ; i++) {
11917 void *ptr;
11918 ssize_t result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020011919 static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
Larry Hastings9cf065c2012-06-22 16:30:09 -070011920 Py_ssize_t buffer_size = buffer_sizes[i];
11921 if (!buffer_size) {
Larry Hastings2f936352014-08-05 14:04:04 +100011922 path_error(path);
11923 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011924 }
11925 buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
11926 if (!buffer)
Larry Hastings2f936352014-08-05 14:04:04 +100011927 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011928 ptr = PyBytes_AS_STRING(buffer);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011929
Larry Hastings9cf065c2012-06-22 16:30:09 -070011930 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011931 if (path->fd >= 0)
11932 result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011933 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011934 result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011935 else
Larry Hastings2f936352014-08-05 14:04:04 +100011936 result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011937 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011938
Larry Hastings9cf065c2012-06-22 16:30:09 -070011939 if (result < 0) {
11940 Py_DECREF(buffer);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011941 if (errno == ERANGE)
11942 continue;
Larry Hastings2f936352014-08-05 14:04:04 +100011943 path_error(path);
11944 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011945 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011946
Larry Hastings9cf065c2012-06-22 16:30:09 -070011947 if (result != buffer_size) {
11948 /* Can only shrink. */
11949 _PyBytes_Resize(&buffer, result);
11950 }
11951 break;
11952 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011953
Larry Hastings9cf065c2012-06-22 16:30:09 -070011954 return buffer;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011955}
11956
Larry Hastings2f936352014-08-05 14:04:04 +100011957
11958/*[clinic input]
11959os.setxattr
11960
11961 path: path_t(allow_fd=True)
11962 attribute: path_t
11963 value: Py_buffer
11964 flags: int = 0
11965 *
11966 follow_symlinks: bool = True
11967
11968Set extended attribute attribute on path to value.
11969
BNMetricsb9427072018-11-02 15:20:19 +000011970path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011971If follow_symlinks is False, and the last element of the path is a symbolic
11972 link, setxattr will modify the symbolic link itself instead of the file
11973 the link points to.
11974
11975[clinic start generated code]*/
11976
Benjamin Peterson799bd802011-08-31 22:15:17 -040011977static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011978os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011979 Py_buffer *value, int flags, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011980/*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
Benjamin Peterson799bd802011-08-31 22:15:17 -040011981{
Larry Hastings2f936352014-08-05 14:04:04 +100011982 ssize_t result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011983
Larry Hastings2f936352014-08-05 14:04:04 +100011984 if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
Benjamin Peterson799bd802011-08-31 22:15:17 -040011985 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011986
Benjamin Peterson799bd802011-08-31 22:15:17 -040011987 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011988 if (path->fd > -1)
11989 result = fsetxattr(path->fd, attribute->narrow,
11990 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011991 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011992 result = setxattr(path->narrow, attribute->narrow,
11993 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011994 else
Larry Hastings2f936352014-08-05 14:04:04 +100011995 result = lsetxattr(path->narrow, attribute->narrow,
11996 value->buf, value->len, flags);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011997 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011998
Larry Hastings9cf065c2012-06-22 16:30:09 -070011999 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100012000 path_error(path);
12001 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012002 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012003
Larry Hastings2f936352014-08-05 14:04:04 +100012004 Py_RETURN_NONE;
12005}
12006
12007
12008/*[clinic input]
12009os.removexattr
12010
12011 path: path_t(allow_fd=True)
12012 attribute: path_t
12013 *
12014 follow_symlinks: bool = True
12015
12016Remove extended attribute attribute on path.
12017
BNMetricsb9427072018-11-02 15:20:19 +000012018path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012019If follow_symlinks is False, and the last element of the path is a symbolic
12020 link, removexattr will modify the symbolic link itself instead of the file
12021 the link points to.
12022
12023[clinic start generated code]*/
12024
Larry Hastings2f936352014-08-05 14:04:04 +100012025static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012026os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012027 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012028/*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012029{
12030 ssize_t result;
12031
12032 if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
12033 return NULL;
12034
12035 Py_BEGIN_ALLOW_THREADS;
12036 if (path->fd > -1)
12037 result = fremovexattr(path->fd, attribute->narrow);
12038 else if (follow_symlinks)
12039 result = removexattr(path->narrow, attribute->narrow);
12040 else
12041 result = lremovexattr(path->narrow, attribute->narrow);
12042 Py_END_ALLOW_THREADS;
12043
12044 if (result) {
12045 return path_error(path);
12046 }
12047
12048 Py_RETURN_NONE;
12049}
12050
12051
12052/*[clinic input]
12053os.listxattr
12054
12055 path: path_t(allow_fd=True, nullable=True) = None
12056 *
12057 follow_symlinks: bool = True
12058
12059Return a list of extended attributes on path.
12060
BNMetricsb9427072018-11-02 15:20:19 +000012061path may be either None, a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012062if path is None, listxattr will examine the current directory.
12063If follow_symlinks is False, and the last element of the path is a symbolic
12064 link, listxattr will examine the symbolic link itself instead of the file
12065 the link points to.
12066[clinic start generated code]*/
12067
Larry Hastings2f936352014-08-05 14:04:04 +100012068static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012069os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012070/*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012071{
Larry Hastings9cf065c2012-06-22 16:30:09 -070012072 Py_ssize_t i;
12073 PyObject *result = NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100012074 const char *name;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012075 char *buffer = NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012076
Larry Hastings2f936352014-08-05 14:04:04 +100012077 if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
Larry Hastings9cf065c2012-06-22 16:30:09 -070012078 goto exit;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012079
Larry Hastings2f936352014-08-05 14:04:04 +100012080 name = path->narrow ? path->narrow : ".";
12081
Larry Hastings9cf065c2012-06-22 16:30:09 -070012082 for (i = 0; ; i++) {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012083 const char *start, *trace, *end;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012084 ssize_t length;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012085 static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
Larry Hastings9cf065c2012-06-22 16:30:09 -070012086 Py_ssize_t buffer_size = buffer_sizes[i];
12087 if (!buffer_size) {
Christian Heimes3b9493b2012-09-23 16:11:15 +020012088 /* ERANGE */
Larry Hastings2f936352014-08-05 14:04:04 +100012089 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012090 break;
12091 }
12092 buffer = PyMem_MALLOC(buffer_size);
12093 if (!buffer) {
12094 PyErr_NoMemory();
12095 break;
12096 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012097
Larry Hastings9cf065c2012-06-22 16:30:09 -070012098 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012099 if (path->fd > -1)
12100 length = flistxattr(path->fd, buffer, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012101 else if (follow_symlinks)
12102 length = listxattr(name, buffer, buffer_size);
12103 else
12104 length = llistxattr(name, buffer, buffer_size);
12105 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012106
Larry Hastings9cf065c2012-06-22 16:30:09 -070012107 if (length < 0) {
Antoine Pitrou7f987392013-05-13 19:46:29 +020012108 if (errno == ERANGE) {
12109 PyMem_FREE(buffer);
Benjamin Petersondedac522013-05-13 19:55:40 -050012110 buffer = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012111 continue;
Antoine Pitrou7f987392013-05-13 19:46:29 +020012112 }
Larry Hastings2f936352014-08-05 14:04:04 +100012113 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012114 break;
12115 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012116
Larry Hastings9cf065c2012-06-22 16:30:09 -070012117 result = PyList_New(0);
12118 if (!result) {
12119 goto exit;
12120 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012121
Larry Hastings9cf065c2012-06-22 16:30:09 -070012122 end = buffer + length;
12123 for (trace = start = buffer; trace != end; trace++) {
12124 if (!*trace) {
12125 int error;
12126 PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
12127 trace - start);
12128 if (!attribute) {
12129 Py_DECREF(result);
12130 result = NULL;
12131 goto exit;
12132 }
12133 error = PyList_Append(result, attribute);
12134 Py_DECREF(attribute);
12135 if (error) {
12136 Py_DECREF(result);
12137 result = NULL;
12138 goto exit;
12139 }
12140 start = trace + 1;
12141 }
12142 }
12143 break;
12144 }
12145exit:
Larry Hastings9cf065c2012-06-22 16:30:09 -070012146 if (buffer)
12147 PyMem_FREE(buffer);
12148 return result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012149}
Benjamin Peterson9428d532011-09-14 11:45:52 -040012150#endif /* USE_XATTRS */
Benjamin Peterson799bd802011-08-31 22:15:17 -040012151
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012152
Larry Hastings2f936352014-08-05 14:04:04 +100012153/*[clinic input]
12154os.urandom
12155
12156 size: Py_ssize_t
12157 /
12158
12159Return a bytes object containing random bytes suitable for cryptographic use.
12160[clinic start generated code]*/
12161
Larry Hastings2f936352014-08-05 14:04:04 +100012162static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012163os_urandom_impl(PyObject *module, Py_ssize_t size)
12164/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012165{
12166 PyObject *bytes;
12167 int result;
12168
Georg Brandl2fb477c2012-02-21 00:33:36 +010012169 if (size < 0)
12170 return PyErr_Format(PyExc_ValueError,
12171 "negative argument not allowed");
Larry Hastings2f936352014-08-05 14:04:04 +100012172 bytes = PyBytes_FromStringAndSize(NULL, size);
12173 if (bytes == NULL)
Georg Brandl2fb477c2012-02-21 00:33:36 +010012174 return NULL;
12175
Victor Stinnere66987e2016-09-06 16:33:52 -070012176 result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
Larry Hastings2f936352014-08-05 14:04:04 +100012177 if (result == -1) {
12178 Py_DECREF(bytes);
Georg Brandl2fb477c2012-02-21 00:33:36 +010012179 return NULL;
12180 }
Larry Hastings2f936352014-08-05 14:04:04 +100012181 return bytes;
Georg Brandl2fb477c2012-02-21 00:33:36 +010012182}
12183
Zackery Spytz43fdbd22019-05-29 13:57:07 -060012184#ifdef HAVE_MEMFD_CREATE
12185/*[clinic input]
12186os.memfd_create
12187
12188 name: FSConverter
12189 flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
12190
12191[clinic start generated code]*/
12192
12193static PyObject *
12194os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
12195/*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
12196{
12197 int fd;
12198 const char *bytes = PyBytes_AS_STRING(name);
12199 Py_BEGIN_ALLOW_THREADS
12200 fd = memfd_create(bytes, flags);
12201 Py_END_ALLOW_THREADS
12202 if (fd == -1) {
12203 return PyErr_SetFromErrno(PyExc_OSError);
12204 }
12205 return PyLong_FromLong(fd);
12206}
12207#endif
12208
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012209/* Terminal size querying */
12210
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012211PyDoc_STRVAR(TerminalSize_docstring,
12212 "A tuple of (columns, lines) for holding terminal window size");
12213
12214static PyStructSequence_Field TerminalSize_fields[] = {
12215 {"columns", "width of the terminal window in characters"},
12216 {"lines", "height of the terminal window in characters"},
12217 {NULL, NULL}
12218};
12219
12220static PyStructSequence_Desc TerminalSize_desc = {
12221 "os.terminal_size",
12222 TerminalSize_docstring,
12223 TerminalSize_fields,
12224 2,
12225};
12226
12227#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
Larry Hastings2f936352014-08-05 14:04:04 +100012228/* AC 3.5: fd should accept None */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012229PyDoc_STRVAR(termsize__doc__,
12230 "Return the size of the terminal window as (columns, lines).\n" \
12231 "\n" \
12232 "The optional argument fd (default standard output) specifies\n" \
12233 "which file descriptor should be queried.\n" \
12234 "\n" \
12235 "If the file descriptor is not connected to a terminal, an OSError\n" \
12236 "is thrown.\n" \
12237 "\n" \
12238 "This function will only be defined if an implementation is\n" \
12239 "available for this system.\n" \
12240 "\n" \
oldkaa0735f2018-02-02 16:52:55 +080012241 "shutil.get_terminal_size is the high-level function which should\n" \
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012242 "normally be used, os.get_terminal_size is the low-level implementation.");
12243
12244static PyObject*
12245get_terminal_size(PyObject *self, PyObject *args)
12246{
12247 int columns, lines;
12248 PyObject *termsize;
12249
12250 int fd = fileno(stdout);
12251 /* Under some conditions stdout may not be connected and
12252 * fileno(stdout) may point to an invalid file descriptor. For example
12253 * GUI apps don't have valid standard streams by default.
12254 *
12255 * If this happens, and the optional fd argument is not present,
12256 * the ioctl below will fail returning EBADF. This is what we want.
12257 */
12258
12259 if (!PyArg_ParseTuple(args, "|i", &fd))
12260 return NULL;
12261
12262#ifdef TERMSIZE_USE_IOCTL
12263 {
12264 struct winsize w;
12265 if (ioctl(fd, TIOCGWINSZ, &w))
12266 return PyErr_SetFromErrno(PyExc_OSError);
12267 columns = w.ws_col;
12268 lines = w.ws_row;
12269 }
12270#endif /* TERMSIZE_USE_IOCTL */
12271
12272#ifdef TERMSIZE_USE_CONIO
12273 {
12274 DWORD nhandle;
12275 HANDLE handle;
12276 CONSOLE_SCREEN_BUFFER_INFO csbi;
12277 switch (fd) {
12278 case 0: nhandle = STD_INPUT_HANDLE;
12279 break;
12280 case 1: nhandle = STD_OUTPUT_HANDLE;
12281 break;
12282 case 2: nhandle = STD_ERROR_HANDLE;
12283 break;
12284 default:
12285 return PyErr_Format(PyExc_ValueError, "bad file descriptor");
12286 }
12287 handle = GetStdHandle(nhandle);
12288 if (handle == NULL)
12289 return PyErr_Format(PyExc_OSError, "handle cannot be retrieved");
12290 if (handle == INVALID_HANDLE_VALUE)
12291 return PyErr_SetFromWindowsErr(0);
12292
12293 if (!GetConsoleScreenBufferInfo(handle, &csbi))
12294 return PyErr_SetFromWindowsErr(0);
12295
12296 columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
12297 lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
12298 }
12299#endif /* TERMSIZE_USE_CONIO */
12300
Eddie Elizondob3966632019-11-05 07:16:14 -080012301 PyObject *TerminalSizeType = _posixstate(self)->TerminalSizeType;
12302 termsize = PyStructSequence_New((PyTypeObject *)TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012303 if (termsize == NULL)
12304 return NULL;
12305 PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
12306 PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
12307 if (PyErr_Occurred()) {
12308 Py_DECREF(termsize);
12309 return NULL;
12310 }
12311 return termsize;
12312}
12313#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
12314
Larry Hastings2f936352014-08-05 14:04:04 +100012315
12316/*[clinic input]
12317os.cpu_count
12318
Charles-François Natali80d62e62015-08-13 20:37:08 +010012319Return the number of CPUs in the system; return None if indeterminable.
12320
12321This number is not equivalent to the number of CPUs the current process can
12322use. The number of usable CPUs can be obtained with
12323``len(os.sched_getaffinity(0))``
Larry Hastings2f936352014-08-05 14:04:04 +100012324[clinic start generated code]*/
12325
Larry Hastings2f936352014-08-05 14:04:04 +100012326static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012327os_cpu_count_impl(PyObject *module)
Serhiy Storchaka2954f832016-07-07 18:20:03 +030012328/*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012329{
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012330 int ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012331#ifdef MS_WINDOWS
Steve Doweraa929272019-09-11 16:15:39 +010012332 ncpu = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012333#elif defined(__hpux)
12334 ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
12335#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
12336 ncpu = sysconf(_SC_NPROCESSORS_ONLN);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012337#elif defined(__DragonFly__) || \
12338 defined(__OpenBSD__) || \
12339 defined(__FreeBSD__) || \
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012340 defined(__NetBSD__) || \
12341 defined(__APPLE__)
Charles-Francois Natali7c4f8da2013-05-20 17:40:32 +020012342 int mib[2];
12343 size_t len = sizeof(ncpu);
12344 mib[0] = CTL_HW;
12345 mib[1] = HW_NCPU;
12346 if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
12347 ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012348#endif
12349 if (ncpu >= 1)
12350 return PyLong_FromLong(ncpu);
12351 else
12352 Py_RETURN_NONE;
12353}
12354
Victor Stinnerdaf45552013-08-28 00:53:59 +020012355
Larry Hastings2f936352014-08-05 14:04:04 +100012356/*[clinic input]
12357os.get_inheritable -> bool
12358
12359 fd: int
12360 /
12361
12362Get the close-on-exe flag of the specified file descriptor.
12363[clinic start generated code]*/
12364
Larry Hastings2f936352014-08-05 14:04:04 +100012365static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012366os_get_inheritable_impl(PyObject *module, int fd)
12367/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012368{
Steve Dower8fc89802015-04-12 00:26:27 -040012369 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -040012370 _Py_BEGIN_SUPPRESS_IPH
12371 return_value = _Py_get_inheritable(fd);
12372 _Py_END_SUPPRESS_IPH
12373 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +100012374}
12375
12376
12377/*[clinic input]
12378os.set_inheritable
12379 fd: int
12380 inheritable: int
12381 /
12382
12383Set the inheritable flag of the specified file descriptor.
12384[clinic start generated code]*/
12385
Larry Hastings2f936352014-08-05 14:04:04 +100012386static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012387os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
12388/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
Victor Stinnerdaf45552013-08-28 00:53:59 +020012389{
Steve Dower8fc89802015-04-12 00:26:27 -040012390 int result;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012391
Steve Dower8fc89802015-04-12 00:26:27 -040012392 _Py_BEGIN_SUPPRESS_IPH
12393 result = _Py_set_inheritable(fd, inheritable, NULL);
12394 _Py_END_SUPPRESS_IPH
12395 if (result < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +020012396 return NULL;
12397 Py_RETURN_NONE;
12398}
12399
12400
12401#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100012402/*[clinic input]
12403os.get_handle_inheritable -> bool
Benjamin Petersonca470632016-09-06 13:47:26 -070012404 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012405 /
Victor Stinnerdaf45552013-08-28 00:53:59 +020012406
Larry Hastings2f936352014-08-05 14:04:04 +100012407Get the close-on-exe flag of the specified file descriptor.
12408[clinic start generated code]*/
12409
Larry Hastings2f936352014-08-05 14:04:04 +100012410static int
Benjamin Petersonca470632016-09-06 13:47:26 -070012411os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
Victor Stinner581139c2016-09-06 15:54:20 -070012412/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012413{
12414 DWORD flags;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012415
12416 if (!GetHandleInformation((HANDLE)handle, &flags)) {
12417 PyErr_SetFromWindowsErr(0);
Larry Hastings2f936352014-08-05 14:04:04 +100012418 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012419 }
12420
Larry Hastings2f936352014-08-05 14:04:04 +100012421 return flags & HANDLE_FLAG_INHERIT;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012422}
12423
Victor Stinnerdaf45552013-08-28 00:53:59 +020012424
Larry Hastings2f936352014-08-05 14:04:04 +100012425/*[clinic input]
12426os.set_handle_inheritable
Benjamin Petersonca470632016-09-06 13:47:26 -070012427 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012428 inheritable: bool
12429 /
12430
12431Set the inheritable flag of the specified handle.
12432[clinic start generated code]*/
12433
Larry Hastings2f936352014-08-05 14:04:04 +100012434static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -070012435os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
Larry Hastings89964c42015-04-14 18:07:59 -040012436 int inheritable)
Victor Stinner581139c2016-09-06 15:54:20 -070012437/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012438{
12439 DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012440 if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
12441 PyErr_SetFromWindowsErr(0);
12442 return NULL;
12443 }
12444 Py_RETURN_NONE;
12445}
Larry Hastings2f936352014-08-05 14:04:04 +100012446#endif /* MS_WINDOWS */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012447
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012448#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012449/*[clinic input]
12450os.get_blocking -> bool
12451 fd: int
12452 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012453
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012454Get the blocking mode of the file descriptor.
12455
12456Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
12457[clinic start generated code]*/
12458
12459static int
12460os_get_blocking_impl(PyObject *module, int fd)
12461/*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012462{
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012463 int blocking;
12464
Steve Dower8fc89802015-04-12 00:26:27 -040012465 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012466 blocking = _Py_get_blocking(fd);
Steve Dower8fc89802015-04-12 00:26:27 -040012467 _Py_END_SUPPRESS_IPH
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012468 return blocking;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012469}
12470
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012471/*[clinic input]
12472os.set_blocking
12473 fd: int
12474 blocking: bool(accept={int})
12475 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012476
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012477Set the blocking mode of the specified file descriptor.
12478
12479Set the O_NONBLOCK flag if blocking is False,
12480clear the O_NONBLOCK flag otherwise.
12481[clinic start generated code]*/
12482
12483static PyObject *
12484os_set_blocking_impl(PyObject *module, int fd, int blocking)
12485/*[clinic end generated code: output=384eb43aa0762a9d input=bf5c8efdc5860ff3]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012486{
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012487 int result;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012488
Steve Dower8fc89802015-04-12 00:26:27 -040012489 _Py_BEGIN_SUPPRESS_IPH
12490 result = _Py_set_blocking(fd, blocking);
12491 _Py_END_SUPPRESS_IPH
12492 if (result < 0)
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012493 return NULL;
12494 Py_RETURN_NONE;
12495}
12496#endif /* !MS_WINDOWS */
12497
12498
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012499/*[clinic input]
Eddie Elizondob3966632019-11-05 07:16:14 -080012500class os.DirEntry "DirEntry *" "DirEntryType"
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012501[clinic start generated code]*/
Eddie Elizondob3966632019-11-05 07:16:14 -080012502/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3c18c7a448247980]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012503
12504typedef struct {
12505 PyObject_HEAD
12506 PyObject *name;
12507 PyObject *path;
12508 PyObject *stat;
12509 PyObject *lstat;
12510#ifdef MS_WINDOWS
12511 struct _Py_stat_struct win32_lstat;
Victor Stinner0f6d7332017-03-09 17:34:28 +010012512 uint64_t win32_file_index;
Victor Stinner6036e442015-03-08 01:58:04 +010012513 int got_file_index;
12514#else /* POSIX */
Victor Stinner35a97c02015-03-08 02:59:09 +010012515#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012516 unsigned char d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012517#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012518 ino_t d_ino;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012519 int dir_fd;
Victor Stinner6036e442015-03-08 01:58:04 +010012520#endif
12521} DirEntry;
12522
Eddie Elizondob3966632019-11-05 07:16:14 -080012523static PyObject *
12524_disabled_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
12525{
12526 PyErr_Format(PyExc_TypeError,
12527 "cannot create '%.100s' instances", _PyType_Name(type));
12528 return NULL;
12529}
12530
Victor Stinner6036e442015-03-08 01:58:04 +010012531static void
12532DirEntry_dealloc(DirEntry *entry)
12533{
Eddie Elizondob3966632019-11-05 07:16:14 -080012534 PyTypeObject *tp = Py_TYPE(entry);
Victor Stinner6036e442015-03-08 01:58:04 +010012535 Py_XDECREF(entry->name);
12536 Py_XDECREF(entry->path);
12537 Py_XDECREF(entry->stat);
12538 Py_XDECREF(entry->lstat);
Eddie Elizondob3966632019-11-05 07:16:14 -080012539 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
12540 free_func(entry);
12541 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010012542}
12543
12544/* Forward reference */
12545static int
12546DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits);
12547
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012548/*[clinic input]
12549os.DirEntry.is_symlink -> bool
12550
12551Return True if the entry is a symbolic link; cached per entry.
12552[clinic start generated code]*/
12553
Victor Stinner6036e442015-03-08 01:58:04 +010012554static int
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012555os_DirEntry_is_symlink_impl(DirEntry *self)
12556/*[clinic end generated code: output=42244667d7bcfc25 input=1605a1b4b96976c3]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012557{
12558#ifdef MS_WINDOWS
12559 return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
Victor Stinner35a97c02015-03-08 02:59:09 +010012560#elif defined(HAVE_DIRENT_D_TYPE)
12561 /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010012562 if (self->d_type != DT_UNKNOWN)
12563 return self->d_type == DT_LNK;
12564 else
12565 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner35a97c02015-03-08 02:59:09 +010012566#else
12567 /* POSIX without d_type */
12568 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner6036e442015-03-08 01:58:04 +010012569#endif
12570}
12571
12572static PyObject *
Victor Stinner6036e442015-03-08 01:58:04 +010012573DirEntry_fetch_stat(DirEntry *self, int follow_symlinks)
12574{
12575 int result;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012576 STRUCT_STAT st;
12577 PyObject *ub;
Victor Stinner6036e442015-03-08 01:58:04 +010012578
12579#ifdef MS_WINDOWS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012580 if (!PyUnicode_FSDecoder(self->path, &ub))
12581 return NULL;
12582 const wchar_t *path = PyUnicode_AsUnicode(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012583#else /* POSIX */
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012584 if (!PyUnicode_FSConverter(self->path, &ub))
12585 return NULL;
12586 const char *path = PyBytes_AS_STRING(ub);
12587 if (self->dir_fd != DEFAULT_DIR_FD) {
12588#ifdef HAVE_FSTATAT
12589 result = fstatat(self->dir_fd, path, &st,
12590 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
12591#else
12592 PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
12593 return NULL;
12594#endif /* HAVE_FSTATAT */
12595 }
12596 else
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012597#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012598 {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012599 if (follow_symlinks)
12600 result = STAT(path, &st);
12601 else
12602 result = LSTAT(path, &st);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012603 }
12604 Py_DECREF(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012605
12606 if (result != 0)
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012607 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012608
12609 return _pystat_fromstructstat(&st);
12610}
12611
12612static PyObject *
12613DirEntry_get_lstat(DirEntry *self)
12614{
12615 if (!self->lstat) {
12616#ifdef MS_WINDOWS
12617 self->lstat = _pystat_fromstructstat(&self->win32_lstat);
12618#else /* POSIX */
12619 self->lstat = DirEntry_fetch_stat(self, 0);
12620#endif
12621 }
12622 Py_XINCREF(self->lstat);
12623 return self->lstat;
12624}
12625
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012626/*[clinic input]
12627os.DirEntry.stat
12628 *
12629 follow_symlinks: bool = True
12630
12631Return stat_result object for the entry; cached per entry.
12632[clinic start generated code]*/
12633
Victor Stinner6036e442015-03-08 01:58:04 +010012634static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012635os_DirEntry_stat_impl(DirEntry *self, int follow_symlinks)
12636/*[clinic end generated code: output=008593b3a6d01305 input=280d14c1d6f1d00d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012637{
12638 if (!follow_symlinks)
12639 return DirEntry_get_lstat(self);
12640
12641 if (!self->stat) {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012642 int result = os_DirEntry_is_symlink_impl(self);
Victor Stinner6036e442015-03-08 01:58:04 +010012643 if (result == -1)
12644 return NULL;
12645 else if (result)
12646 self->stat = DirEntry_fetch_stat(self, 1);
12647 else
12648 self->stat = DirEntry_get_lstat(self);
12649 }
12650
12651 Py_XINCREF(self->stat);
12652 return self->stat;
12653}
12654
Victor Stinner6036e442015-03-08 01:58:04 +010012655/* Set exception and return -1 on error, 0 for False, 1 for True */
12656static int
12657DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
12658{
12659 PyObject *stat = NULL;
12660 PyObject *st_mode = NULL;
12661 long mode;
12662 int result;
Victor Stinner35a97c02015-03-08 02:59:09 +010012663#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012664 int is_symlink;
12665 int need_stat;
Victor Stinner35a97c02015-03-08 02:59:09 +010012666#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012667#ifdef MS_WINDOWS
12668 unsigned long dir_bits;
12669#endif
12670
12671#ifdef MS_WINDOWS
12672 is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
12673 need_stat = follow_symlinks && is_symlink;
Victor Stinner35a97c02015-03-08 02:59:09 +010012674#elif defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012675 is_symlink = self->d_type == DT_LNK;
12676 need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
12677#endif
12678
Victor Stinner35a97c02015-03-08 02:59:09 +010012679#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012680 if (need_stat) {
Victor Stinner35a97c02015-03-08 02:59:09 +010012681#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012682 stat = os_DirEntry_stat_impl(self, follow_symlinks);
Victor Stinner6036e442015-03-08 01:58:04 +010012683 if (!stat) {
12684 if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
12685 /* If file doesn't exist (anymore), then return False
12686 (i.e., say it's not a file/directory) */
12687 PyErr_Clear();
12688 return 0;
12689 }
12690 goto error;
12691 }
Eddie Elizondob3966632019-11-05 07:16:14 -080012692 st_mode = PyObject_GetAttr(stat, _posixstate_global->st_mode);
Victor Stinner6036e442015-03-08 01:58:04 +010012693 if (!st_mode)
12694 goto error;
12695
12696 mode = PyLong_AsLong(st_mode);
12697 if (mode == -1 && PyErr_Occurred())
12698 goto error;
12699 Py_CLEAR(st_mode);
12700 Py_CLEAR(stat);
12701 result = (mode & S_IFMT) == mode_bits;
Victor Stinner35a97c02015-03-08 02:59:09 +010012702#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012703 }
12704 else if (is_symlink) {
12705 assert(mode_bits != S_IFLNK);
12706 result = 0;
12707 }
12708 else {
12709 assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
12710#ifdef MS_WINDOWS
12711 dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
12712 if (mode_bits == S_IFDIR)
12713 result = dir_bits != 0;
12714 else
12715 result = dir_bits == 0;
12716#else /* POSIX */
12717 if (mode_bits == S_IFDIR)
12718 result = self->d_type == DT_DIR;
12719 else
12720 result = self->d_type == DT_REG;
12721#endif
12722 }
Victor Stinner35a97c02015-03-08 02:59:09 +010012723#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012724
12725 return result;
12726
12727error:
12728 Py_XDECREF(st_mode);
12729 Py_XDECREF(stat);
12730 return -1;
12731}
12732
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012733/*[clinic input]
12734os.DirEntry.is_dir -> bool
12735 *
12736 follow_symlinks: bool = True
Victor Stinner6036e442015-03-08 01:58:04 +010012737
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012738Return True if the entry is a directory; cached per entry.
12739[clinic start generated code]*/
12740
12741static int
12742os_DirEntry_is_dir_impl(DirEntry *self, int follow_symlinks)
12743/*[clinic end generated code: output=ad2e8d54365da287 input=0135232766f53f58]*/
12744{
12745 return DirEntry_test_mode(self, follow_symlinks, S_IFDIR);
Victor Stinner6036e442015-03-08 01:58:04 +010012746}
12747
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012748/*[clinic input]
12749os.DirEntry.is_file -> bool
12750 *
12751 follow_symlinks: bool = True
12752
12753Return True if the entry is a file; cached per entry.
12754[clinic start generated code]*/
12755
12756static int
12757os_DirEntry_is_file_impl(DirEntry *self, int follow_symlinks)
12758/*[clinic end generated code: output=8462ade481d8a476 input=0dc90be168b041ee]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012759{
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012760 return DirEntry_test_mode(self, follow_symlinks, S_IFREG);
Victor Stinner6036e442015-03-08 01:58:04 +010012761}
12762
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012763/*[clinic input]
12764os.DirEntry.inode
Victor Stinner6036e442015-03-08 01:58:04 +010012765
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012766Return inode of the entry; cached per entry.
12767[clinic start generated code]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012768
12769static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012770os_DirEntry_inode_impl(DirEntry *self)
12771/*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012772{
12773#ifdef MS_WINDOWS
12774 if (!self->got_file_index) {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012775 PyObject *unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012776 const wchar_t *path;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012777 STRUCT_STAT stat;
12778 int result;
Victor Stinner6036e442015-03-08 01:58:04 +010012779
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012780 if (!PyUnicode_FSDecoder(self->path, &unicode))
Victor Stinner6036e442015-03-08 01:58:04 +010012781 return NULL;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012782 path = PyUnicode_AsUnicode(unicode);
12783 result = LSTAT(path, &stat);
12784 Py_DECREF(unicode);
Victor Stinner6036e442015-03-08 01:58:04 +010012785
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012786 if (result != 0)
12787 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012788
12789 self->win32_file_index = stat.st_ino;
12790 self->got_file_index = 1;
12791 }
Victor Stinner0f6d7332017-03-09 17:34:28 +010012792 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->win32_file_index));
12793 return PyLong_FromUnsignedLongLong(self->win32_file_index);
Victor Stinner6036e442015-03-08 01:58:04 +010012794#else /* POSIX */
xdegaye50e86032017-05-22 11:15:08 +020012795 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->d_ino));
12796 return PyLong_FromUnsignedLongLong(self->d_ino);
Victor Stinner6036e442015-03-08 01:58:04 +010012797#endif
12798}
12799
12800static PyObject *
12801DirEntry_repr(DirEntry *self)
12802{
12803 return PyUnicode_FromFormat("<DirEntry %R>", self->name);
12804}
12805
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012806/*[clinic input]
12807os.DirEntry.__fspath__
12808
12809Returns the path for the entry.
12810[clinic start generated code]*/
12811
Brett Cannon96881cd2016-06-10 14:37:21 -070012812static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012813os_DirEntry___fspath___impl(DirEntry *self)
12814/*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
Brett Cannon96881cd2016-06-10 14:37:21 -070012815{
12816 Py_INCREF(self->path);
12817 return self->path;
12818}
12819
Victor Stinner6036e442015-03-08 01:58:04 +010012820static PyMemberDef DirEntry_members[] = {
12821 {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
12822 "the entry's base filename, relative to scandir() \"path\" argument"},
12823 {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
12824 "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
12825 {NULL}
12826};
12827
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012828#include "clinic/posixmodule.c.h"
12829
Victor Stinner6036e442015-03-08 01:58:04 +010012830static PyMethodDef DirEntry_methods[] = {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012831 OS_DIRENTRY_IS_DIR_METHODDEF
12832 OS_DIRENTRY_IS_FILE_METHODDEF
12833 OS_DIRENTRY_IS_SYMLINK_METHODDEF
12834 OS_DIRENTRY_STAT_METHODDEF
12835 OS_DIRENTRY_INODE_METHODDEF
12836 OS_DIRENTRY___FSPATH___METHODDEF
Victor Stinner6036e442015-03-08 01:58:04 +010012837 {NULL}
12838};
12839
Eddie Elizondob3966632019-11-05 07:16:14 -080012840static PyType_Slot DirEntryType_slots[] = {
12841 {Py_tp_new, _disabled_new},
12842 {Py_tp_dealloc, DirEntry_dealloc},
12843 {Py_tp_repr, DirEntry_repr},
12844 {Py_tp_methods, DirEntry_methods},
12845 {Py_tp_members, DirEntry_members},
12846 {0, 0},
Victor Stinner6036e442015-03-08 01:58:04 +010012847};
12848
Eddie Elizondob3966632019-11-05 07:16:14 -080012849static PyType_Spec DirEntryType_spec = {
12850 MODNAME ".DirEntry",
12851 sizeof(DirEntry),
12852 0,
12853 Py_TPFLAGS_DEFAULT,
12854 DirEntryType_slots
12855};
12856
12857
Victor Stinner6036e442015-03-08 01:58:04 +010012858#ifdef MS_WINDOWS
12859
12860static wchar_t *
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012861join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
Victor Stinner6036e442015-03-08 01:58:04 +010012862{
12863 Py_ssize_t path_len;
12864 Py_ssize_t size;
12865 wchar_t *result;
12866 wchar_t ch;
12867
12868 if (!path_wide) { /* Default arg: "." */
12869 path_wide = L".";
12870 path_len = 1;
12871 }
12872 else {
12873 path_len = wcslen(path_wide);
12874 }
12875
12876 /* The +1's are for the path separator and the NUL */
12877 size = path_len + 1 + wcslen(filename) + 1;
12878 result = PyMem_New(wchar_t, size);
12879 if (!result) {
12880 PyErr_NoMemory();
12881 return NULL;
12882 }
12883 wcscpy(result, path_wide);
12884 if (path_len > 0) {
12885 ch = result[path_len - 1];
12886 if (ch != SEP && ch != ALTSEP && ch != L':')
12887 result[path_len++] = SEP;
12888 wcscpy(result + path_len, filename);
12889 }
12890 return result;
12891}
12892
12893static PyObject *
12894DirEntry_from_find_data(path_t *path, WIN32_FIND_DATAW *dataW)
12895{
12896 DirEntry *entry;
12897 BY_HANDLE_FILE_INFORMATION file_info;
12898 ULONG reparse_tag;
12899 wchar_t *joined_path;
12900
Eddie Elizondob3966632019-11-05 07:16:14 -080012901 PyObject *DirEntryType = _posixstate_global->DirEntryType;
12902 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010012903 if (!entry)
12904 return NULL;
12905 entry->name = NULL;
12906 entry->path = NULL;
12907 entry->stat = NULL;
12908 entry->lstat = NULL;
12909 entry->got_file_index = 0;
12910
12911 entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
12912 if (!entry->name)
12913 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012914 if (path->narrow) {
12915 Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
12916 if (!entry->name)
12917 goto error;
12918 }
Victor Stinner6036e442015-03-08 01:58:04 +010012919
12920 joined_path = join_path_filenameW(path->wide, dataW->cFileName);
12921 if (!joined_path)
12922 goto error;
12923
12924 entry->path = PyUnicode_FromWideChar(joined_path, -1);
12925 PyMem_Free(joined_path);
12926 if (!entry->path)
12927 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012928 if (path->narrow) {
12929 Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
12930 if (!entry->path)
12931 goto error;
12932 }
Victor Stinner6036e442015-03-08 01:58:04 +010012933
Steve Dowercc16be82016-09-08 10:35:16 -070012934 find_data_to_file_info(dataW, &file_info, &reparse_tag);
Victor Stinner6036e442015-03-08 01:58:04 +010012935 _Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
12936
12937 return (PyObject *)entry;
12938
12939error:
12940 Py_DECREF(entry);
12941 return NULL;
12942}
12943
12944#else /* POSIX */
12945
12946static char *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012947join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
Victor Stinner6036e442015-03-08 01:58:04 +010012948{
12949 Py_ssize_t path_len;
12950 Py_ssize_t size;
12951 char *result;
12952
12953 if (!path_narrow) { /* Default arg: "." */
12954 path_narrow = ".";
12955 path_len = 1;
12956 }
12957 else {
12958 path_len = strlen(path_narrow);
12959 }
12960
12961 if (filename_len == -1)
12962 filename_len = strlen(filename);
12963
12964 /* The +1's are for the path separator and the NUL */
12965 size = path_len + 1 + filename_len + 1;
12966 result = PyMem_New(char, size);
12967 if (!result) {
12968 PyErr_NoMemory();
12969 return NULL;
12970 }
12971 strcpy(result, path_narrow);
12972 if (path_len > 0 && result[path_len - 1] != '/')
12973 result[path_len++] = '/';
12974 strcpy(result + path_len, filename);
12975 return result;
12976}
12977
12978static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012979DirEntry_from_posix_info(path_t *path, const char *name, Py_ssize_t name_len,
Victor Stinner35a97c02015-03-08 02:59:09 +010012980 ino_t d_ino
12981#ifdef HAVE_DIRENT_D_TYPE
12982 , unsigned char d_type
12983#endif
12984 )
Victor Stinner6036e442015-03-08 01:58:04 +010012985{
12986 DirEntry *entry;
12987 char *joined_path;
12988
Eddie Elizondob3966632019-11-05 07:16:14 -080012989 PyObject *DirEntryType = _posixstate_global->DirEntryType;
12990 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010012991 if (!entry)
12992 return NULL;
12993 entry->name = NULL;
12994 entry->path = NULL;
12995 entry->stat = NULL;
12996 entry->lstat = NULL;
12997
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012998 if (path->fd != -1) {
12999 entry->dir_fd = path->fd;
13000 joined_path = NULL;
13001 }
13002 else {
13003 entry->dir_fd = DEFAULT_DIR_FD;
13004 joined_path = join_path_filename(path->narrow, name, name_len);
13005 if (!joined_path)
13006 goto error;
13007 }
Victor Stinner6036e442015-03-08 01:58:04 +010013008
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +030013009 if (!path->narrow || !PyObject_CheckBuffer(path->object)) {
Victor Stinner6036e442015-03-08 01:58:04 +010013010 entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013011 if (joined_path)
13012 entry->path = PyUnicode_DecodeFSDefault(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013013 }
13014 else {
13015 entry->name = PyBytes_FromStringAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013016 if (joined_path)
13017 entry->path = PyBytes_FromString(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013018 }
13019 PyMem_Free(joined_path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013020 if (!entry->name)
13021 goto error;
13022
13023 if (path->fd != -1) {
13024 entry->path = entry->name;
13025 Py_INCREF(entry->path);
13026 }
13027 else if (!entry->path)
Victor Stinner6036e442015-03-08 01:58:04 +010013028 goto error;
13029
Victor Stinner35a97c02015-03-08 02:59:09 +010013030#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010013031 entry->d_type = d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010013032#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013033 entry->d_ino = d_ino;
13034
13035 return (PyObject *)entry;
13036
13037error:
13038 Py_XDECREF(entry);
13039 return NULL;
13040}
13041
13042#endif
13043
13044
13045typedef struct {
13046 PyObject_HEAD
13047 path_t path;
13048#ifdef MS_WINDOWS
13049 HANDLE handle;
13050 WIN32_FIND_DATAW file_data;
13051 int first_time;
13052#else /* POSIX */
13053 DIR *dirp;
13054#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013055#ifdef HAVE_FDOPENDIR
13056 int fd;
13057#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013058} ScandirIterator;
13059
13060#ifdef MS_WINDOWS
13061
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013062static int
13063ScandirIterator_is_closed(ScandirIterator *iterator)
13064{
13065 return iterator->handle == INVALID_HANDLE_VALUE;
13066}
13067
Victor Stinner6036e442015-03-08 01:58:04 +010013068static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013069ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013070{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013071 HANDLE handle = iterator->handle;
13072
13073 if (handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013074 return;
13075
Victor Stinner6036e442015-03-08 01:58:04 +010013076 iterator->handle = INVALID_HANDLE_VALUE;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013077 Py_BEGIN_ALLOW_THREADS
13078 FindClose(handle);
13079 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013080}
13081
13082static PyObject *
13083ScandirIterator_iternext(ScandirIterator *iterator)
13084{
13085 WIN32_FIND_DATAW *file_data = &iterator->file_data;
13086 BOOL success;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013087 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013088
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013089 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013090 if (iterator->handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013091 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013092
13093 while (1) {
13094 if (!iterator->first_time) {
13095 Py_BEGIN_ALLOW_THREADS
13096 success = FindNextFileW(iterator->handle, file_data);
13097 Py_END_ALLOW_THREADS
13098 if (!success) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013099 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013100 if (GetLastError() != ERROR_NO_MORE_FILES)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013101 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013102 break;
13103 }
13104 }
13105 iterator->first_time = 0;
13106
13107 /* Skip over . and .. */
13108 if (wcscmp(file_data->cFileName, L".") != 0 &&
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013109 wcscmp(file_data->cFileName, L"..") != 0) {
13110 entry = DirEntry_from_find_data(&iterator->path, file_data);
13111 if (!entry)
13112 break;
13113 return entry;
13114 }
Victor Stinner6036e442015-03-08 01:58:04 +010013115
13116 /* Loop till we get a non-dot directory or finish iterating */
13117 }
13118
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013119 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013120 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013121 return NULL;
13122}
13123
13124#else /* POSIX */
13125
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013126static int
13127ScandirIterator_is_closed(ScandirIterator *iterator)
13128{
13129 return !iterator->dirp;
13130}
13131
Victor Stinner6036e442015-03-08 01:58:04 +010013132static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013133ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013134{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013135 DIR *dirp = iterator->dirp;
13136
13137 if (!dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013138 return;
13139
Victor Stinner6036e442015-03-08 01:58:04 +010013140 iterator->dirp = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013141 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013142#ifdef HAVE_FDOPENDIR
13143 if (iterator->path.fd != -1)
13144 rewinddir(dirp);
13145#endif
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013146 closedir(dirp);
13147 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013148 return;
13149}
13150
13151static PyObject *
13152ScandirIterator_iternext(ScandirIterator *iterator)
13153{
13154 struct dirent *direntp;
13155 Py_ssize_t name_len;
13156 int is_dot;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013157 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013158
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013159 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013160 if (!iterator->dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013161 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013162
13163 while (1) {
13164 errno = 0;
13165 Py_BEGIN_ALLOW_THREADS
13166 direntp = readdir(iterator->dirp);
13167 Py_END_ALLOW_THREADS
13168
13169 if (!direntp) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013170 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013171 if (errno != 0)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013172 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013173 break;
13174 }
13175
13176 /* Skip over . and .. */
13177 name_len = NAMLEN(direntp);
13178 is_dot = direntp->d_name[0] == '.' &&
13179 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
13180 if (!is_dot) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013181 entry = DirEntry_from_posix_info(&iterator->path, direntp->d_name,
Victor Stinner35a97c02015-03-08 02:59:09 +010013182 name_len, direntp->d_ino
13183#ifdef HAVE_DIRENT_D_TYPE
13184 , direntp->d_type
13185#endif
13186 );
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013187 if (!entry)
13188 break;
13189 return entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013190 }
13191
13192 /* Loop till we get a non-dot directory or finish iterating */
13193 }
13194
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013195 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013196 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013197 return NULL;
13198}
13199
13200#endif
13201
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013202static PyObject *
13203ScandirIterator_close(ScandirIterator *self, PyObject *args)
13204{
13205 ScandirIterator_closedir(self);
13206 Py_RETURN_NONE;
13207}
13208
13209static PyObject *
13210ScandirIterator_enter(PyObject *self, PyObject *args)
13211{
13212 Py_INCREF(self);
13213 return self;
13214}
13215
13216static PyObject *
13217ScandirIterator_exit(ScandirIterator *self, PyObject *args)
13218{
13219 ScandirIterator_closedir(self);
13220 Py_RETURN_NONE;
13221}
13222
Victor Stinner6036e442015-03-08 01:58:04 +010013223static void
Victor Stinner7bfa4092016-03-23 00:43:54 +010013224ScandirIterator_finalize(ScandirIterator *iterator)
13225{
13226 PyObject *error_type, *error_value, *error_traceback;
13227
13228 /* Save the current exception, if any. */
13229 PyErr_Fetch(&error_type, &error_value, &error_traceback);
13230
13231 if (!ScandirIterator_is_closed(iterator)) {
13232 ScandirIterator_closedir(iterator);
13233
13234 if (PyErr_ResourceWarning((PyObject *)iterator, 1,
13235 "unclosed scandir iterator %R", iterator)) {
13236 /* Spurious errors can appear at shutdown */
13237 if (PyErr_ExceptionMatches(PyExc_Warning)) {
13238 PyErr_WriteUnraisable((PyObject *) iterator);
13239 }
13240 }
13241 }
13242
Victor Stinner7bfa4092016-03-23 00:43:54 +010013243 path_cleanup(&iterator->path);
13244
13245 /* Restore the saved exception. */
13246 PyErr_Restore(error_type, error_value, error_traceback);
13247}
13248
13249static void
Victor Stinner6036e442015-03-08 01:58:04 +010013250ScandirIterator_dealloc(ScandirIterator *iterator)
13251{
Eddie Elizondob3966632019-11-05 07:16:14 -080013252 PyTypeObject *tp = Py_TYPE(iterator);
Victor Stinner7bfa4092016-03-23 00:43:54 +010013253 if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
13254 return;
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013255
Eddie Elizondob3966632019-11-05 07:16:14 -080013256 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
13257 free_func(iterator);
13258 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010013259}
13260
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013261static PyMethodDef ScandirIterator_methods[] = {
13262 {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
13263 {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
13264 {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
13265 {NULL}
13266};
13267
Eddie Elizondob3966632019-11-05 07:16:14 -080013268static PyType_Slot ScandirIteratorType_slots[] = {
13269 {Py_tp_new, _disabled_new},
13270 {Py_tp_dealloc, ScandirIterator_dealloc},
13271 {Py_tp_finalize, ScandirIterator_finalize},
13272 {Py_tp_iter, PyObject_SelfIter},
13273 {Py_tp_iternext, ScandirIterator_iternext},
13274 {Py_tp_methods, ScandirIterator_methods},
13275 {0, 0},
13276};
13277
13278static PyType_Spec ScandirIteratorType_spec = {
13279 MODNAME ".ScandirIterator",
13280 sizeof(ScandirIterator),
13281 0,
13282 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE,
13283 ScandirIteratorType_slots
Victor Stinner6036e442015-03-08 01:58:04 +010013284};
13285
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013286/*[clinic input]
13287os.scandir
13288
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013289 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013290
13291Return an iterator of DirEntry objects for given path.
13292
BNMetricsb9427072018-11-02 15:20:19 +000013293path can be specified as either str, bytes, or a path-like object. If path
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013294is bytes, the names of yielded DirEntry objects will also be bytes; in
13295all other circumstances they will be str.
13296
13297If path is None, uses the path='.'.
13298[clinic start generated code]*/
13299
Victor Stinner6036e442015-03-08 01:58:04 +010013300static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013301os_scandir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +000013302/*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013303{
13304 ScandirIterator *iterator;
Victor Stinner6036e442015-03-08 01:58:04 +010013305#ifdef MS_WINDOWS
13306 wchar_t *path_strW;
13307#else
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013308 const char *path_str;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013309#ifdef HAVE_FDOPENDIR
13310 int fd = -1;
13311#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013312#endif
13313
Steve Dower60419a72019-06-24 08:42:54 -070013314 if (PySys_Audit("os.scandir", "O",
13315 path->object ? path->object : Py_None) < 0) {
13316 return NULL;
13317 }
13318
Eddie Elizondob3966632019-11-05 07:16:14 -080013319 PyObject *ScandirIteratorType = _posixstate(module)->ScandirIteratorType;
13320 iterator = PyObject_New(ScandirIterator, (PyTypeObject *)ScandirIteratorType);
Victor Stinner6036e442015-03-08 01:58:04 +010013321 if (!iterator)
13322 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013323
13324#ifdef MS_WINDOWS
13325 iterator->handle = INVALID_HANDLE_VALUE;
13326#else
13327 iterator->dirp = NULL;
13328#endif
13329
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013330 memcpy(&iterator->path, path, sizeof(path_t));
Serhiy Storchaka095ef732017-02-09 20:05:51 +020013331 /* Move the ownership to iterator->path */
13332 path->object = NULL;
13333 path->cleanup = NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013334
13335#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +010013336 iterator->first_time = 1;
13337
13338 path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
13339 if (!path_strW)
13340 goto error;
13341
13342 Py_BEGIN_ALLOW_THREADS
13343 iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
13344 Py_END_ALLOW_THREADS
13345
13346 PyMem_Free(path_strW);
13347
13348 if (iterator->handle == INVALID_HANDLE_VALUE) {
13349 path_error(&iterator->path);
13350 goto error;
13351 }
13352#else /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010013353 errno = 0;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013354#ifdef HAVE_FDOPENDIR
13355 if (path->fd != -1) {
13356 /* closedir() closes the FD, so we duplicate it */
13357 fd = _Py_dup(path->fd);
13358 if (fd == -1)
13359 goto error;
13360
13361 Py_BEGIN_ALLOW_THREADS
13362 iterator->dirp = fdopendir(fd);
13363 Py_END_ALLOW_THREADS
13364 }
13365 else
13366#endif
13367 {
13368 if (iterator->path.narrow)
13369 path_str = iterator->path.narrow;
13370 else
13371 path_str = ".";
13372
13373 Py_BEGIN_ALLOW_THREADS
13374 iterator->dirp = opendir(path_str);
13375 Py_END_ALLOW_THREADS
13376 }
Victor Stinner6036e442015-03-08 01:58:04 +010013377
13378 if (!iterator->dirp) {
13379 path_error(&iterator->path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013380#ifdef HAVE_FDOPENDIR
13381 if (fd != -1) {
13382 Py_BEGIN_ALLOW_THREADS
13383 close(fd);
13384 Py_END_ALLOW_THREADS
13385 }
13386#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013387 goto error;
13388 }
13389#endif
13390
13391 return (PyObject *)iterator;
13392
13393error:
13394 Py_DECREF(iterator);
13395 return NULL;
13396}
13397
Ethan Furman410ef8e2016-06-04 12:06:26 -070013398/*
13399 Return the file system path representation of the object.
13400
13401 If the object is str or bytes, then allow it to pass through with
13402 an incremented refcount. If the object defines __fspath__(), then
13403 return the result of that method. All other types raise a TypeError.
13404*/
13405PyObject *
13406PyOS_FSPath(PyObject *path)
13407{
Brett Cannon3f9183b2016-08-26 14:44:48 -070013408 /* For error message reasons, this function is manually inlined in
13409 path_converter(). */
Ethan Furman410ef8e2016-06-04 12:06:26 -070013410 PyObject *func = NULL;
13411 PyObject *path_repr = NULL;
13412
13413 if (PyUnicode_Check(path) || PyBytes_Check(path)) {
13414 Py_INCREF(path);
13415 return path;
13416 }
13417
13418 func = _PyObject_LookupSpecial(path, &PyId___fspath__);
13419 if (NULL == func) {
13420 return PyErr_Format(PyExc_TypeError,
13421 "expected str, bytes or os.PathLike object, "
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013422 "not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -080013423 _PyType_Name(Py_TYPE(path)));
Ethan Furman410ef8e2016-06-04 12:06:26 -070013424 }
13425
Victor Stinnerf17c3de2016-12-06 18:46:19 +010013426 path_repr = _PyObject_CallNoArg(func);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013427 Py_DECREF(func);
Brett Cannon044283a2016-07-15 10:41:49 -070013428 if (NULL == path_repr) {
13429 return NULL;
13430 }
13431
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013432 if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
13433 PyErr_Format(PyExc_TypeError,
13434 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -080013435 "not %.200s", _PyType_Name(Py_TYPE(path)),
13436 _PyType_Name(Py_TYPE(path_repr)));
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013437 Py_DECREF(path_repr);
13438 return NULL;
13439 }
13440
Ethan Furman410ef8e2016-06-04 12:06:26 -070013441 return path_repr;
13442}
13443
13444/*[clinic input]
13445os.fspath
13446
13447 path: object
13448
13449Return the file system path representation of the object.
13450
Brett Cannonb4f43e92016-06-09 14:32:08 -070013451If the object is str or bytes, then allow it to pass through as-is. If the
13452object defines __fspath__(), then return the result of that method. All other
13453types raise a TypeError.
Ethan Furman410ef8e2016-06-04 12:06:26 -070013454[clinic start generated code]*/
13455
13456static PyObject *
Serhiy Storchaka2954f832016-07-07 18:20:03 +030013457os_fspath_impl(PyObject *module, PyObject *path)
13458/*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
Ethan Furman410ef8e2016-06-04 12:06:26 -070013459{
13460 return PyOS_FSPath(path);
13461}
Victor Stinner6036e442015-03-08 01:58:04 +010013462
Victor Stinner9b1f4742016-09-06 16:18:52 -070013463#ifdef HAVE_GETRANDOM_SYSCALL
13464/*[clinic input]
13465os.getrandom
13466
13467 size: Py_ssize_t
13468 flags: int=0
13469
13470Obtain a series of random bytes.
13471[clinic start generated code]*/
13472
13473static PyObject *
13474os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
13475/*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
13476{
Victor Stinner9b1f4742016-09-06 16:18:52 -070013477 PyObject *bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013478 Py_ssize_t n;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013479
13480 if (size < 0) {
13481 errno = EINVAL;
13482 return posix_error();
13483 }
13484
Victor Stinnerec2319c2016-09-20 23:00:59 +020013485 bytes = PyBytes_FromStringAndSize(NULL, size);
13486 if (bytes == NULL) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013487 PyErr_NoMemory();
13488 return NULL;
13489 }
13490
13491 while (1) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013492 n = syscall(SYS_getrandom,
13493 PyBytes_AS_STRING(bytes),
13494 PyBytes_GET_SIZE(bytes),
13495 flags);
Victor Stinner9b1f4742016-09-06 16:18:52 -070013496 if (n < 0 && errno == EINTR) {
13497 if (PyErr_CheckSignals() < 0) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013498 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013499 }
Victor Stinnerec2319c2016-09-20 23:00:59 +020013500
13501 /* getrandom() was interrupted by a signal: retry */
Victor Stinner9b1f4742016-09-06 16:18:52 -070013502 continue;
13503 }
13504 break;
13505 }
13506
13507 if (n < 0) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013508 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerec2319c2016-09-20 23:00:59 +020013509 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013510 }
13511
Victor Stinnerec2319c2016-09-20 23:00:59 +020013512 if (n != size) {
13513 _PyBytes_Resize(&bytes, n);
13514 }
Victor Stinner9b1f4742016-09-06 16:18:52 -070013515
13516 return bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013517
13518error:
13519 Py_DECREF(bytes);
13520 return NULL;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013521}
13522#endif /* HAVE_GETRANDOM_SYSCALL */
13523
Steve Dower2438cdf2019-03-29 16:37:16 -070013524#ifdef MS_WINDOWS
13525/* bpo-36085: Helper functions for managing DLL search directories
13526 * on win32
13527 */
13528
13529typedef DLL_DIRECTORY_COOKIE (WINAPI *PAddDllDirectory)(PCWSTR newDirectory);
13530typedef BOOL (WINAPI *PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE cookie);
13531
13532/*[clinic input]
13533os._add_dll_directory
13534
13535 path: path_t
13536
13537Add a path to the DLL search path.
13538
13539This search path is used when resolving dependencies for imported
13540extension modules (the module itself is resolved through sys.path),
13541and also by ctypes.
13542
13543Returns an opaque value that may be passed to os.remove_dll_directory
13544to remove this directory from the search path.
13545[clinic start generated code]*/
13546
13547static PyObject *
13548os__add_dll_directory_impl(PyObject *module, path_t *path)
13549/*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
13550{
13551 HMODULE hKernel32;
13552 PAddDllDirectory AddDllDirectory;
13553 DLL_DIRECTORY_COOKIE cookie = 0;
13554 DWORD err = 0;
13555
13556 /* For Windows 7, we have to load this. As this will be a fairly
13557 infrequent operation, just do it each time. Kernel32 is always
13558 loaded. */
13559 Py_BEGIN_ALLOW_THREADS
13560 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13561 !(AddDllDirectory = (PAddDllDirectory)GetProcAddress(
13562 hKernel32, "AddDllDirectory")) ||
13563 !(cookie = (*AddDllDirectory)(path->wide))) {
13564 err = GetLastError();
13565 }
13566 Py_END_ALLOW_THREADS
13567
13568 if (err) {
13569 return win32_error_object_err("add_dll_directory",
13570 path->object, err);
13571 }
13572
13573 return PyCapsule_New(cookie, "DLL directory cookie", NULL);
13574}
13575
13576/*[clinic input]
13577os._remove_dll_directory
13578
13579 cookie: object
13580
13581Removes a path from the DLL search path.
13582
13583The parameter is an opaque value that was returned from
13584os.add_dll_directory. You can only remove directories that you added
13585yourself.
13586[clinic start generated code]*/
13587
13588static PyObject *
13589os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
13590/*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
13591{
13592 HMODULE hKernel32;
13593 PRemoveDllDirectory RemoveDllDirectory;
13594 DLL_DIRECTORY_COOKIE cookieValue;
13595 DWORD err = 0;
13596
13597 if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
13598 PyErr_SetString(PyExc_TypeError,
13599 "Provided cookie was not returned from os.add_dll_directory");
13600 return NULL;
13601 }
13602
13603 cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
13604 cookie, "DLL directory cookie");
13605
13606 /* For Windows 7, we have to load this. As this will be a fairly
13607 infrequent operation, just do it each time. Kernel32 is always
13608 loaded. */
13609 Py_BEGIN_ALLOW_THREADS
13610 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13611 !(RemoveDllDirectory = (PRemoveDllDirectory)GetProcAddress(
13612 hKernel32, "RemoveDllDirectory")) ||
13613 !(*RemoveDllDirectory)(cookieValue)) {
13614 err = GetLastError();
13615 }
13616 Py_END_ALLOW_THREADS
13617
13618 if (err) {
13619 return win32_error_object_err("remove_dll_directory",
13620 NULL, err);
13621 }
13622
13623 if (PyCapsule_SetName(cookie, NULL)) {
13624 return NULL;
13625 }
13626
13627 Py_RETURN_NONE;
13628}
13629
13630#endif
Larry Hastings31826802013-10-19 00:09:25 -070013631
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013632static PyMethodDef posix_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -070013633
13634 OS_STAT_METHODDEF
13635 OS_ACCESS_METHODDEF
13636 OS_TTYNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013637 OS_CHDIR_METHODDEF
13638 OS_CHFLAGS_METHODDEF
13639 OS_CHMOD_METHODDEF
13640 OS_FCHMOD_METHODDEF
13641 OS_LCHMOD_METHODDEF
13642 OS_CHOWN_METHODDEF
13643 OS_FCHOWN_METHODDEF
13644 OS_LCHOWN_METHODDEF
13645 OS_LCHFLAGS_METHODDEF
13646 OS_CHROOT_METHODDEF
13647 OS_CTERMID_METHODDEF
13648 OS_GETCWD_METHODDEF
13649 OS_GETCWDB_METHODDEF
13650 OS_LINK_METHODDEF
13651 OS_LISTDIR_METHODDEF
13652 OS_LSTAT_METHODDEF
13653 OS_MKDIR_METHODDEF
13654 OS_NICE_METHODDEF
13655 OS_GETPRIORITY_METHODDEF
13656 OS_SETPRIORITY_METHODDEF
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000013657 OS_POSIX_SPAWN_METHODDEF
Joannah Nanjekye92b83222019-01-16 16:29:26 +030013658 OS_POSIX_SPAWNP_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013659 OS_READLINK_METHODDEF
Pablo Galindoaac4d032019-05-31 19:39:47 +010013660 OS_COPY_FILE_RANGE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013661 OS_RENAME_METHODDEF
13662 OS_REPLACE_METHODDEF
13663 OS_RMDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013664 OS_SYMLINK_METHODDEF
13665 OS_SYSTEM_METHODDEF
13666 OS_UMASK_METHODDEF
13667 OS_UNAME_METHODDEF
13668 OS_UNLINK_METHODDEF
13669 OS_REMOVE_METHODDEF
13670 OS_UTIME_METHODDEF
13671 OS_TIMES_METHODDEF
13672 OS__EXIT_METHODDEF
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020013673 OS__FCOPYFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013674 OS_EXECV_METHODDEF
13675 OS_EXECVE_METHODDEF
13676 OS_SPAWNV_METHODDEF
13677 OS_SPAWNVE_METHODDEF
13678 OS_FORK1_METHODDEF
13679 OS_FORK_METHODDEF
Antoine Pitrou346cbd32017-05-27 17:50:54 +020013680 OS_REGISTER_AT_FORK_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013681 OS_SCHED_GET_PRIORITY_MAX_METHODDEF
13682 OS_SCHED_GET_PRIORITY_MIN_METHODDEF
13683 OS_SCHED_GETPARAM_METHODDEF
13684 OS_SCHED_GETSCHEDULER_METHODDEF
13685 OS_SCHED_RR_GET_INTERVAL_METHODDEF
13686 OS_SCHED_SETPARAM_METHODDEF
13687 OS_SCHED_SETSCHEDULER_METHODDEF
13688 OS_SCHED_YIELD_METHODDEF
13689 OS_SCHED_SETAFFINITY_METHODDEF
13690 OS_SCHED_GETAFFINITY_METHODDEF
13691 OS_OPENPTY_METHODDEF
13692 OS_FORKPTY_METHODDEF
13693 OS_GETEGID_METHODDEF
13694 OS_GETEUID_METHODDEF
13695 OS_GETGID_METHODDEF
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +020013696#ifdef HAVE_GETGROUPLIST
13697 {"getgrouplist", posix_getgrouplist, METH_VARARGS, posix_getgrouplist__doc__},
13698#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013699 OS_GETGROUPS_METHODDEF
13700 OS_GETPID_METHODDEF
13701 OS_GETPGRP_METHODDEF
13702 OS_GETPPID_METHODDEF
13703 OS_GETUID_METHODDEF
13704 OS_GETLOGIN_METHODDEF
13705 OS_KILL_METHODDEF
13706 OS_KILLPG_METHODDEF
13707 OS_PLOCK_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013708#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -070013709 OS_STARTFILE_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013710#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013711 OS_SETUID_METHODDEF
13712 OS_SETEUID_METHODDEF
13713 OS_SETREUID_METHODDEF
13714 OS_SETGID_METHODDEF
13715 OS_SETEGID_METHODDEF
13716 OS_SETREGID_METHODDEF
13717 OS_SETGROUPS_METHODDEF
Antoine Pitroub7572f02009-12-02 20:46:48 +000013718#ifdef HAVE_INITGROUPS
Victor Stinner8c62be82010-05-06 00:08:46 +000013719 {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__},
Antoine Pitroub7572f02009-12-02 20:46:48 +000013720#endif /* HAVE_INITGROUPS */
Larry Hastings2f936352014-08-05 14:04:04 +100013721 OS_GETPGID_METHODDEF
13722 OS_SETPGRP_METHODDEF
13723 OS_WAIT_METHODDEF
13724 OS_WAIT3_METHODDEF
13725 OS_WAIT4_METHODDEF
13726 OS_WAITID_METHODDEF
13727 OS_WAITPID_METHODDEF
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -080013728 OS_PIDFD_OPEN_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013729 OS_GETSID_METHODDEF
13730 OS_SETSID_METHODDEF
13731 OS_SETPGID_METHODDEF
13732 OS_TCGETPGRP_METHODDEF
13733 OS_TCSETPGRP_METHODDEF
13734 OS_OPEN_METHODDEF
13735 OS_CLOSE_METHODDEF
13736 OS_CLOSERANGE_METHODDEF
13737 OS_DEVICE_ENCODING_METHODDEF
13738 OS_DUP_METHODDEF
13739 OS_DUP2_METHODDEF
13740 OS_LOCKF_METHODDEF
13741 OS_LSEEK_METHODDEF
13742 OS_READ_METHODDEF
13743 OS_READV_METHODDEF
13744 OS_PREAD_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013745 OS_PREADV_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013746 OS_WRITE_METHODDEF
13747 OS_WRITEV_METHODDEF
13748 OS_PWRITE_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013749 OS_PWRITEV_METHODDEF
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013750#ifdef HAVE_SENDFILE
Serhiy Storchaka62be7422018-11-27 13:27:31 +020013751 {"sendfile", (PyCFunction)(void(*)(void))posix_sendfile, METH_VARARGS | METH_KEYWORDS,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013752 posix_sendfile__doc__},
13753#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013754 OS_FSTAT_METHODDEF
13755 OS_ISATTY_METHODDEF
13756 OS_PIPE_METHODDEF
13757 OS_PIPE2_METHODDEF
13758 OS_MKFIFO_METHODDEF
13759 OS_MKNOD_METHODDEF
13760 OS_MAJOR_METHODDEF
13761 OS_MINOR_METHODDEF
13762 OS_MAKEDEV_METHODDEF
13763 OS_FTRUNCATE_METHODDEF
13764 OS_TRUNCATE_METHODDEF
13765 OS_POSIX_FALLOCATE_METHODDEF
13766 OS_POSIX_FADVISE_METHODDEF
13767 OS_PUTENV_METHODDEF
13768 OS_UNSETENV_METHODDEF
13769 OS_STRERROR_METHODDEF
13770 OS_FCHDIR_METHODDEF
13771 OS_FSYNC_METHODDEF
13772 OS_SYNC_METHODDEF
13773 OS_FDATASYNC_METHODDEF
13774 OS_WCOREDUMP_METHODDEF
13775 OS_WIFCONTINUED_METHODDEF
13776 OS_WIFSTOPPED_METHODDEF
13777 OS_WIFSIGNALED_METHODDEF
13778 OS_WIFEXITED_METHODDEF
13779 OS_WEXITSTATUS_METHODDEF
13780 OS_WTERMSIG_METHODDEF
13781 OS_WSTOPSIG_METHODDEF
13782 OS_FSTATVFS_METHODDEF
13783 OS_STATVFS_METHODDEF
13784 OS_CONFSTR_METHODDEF
13785 OS_SYSCONF_METHODDEF
13786 OS_FPATHCONF_METHODDEF
13787 OS_PATHCONF_METHODDEF
13788 OS_ABORT_METHODDEF
Serhiy Storchakaf0b50152015-05-13 00:52:39 +030013789 OS__GETFULLPATHNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013790 OS__GETDISKUSAGE_METHODDEF
13791 OS__GETFINALPATHNAME_METHODDEF
13792 OS__GETVOLUMEPATHNAME_METHODDEF
13793 OS_GETLOADAVG_METHODDEF
13794 OS_URANDOM_METHODDEF
13795 OS_SETRESUID_METHODDEF
13796 OS_SETRESGID_METHODDEF
13797 OS_GETRESUID_METHODDEF
13798 OS_GETRESGID_METHODDEF
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000013799
Larry Hastings2f936352014-08-05 14:04:04 +100013800 OS_GETXATTR_METHODDEF
13801 OS_SETXATTR_METHODDEF
13802 OS_REMOVEXATTR_METHODDEF
13803 OS_LISTXATTR_METHODDEF
13804
Antoine Pitroubcf2b592012-02-08 23:28:36 +010013805#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
13806 {"get_terminal_size", get_terminal_size, METH_VARARGS, termsize__doc__},
13807#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013808 OS_CPU_COUNT_METHODDEF
13809 OS_GET_INHERITABLE_METHODDEF
13810 OS_SET_INHERITABLE_METHODDEF
13811 OS_GET_HANDLE_INHERITABLE_METHODDEF
13812 OS_SET_HANDLE_INHERITABLE_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013813#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013814 OS_GET_BLOCKING_METHODDEF
13815 OS_SET_BLOCKING_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013816#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013817 OS_SCANDIR_METHODDEF
Ethan Furman410ef8e2016-06-04 12:06:26 -070013818 OS_FSPATH_METHODDEF
Victor Stinner9b1f4742016-09-06 16:18:52 -070013819 OS_GETRANDOM_METHODDEF
Zackery Spytz43fdbd22019-05-29 13:57:07 -060013820 OS_MEMFD_CREATE_METHODDEF
Steve Dower2438cdf2019-03-29 16:37:16 -070013821#ifdef MS_WINDOWS
13822 OS__ADD_DLL_DIRECTORY_METHODDEF
13823 OS__REMOVE_DLL_DIRECTORY_METHODDEF
13824#endif
Victor Stinner8c62be82010-05-06 00:08:46 +000013825 {NULL, NULL} /* Sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013826};
13827
Barry Warsaw4a342091996-12-19 23:50:02 +000013828static int
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013829all_ins(PyObject *m)
Barry Warsaw4a342091996-12-19 23:50:02 +000013830{
Guido van Rossum94f6f721999-01-06 18:42:14 +000013831#ifdef F_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013832 if (PyModule_AddIntMacro(m, F_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013833#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013834#ifdef R_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013835 if (PyModule_AddIntMacro(m, R_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013836#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013837#ifdef W_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013838 if (PyModule_AddIntMacro(m, W_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013839#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013840#ifdef X_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013841 if (PyModule_AddIntMacro(m, X_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013842#endif
Fred Drakec9680921999-12-13 16:37:25 +000013843#ifdef NGROUPS_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013844 if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
Fred Drakec9680921999-12-13 16:37:25 +000013845#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013846#ifdef TMP_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013847 if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013848#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013849#ifdef WCONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013850 if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013851#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013852#ifdef WNOHANG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013853 if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013854#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013855#ifdef WUNTRACED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013856 if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013857#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013858#ifdef O_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013859 if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013860#endif
13861#ifdef O_WRONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013862 if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013863#endif
13864#ifdef O_RDWR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013865 if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013866#endif
13867#ifdef O_NDELAY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013868 if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013869#endif
13870#ifdef O_NONBLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013871 if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013872#endif
13873#ifdef O_APPEND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013874 if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013875#endif
13876#ifdef O_DSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013877 if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013878#endif
13879#ifdef O_RSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013880 if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013881#endif
13882#ifdef O_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013883 if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013884#endif
13885#ifdef O_NOCTTY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013886 if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013887#endif
13888#ifdef O_CREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013889 if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013890#endif
13891#ifdef O_EXCL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013892 if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013893#endif
13894#ifdef O_TRUNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013895 if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013896#endif
Guido van Rossum98d9d091997-08-08 21:48:51 +000013897#ifdef O_BINARY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013898 if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013899#endif
13900#ifdef O_TEXT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013901 if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013902#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013903#ifdef O_XATTR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013904 if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013905#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013906#ifdef O_LARGEFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013907 if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013908#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013909#ifndef __GNU__
Skip Montanaro5ff14922005-05-16 02:42:22 +000013910#ifdef O_SHLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013911 if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013912#endif
13913#ifdef O_EXLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013914 if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013915#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013916#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013917#ifdef O_EXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013918 if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013919#endif
13920#ifdef O_SEARCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013921 if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013922#endif
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013923#ifdef O_PATH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013924 if (PyModule_AddIntMacro(m, O_PATH)) return -1;
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013925#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013926#ifdef O_TTY_INIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013927 if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013928#endif
Christian Heimes177b3f92013-08-16 14:35:09 +020013929#ifdef O_TMPFILE
13930 if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
13931#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013932#ifdef PRIO_PROCESS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013933 if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013934#endif
13935#ifdef PRIO_PGRP
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013936 if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013937#endif
13938#ifdef PRIO_USER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013939 if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013940#endif
Charles-François Natali1e045b12011-05-22 20:42:32 +020013941#ifdef O_CLOEXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013942 if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
Charles-François Natali1e045b12011-05-22 20:42:32 +020013943#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013944#ifdef O_ACCMODE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013945 if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013946#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013947
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013948
Jesus Cea94363612012-06-22 18:32:07 +020013949#ifdef SEEK_HOLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013950 if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013951#endif
13952#ifdef SEEK_DATA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013953 if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013954#endif
13955
Tim Peters5aa91602002-01-30 05:46:57 +000013956/* MS Windows */
13957#ifdef O_NOINHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000013958 /* Don't inherit in child processes. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013959 if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013960#endif
13961#ifdef _O_SHORT_LIVED
Victor Stinner8c62be82010-05-06 00:08:46 +000013962 /* Optimize for short life (keep in memory). */
13963 /* MS forgot to define this one with a non-underscore form too. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013964 if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013965#endif
13966#ifdef O_TEMPORARY
Victor Stinner8c62be82010-05-06 00:08:46 +000013967 /* Automatically delete when last handle is closed. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013968 if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013969#endif
13970#ifdef O_RANDOM
Victor Stinner8c62be82010-05-06 00:08:46 +000013971 /* Optimize for random access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013972 if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013973#endif
13974#ifdef O_SEQUENTIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000013975 /* Optimize for sequential access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013976 if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013977#endif
13978
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013979/* GNU extensions. */
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013980#ifdef O_ASYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000013981 /* Send a SIGIO signal whenever input or output
13982 becomes available on file descriptor */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013983 if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013984#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013985#ifdef O_DIRECT
Victor Stinner8c62be82010-05-06 00:08:46 +000013986 /* Direct disk access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013987 if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013988#endif
13989#ifdef O_DIRECTORY
Victor Stinner8c62be82010-05-06 00:08:46 +000013990 /* Must be a directory. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013991 if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013992#endif
13993#ifdef O_NOFOLLOW
Victor Stinner8c62be82010-05-06 00:08:46 +000013994 /* Do not follow links. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013995 if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013996#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013997#ifdef O_NOLINKS
13998 /* Fails if link count of the named file is greater than 1 */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013999 if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020014000#endif
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000014001#ifdef O_NOATIME
Victor Stinner8c62be82010-05-06 00:08:46 +000014002 /* Do not update the access time. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014003 if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000014004#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +000014005
Victor Stinner8c62be82010-05-06 00:08:46 +000014006 /* These come from sysexits.h */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014007#ifdef EX_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014008 if (PyModule_AddIntMacro(m, EX_OK)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014009#endif /* EX_OK */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014010#ifdef EX_USAGE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014011 if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014012#endif /* EX_USAGE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014013#ifdef EX_DATAERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014014 if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014015#endif /* EX_DATAERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014016#ifdef EX_NOINPUT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014017 if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014018#endif /* EX_NOINPUT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014019#ifdef EX_NOUSER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014020 if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014021#endif /* EX_NOUSER */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014022#ifdef EX_NOHOST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014023 if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014024#endif /* EX_NOHOST */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014025#ifdef EX_UNAVAILABLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014026 if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014027#endif /* EX_UNAVAILABLE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014028#ifdef EX_SOFTWARE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014029 if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014030#endif /* EX_SOFTWARE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014031#ifdef EX_OSERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014032 if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014033#endif /* EX_OSERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014034#ifdef EX_OSFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014035 if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014036#endif /* EX_OSFILE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014037#ifdef EX_CANTCREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014038 if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014039#endif /* EX_CANTCREAT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014040#ifdef EX_IOERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014041 if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014042#endif /* EX_IOERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014043#ifdef EX_TEMPFAIL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014044 if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014045#endif /* EX_TEMPFAIL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014046#ifdef EX_PROTOCOL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014047 if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014048#endif /* EX_PROTOCOL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014049#ifdef EX_NOPERM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014050 if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014051#endif /* EX_NOPERM */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014052#ifdef EX_CONFIG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014053 if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014054#endif /* EX_CONFIG */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014055#ifdef EX_NOTFOUND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014056 if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014057#endif /* EX_NOTFOUND */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014058
Amaury Forgeot d'Arc66d00ad2010-09-10 18:11:45 +000014059 /* statvfs */
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014060#ifdef ST_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014061 if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014062#endif /* ST_RDONLY */
14063#ifdef ST_NOSUID
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014064 if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014065#endif /* ST_NOSUID */
14066
doko@ubuntu.comca616a22013-12-08 15:23:07 +010014067 /* GNU extensions */
14068#ifdef ST_NODEV
14069 if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
14070#endif /* ST_NODEV */
14071#ifdef ST_NOEXEC
14072 if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
14073#endif /* ST_NOEXEC */
14074#ifdef ST_SYNCHRONOUS
14075 if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
14076#endif /* ST_SYNCHRONOUS */
14077#ifdef ST_MANDLOCK
14078 if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
14079#endif /* ST_MANDLOCK */
14080#ifdef ST_WRITE
14081 if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
14082#endif /* ST_WRITE */
14083#ifdef ST_APPEND
14084 if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
14085#endif /* ST_APPEND */
14086#ifdef ST_NOATIME
14087 if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
14088#endif /* ST_NOATIME */
14089#ifdef ST_NODIRATIME
14090 if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
14091#endif /* ST_NODIRATIME */
14092#ifdef ST_RELATIME
14093 if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
14094#endif /* ST_RELATIME */
14095
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014096 /* FreeBSD sendfile() constants */
14097#ifdef SF_NODISKIO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014098 if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014099#endif
14100#ifdef SF_MNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014101 if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014102#endif
14103#ifdef SF_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014104 if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014105#endif
14106
Ross Lagerwall7807c352011-03-17 20:20:30 +020014107 /* constants for posix_fadvise */
14108#ifdef POSIX_FADV_NORMAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014109 if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014110#endif
14111#ifdef POSIX_FADV_SEQUENTIAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014112 if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014113#endif
14114#ifdef POSIX_FADV_RANDOM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014115 if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014116#endif
14117#ifdef POSIX_FADV_NOREUSE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014118 if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014119#endif
14120#ifdef POSIX_FADV_WILLNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014121 if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014122#endif
14123#ifdef POSIX_FADV_DONTNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014124 if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014125#endif
14126
14127 /* constants for waitid */
14128#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014129 if (PyModule_AddIntMacro(m, P_PID)) return -1;
14130 if (PyModule_AddIntMacro(m, P_PGID)) return -1;
14131 if (PyModule_AddIntMacro(m, P_ALL)) return -1;
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080014132#ifdef P_PIDFD
14133 if (PyModule_AddIntMacro(m, P_PIDFD)) return -1;
14134#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014135#endif
14136#ifdef WEXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014137 if (PyModule_AddIntMacro(m, WEXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014138#endif
14139#ifdef WNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014140 if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014141#endif
14142#ifdef WSTOPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014143 if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014144#endif
14145#ifdef CLD_EXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014146 if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014147#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014148#ifdef CLD_KILLED
14149 if (PyModule_AddIntMacro(m, CLD_KILLED)) return -1;
14150#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014151#ifdef CLD_DUMPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014152 if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014153#endif
14154#ifdef CLD_TRAPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014155 if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014156#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014157#ifdef CLD_STOPPED
14158 if (PyModule_AddIntMacro(m, CLD_STOPPED)) return -1;
14159#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014160#ifdef CLD_CONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014161 if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014162#endif
14163
14164 /* constants for lockf */
14165#ifdef F_LOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014166 if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014167#endif
14168#ifdef F_TLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014169 if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014170#endif
14171#ifdef F_ULOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014172 if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014173#endif
14174#ifdef F_TEST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014175 if (PyModule_AddIntMacro(m, F_TEST)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014176#endif
14177
Pablo Galindo4defba32018-01-27 16:16:37 +000014178#ifdef RWF_DSYNC
14179 if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
14180#endif
14181#ifdef RWF_HIPRI
14182 if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
14183#endif
14184#ifdef RWF_SYNC
14185 if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
14186#endif
14187#ifdef RWF_NOWAIT
14188 if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
14189#endif
14190
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000014191/* constants for posix_spawn */
14192#ifdef HAVE_POSIX_SPAWN
14193 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
14194 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
14195 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
14196#endif
14197
pxinwrf2d7ac72019-05-21 18:46:37 +080014198#if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014199 if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
14200 if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014201 if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
pxinwrf2d7ac72019-05-21 18:46:37 +080014202#endif
14203#ifdef HAVE_SPAWNV
14204 if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014205 if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
Guido van Rossum246bc171999-02-01 23:54:31 +000014206#endif
14207
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014208#ifdef HAVE_SCHED_H
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014209#ifdef SCHED_OTHER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014210 if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014211#endif
14212#ifdef SCHED_FIFO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014213 if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014214#endif
14215#ifdef SCHED_RR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014216 if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014217#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014218#ifdef SCHED_SPORADIC
messi Liao0d322182017-06-13 22:30:43 +080014219 if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014220#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014221#ifdef SCHED_BATCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014222 if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014223#endif
14224#ifdef SCHED_IDLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014225 if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014226#endif
14227#ifdef SCHED_RESET_ON_FORK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014228 if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014229#endif
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014230#ifdef SCHED_SYS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014231 if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014232#endif
14233#ifdef SCHED_IA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014234 if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014235#endif
14236#ifdef SCHED_FSS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014237 if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014238#endif
14239#ifdef SCHED_FX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014240 if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014241#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014242#endif
14243
Benjamin Peterson9428d532011-09-14 11:45:52 -040014244#ifdef USE_XATTRS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014245 if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
14246 if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
14247 if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
Benjamin Peterson799bd802011-08-31 22:15:17 -040014248#endif
14249
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014250#if HAVE_DECL_RTLD_LAZY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014251 if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014252#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014253#if HAVE_DECL_RTLD_NOW
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014254 if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014255#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014256#if HAVE_DECL_RTLD_GLOBAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014257 if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014258#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014259#if HAVE_DECL_RTLD_LOCAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014260 if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014261#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014262#if HAVE_DECL_RTLD_NODELETE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014263 if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014264#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014265#if HAVE_DECL_RTLD_NOLOAD
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014266 if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014267#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014268#if HAVE_DECL_RTLD_DEEPBIND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014269 if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014270#endif
Michael Feltc5ae1692017-12-19 13:58:49 +010014271#if HAVE_DECL_RTLD_MEMBER
14272 if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
14273#endif
Victor Stinner8b905bd2011-10-25 13:34:04 +020014274
Victor Stinner9b1f4742016-09-06 16:18:52 -070014275#ifdef HAVE_GETRANDOM_SYSCALL
14276 if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
14277 if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
14278#endif
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014279#ifdef HAVE_MEMFD_CREATE
14280 if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
14281 if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
14282#ifdef MFD_HUGETLB
14283 if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014284#endif
14285#ifdef MFD_HUGE_SHIFT
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014286 if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014287#endif
14288#ifdef MFD_HUGE_MASK
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014289 if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014290#endif
14291#ifdef MFD_HUGE_64KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014292 if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014293#endif
14294#ifdef MFD_HUGE_512KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014295 if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014296#endif
14297#ifdef MFD_HUGE_1MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014298 if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014299#endif
14300#ifdef MFD_HUGE_2MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014301 if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014302#endif
14303#ifdef MFD_HUGE_8MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014304 if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014305#endif
14306#ifdef MFD_HUGE_16MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014307 if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014308#endif
14309#ifdef MFD_HUGE_32MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014310 if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014311#endif
14312#ifdef MFD_HUGE_256MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014313 if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014314#endif
14315#ifdef MFD_HUGE_512MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014316 if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014317#endif
14318#ifdef MFD_HUGE_1GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014319 if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014320#endif
14321#ifdef MFD_HUGE_2GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014322 if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014323#endif
14324#ifdef MFD_HUGE_16GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014325 if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
14326#endif
14327#endif
Victor Stinner9b1f4742016-09-06 16:18:52 -070014328
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020014329#if defined(__APPLE__)
14330 if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
14331#endif
14332
Steve Dower2438cdf2019-03-29 16:37:16 -070014333#ifdef MS_WINDOWS
14334 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
14335 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
14336 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
14337 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
14338 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
14339#endif
14340
Victor Stinner8c62be82010-05-06 00:08:46 +000014341 return 0;
Barry Warsaw4a342091996-12-19 23:50:02 +000014342}
14343
14344
Martin v. Löwis1a214512008-06-11 05:26:20 +000014345static struct PyModuleDef posixmodule = {
Victor Stinner8c62be82010-05-06 00:08:46 +000014346 PyModuleDef_HEAD_INIT,
14347 MODNAME,
14348 posix__doc__,
Eddie Elizondob3966632019-11-05 07:16:14 -080014349 sizeof(_posixstate),
Victor Stinner8c62be82010-05-06 00:08:46 +000014350 posix_methods,
14351 NULL,
Eddie Elizondob3966632019-11-05 07:16:14 -080014352 _posix_traverse,
14353 _posix_clear,
14354 _posix_free,
Martin v. Löwis1a214512008-06-11 05:26:20 +000014355};
14356
14357
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014358static const char * const have_functions[] = {
Larry Hastings9cf065c2012-06-22 16:30:09 -070014359
14360#ifdef HAVE_FACCESSAT
14361 "HAVE_FACCESSAT",
14362#endif
14363
14364#ifdef HAVE_FCHDIR
14365 "HAVE_FCHDIR",
14366#endif
14367
14368#ifdef HAVE_FCHMOD
14369 "HAVE_FCHMOD",
14370#endif
14371
14372#ifdef HAVE_FCHMODAT
14373 "HAVE_FCHMODAT",
14374#endif
14375
14376#ifdef HAVE_FCHOWN
14377 "HAVE_FCHOWN",
14378#endif
14379
Larry Hastings00964ed2013-08-12 13:49:30 -040014380#ifdef HAVE_FCHOWNAT
14381 "HAVE_FCHOWNAT",
14382#endif
14383
Larry Hastings9cf065c2012-06-22 16:30:09 -070014384#ifdef HAVE_FEXECVE
14385 "HAVE_FEXECVE",
14386#endif
14387
14388#ifdef HAVE_FDOPENDIR
14389 "HAVE_FDOPENDIR",
14390#endif
14391
Georg Brandl306336b2012-06-24 12:55:33 +020014392#ifdef HAVE_FPATHCONF
14393 "HAVE_FPATHCONF",
14394#endif
14395
Larry Hastings9cf065c2012-06-22 16:30:09 -070014396#ifdef HAVE_FSTATAT
14397 "HAVE_FSTATAT",
14398#endif
14399
14400#ifdef HAVE_FSTATVFS
14401 "HAVE_FSTATVFS",
14402#endif
14403
Steve Dowerfe0a41a2015-03-20 19:50:46 -070014404#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Georg Brandl306336b2012-06-24 12:55:33 +020014405 "HAVE_FTRUNCATE",
14406#endif
14407
Larry Hastings9cf065c2012-06-22 16:30:09 -070014408#ifdef HAVE_FUTIMENS
14409 "HAVE_FUTIMENS",
14410#endif
14411
14412#ifdef HAVE_FUTIMES
14413 "HAVE_FUTIMES",
14414#endif
14415
14416#ifdef HAVE_FUTIMESAT
14417 "HAVE_FUTIMESAT",
14418#endif
14419
14420#ifdef HAVE_LINKAT
14421 "HAVE_LINKAT",
14422#endif
14423
14424#ifdef HAVE_LCHFLAGS
14425 "HAVE_LCHFLAGS",
14426#endif
14427
14428#ifdef HAVE_LCHMOD
14429 "HAVE_LCHMOD",
14430#endif
14431
14432#ifdef HAVE_LCHOWN
14433 "HAVE_LCHOWN",
14434#endif
14435
14436#ifdef HAVE_LSTAT
14437 "HAVE_LSTAT",
14438#endif
14439
14440#ifdef HAVE_LUTIMES
14441 "HAVE_LUTIMES",
14442#endif
14443
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014444#ifdef HAVE_MEMFD_CREATE
14445 "HAVE_MEMFD_CREATE",
14446#endif
14447
Larry Hastings9cf065c2012-06-22 16:30:09 -070014448#ifdef HAVE_MKDIRAT
14449 "HAVE_MKDIRAT",
14450#endif
14451
14452#ifdef HAVE_MKFIFOAT
14453 "HAVE_MKFIFOAT",
14454#endif
14455
14456#ifdef HAVE_MKNODAT
14457 "HAVE_MKNODAT",
14458#endif
14459
14460#ifdef HAVE_OPENAT
14461 "HAVE_OPENAT",
14462#endif
14463
14464#ifdef HAVE_READLINKAT
14465 "HAVE_READLINKAT",
14466#endif
14467
14468#ifdef HAVE_RENAMEAT
14469 "HAVE_RENAMEAT",
14470#endif
14471
14472#ifdef HAVE_SYMLINKAT
14473 "HAVE_SYMLINKAT",
14474#endif
14475
14476#ifdef HAVE_UNLINKAT
14477 "HAVE_UNLINKAT",
14478#endif
14479
14480#ifdef HAVE_UTIMENSAT
14481 "HAVE_UTIMENSAT",
14482#endif
14483
14484#ifdef MS_WINDOWS
14485 "MS_WINDOWS",
14486#endif
14487
14488 NULL
14489};
14490
14491
Mark Hammondfe51c6d2002-08-02 02:27:13 +000014492PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +000014493INITFUNC(void)
Guido van Rossumb6775db1994-08-01 11:34:53 +000014494{
Victor Stinner8c62be82010-05-06 00:08:46 +000014495 PyObject *m, *v;
Larry Hastings9cf065c2012-06-22 16:30:09 -070014496 PyObject *list;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014497 const char * const *trace;
Tim Peters5aa91602002-01-30 05:46:57 +000014498
Eddie Elizondob3966632019-11-05 07:16:14 -080014499 m = PyState_FindModule(&posixmodule);
14500 if (m != NULL) {
14501 Py_INCREF(m);
14502 return m;
14503 }
14504
Victor Stinner8c62be82010-05-06 00:08:46 +000014505 m = PyModule_Create(&posixmodule);
14506 if (m == NULL)
14507 return NULL;
Tim Peters5aa91602002-01-30 05:46:57 +000014508
Victor Stinner8c62be82010-05-06 00:08:46 +000014509 /* Initialize environ dictionary */
14510 v = convertenviron();
14511 Py_XINCREF(v);
14512 if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
14513 return NULL;
14514 Py_DECREF(v);
Fred Drakec9680921999-12-13 16:37:25 +000014515
Victor Stinner8c62be82010-05-06 00:08:46 +000014516 if (all_ins(m))
14517 return NULL;
Barry Warsaw4a342091996-12-19 23:50:02 +000014518
Victor Stinner8c62be82010-05-06 00:08:46 +000014519 if (setup_confname_tables(m))
14520 return NULL;
Fred Drakebec628d1999-12-15 18:31:10 +000014521
Victor Stinner8c62be82010-05-06 00:08:46 +000014522 Py_INCREF(PyExc_OSError);
14523 PyModule_AddObject(m, "error", PyExc_OSError);
Fred Drake762e2061999-08-26 17:23:54 +000014524
Victor Stinner623ed612020-01-21 19:25:32 +010014525#ifdef PY_PUTENV_DICT
Eddie Elizondob3966632019-11-05 07:16:14 -080014526 /* Save putenv() parameters as values here, so we can collect them when they
14527 * get re-set with another call for the same key. */
Victor Stinner623ed612020-01-21 19:25:32 +010014528 _posixstate(m)->putenv_dict = PyDict_New();
Guido van Rossumb3d39562000-01-31 18:41:26 +000014529#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +000014530
Ross Lagerwall7807c352011-03-17 20:20:30 +020014531#if defined(HAVE_WAITID) && !defined(__APPLE__)
Eddie Elizondob3966632019-11-05 07:16:14 -080014532 waitid_result_desc.name = MODNAME ".waitid_result";
14533 PyObject *WaitidResultType = (PyObject *)PyStructSequence_NewType(&waitid_result_desc);
14534 if (WaitidResultType == NULL) {
14535 return NULL;
14536 }
14537 Py_INCREF(WaitidResultType);
14538 PyModule_AddObject(m, "waitid_result", WaitidResultType);
14539 _posixstate(m)->WaitidResultType = WaitidResultType;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014540#endif
14541
Eddie Elizondob3966632019-11-05 07:16:14 -080014542 stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
14543 stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
14544 stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
14545 stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
14546 PyObject *StatResultType = (PyObject *)PyStructSequence_NewType(&stat_result_desc);
14547 if (StatResultType == NULL) {
14548 return NULL;
14549 }
14550 Py_INCREF(StatResultType);
14551 PyModule_AddObject(m, "stat_result", StatResultType);
14552 _posixstate(m)->StatResultType = StatResultType;
14553 structseq_new = ((PyTypeObject *)StatResultType)->tp_new;
14554 ((PyTypeObject *)StatResultType)->tp_new = statresult_new;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014555
Eddie Elizondob3966632019-11-05 07:16:14 -080014556 statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
14557 PyObject *StatVFSResultType = (PyObject *)PyStructSequence_NewType(&statvfs_result_desc);
14558 if (StatVFSResultType == NULL) {
14559 return NULL;
14560 }
14561 Py_INCREF(StatVFSResultType);
14562 PyModule_AddObject(m, "statvfs_result", StatVFSResultType);
14563 _posixstate(m)->StatVFSResultType = StatVFSResultType;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014564#ifdef NEED_TICKS_PER_SECOND
14565# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Eddie Elizondob3966632019-11-05 07:16:14 -080014566 ticks_per_second = sysconf(_SC_CLK_TCK);
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014567# elif defined(HZ)
Eddie Elizondob3966632019-11-05 07:16:14 -080014568 ticks_per_second = HZ;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014569# else
Eddie Elizondob3966632019-11-05 07:16:14 -080014570 ticks_per_second = 60; /* magic fallback value; may be bogus */
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014571# endif
14572#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014573
William Orr81574b82018-10-01 22:19:56 -070014574#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Eddie Elizondob3966632019-11-05 07:16:14 -080014575 sched_param_desc.name = MODNAME ".sched_param";
14576 PyObject *SchedParamType = (PyObject *)PyStructSequence_NewType(&sched_param_desc);
14577 if (SchedParamType == NULL) {
14578 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000014579 }
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014580 Py_INCREF(SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -080014581 PyModule_AddObject(m, "sched_param", SchedParamType);
14582 _posixstate(m)->SchedParamType = SchedParamType;
14583 ((PyTypeObject *)SchedParamType)->tp_new = os_sched_param;
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014584#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +000014585
Eddie Elizondob3966632019-11-05 07:16:14 -080014586 /* initialize TerminalSize_info */
14587 PyObject *TerminalSizeType = (PyObject *)PyStructSequence_NewType(&TerminalSize_desc);
14588 if (TerminalSizeType == NULL) {
14589 return NULL;
14590 }
14591 Py_INCREF(TerminalSizeType);
14592 PyModule_AddObject(m, "terminal_size", TerminalSizeType);
14593 _posixstate(m)->TerminalSizeType = TerminalSizeType;
14594
14595 /* initialize scandir types */
14596 PyObject *ScandirIteratorType = PyType_FromSpec(&ScandirIteratorType_spec);
14597 if (ScandirIteratorType == NULL) {
14598 return NULL;
14599 }
14600 _posixstate(m)->ScandirIteratorType = ScandirIteratorType;
14601
14602 PyObject *DirEntryType = PyType_FromSpec(&DirEntryType_spec);
14603 if (DirEntryType == NULL) {
14604 return NULL;
14605 }
14606 Py_INCREF(DirEntryType);
14607 PyModule_AddObject(m, "DirEntry", DirEntryType);
14608 _posixstate(m)->DirEntryType = DirEntryType;
14609
Larry Hastings605a62d2012-06-24 04:33:36 -070014610 times_result_desc.name = MODNAME ".times_result";
Eddie Elizondob3966632019-11-05 07:16:14 -080014611 PyObject *TimesResultType = (PyObject *)PyStructSequence_NewType(&times_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014612 if (TimesResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014613 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014614 }
Eddie Elizondob3966632019-11-05 07:16:14 -080014615 Py_INCREF(TimesResultType);
14616 PyModule_AddObject(m, "times_result", TimesResultType);
14617 _posixstate(m)->TimesResultType = TimesResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070014618
Eddie Elizondob3966632019-11-05 07:16:14 -080014619 PyTypeObject *UnameResultType = PyStructSequence_NewType(&uname_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014620 if (UnameResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014621 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014622 }
Eddie Elizondob3966632019-11-05 07:16:14 -080014623 Py_INCREF(UnameResultType);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014624 PyModule_AddObject(m, "uname_result", (PyObject *)UnameResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -080014625 _posixstate(m)->UnameResultType = (PyObject *)UnameResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070014626
Thomas Wouters477c8d52006-05-27 19:21:47 +000014627#ifdef __APPLE__
Victor Stinner8c62be82010-05-06 00:08:46 +000014628 /*
14629 * Step 2 of weak-linking support on Mac OS X.
14630 *
14631 * The code below removes functions that are not available on the
14632 * currently active platform.
14633 *
14634 * This block allow one to use a python binary that was build on
Larry Hastings9cf065c2012-06-22 16:30:09 -070014635 * OSX 10.4 on OSX 10.3, without losing access to new APIs on
Victor Stinner8c62be82010-05-06 00:08:46 +000014636 * OSX 10.4.
14637 */
Thomas Wouters477c8d52006-05-27 19:21:47 +000014638#ifdef HAVE_FSTATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014639 if (fstatvfs == NULL) {
14640 if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
14641 return NULL;
14642 }
14643 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014644#endif /* HAVE_FSTATVFS */
14645
14646#ifdef HAVE_STATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014647 if (statvfs == NULL) {
14648 if (PyObject_DelAttrString(m, "statvfs") == -1) {
14649 return NULL;
14650 }
14651 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014652#endif /* HAVE_STATVFS */
14653
14654# ifdef HAVE_LCHOWN
Victor Stinner8c62be82010-05-06 00:08:46 +000014655 if (lchown == NULL) {
14656 if (PyObject_DelAttrString(m, "lchown") == -1) {
14657 return NULL;
14658 }
14659 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014660#endif /* HAVE_LCHOWN */
14661
14662
14663#endif /* __APPLE__ */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014664
Eddie Elizondob3966632019-11-05 07:16:14 -080014665 if ((_posixstate(m)->billion = PyLong_FromLong(1000000000)) == NULL)
14666 return NULL;
14667#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
14668 _posixstate(m)->struct_rusage = PyUnicode_InternFromString("struct_rusage");
14669 if (_posixstate(m)->struct_rusage == NULL)
14670 return NULL;
14671#endif
14672 _posixstate(m)->st_mode = PyUnicode_InternFromString("st_mode");
14673 if (_posixstate(m)->st_mode == NULL)
Larry Hastings6fe20b32012-04-19 15:07:49 -070014674 return NULL;
14675
Larry Hastings9cf065c2012-06-22 16:30:09 -070014676 /* suppress "function not used" warnings */
14677 {
14678 int ignored;
14679 fd_specified("", -1);
14680 follow_symlinks_specified("", 1);
14681 dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
14682 dir_fd_converter(Py_None, &ignored);
14683 dir_fd_unavailable(Py_None, &ignored);
14684 }
14685
14686 /*
14687 * provide list of locally available functions
14688 * so os.py can populate support_* lists
14689 */
14690 list = PyList_New(0);
14691 if (!list)
14692 return NULL;
14693 for (trace = have_functions; *trace; trace++) {
14694 PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
14695 if (!unicode)
14696 return NULL;
14697 if (PyList_Append(list, unicode))
14698 return NULL;
14699 Py_DECREF(unicode);
14700 }
14701 PyModule_AddObject(m, "_have_functions", list);
Ned Deilyeb3be662016-08-15 14:40:38 -040014702
Victor Stinner8c62be82010-05-06 00:08:46 +000014703 return m;
Guido van Rossumb6775db1994-08-01 11:34:53 +000014704}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014705
14706#ifdef __cplusplus
14707}
14708#endif