blob: b71eddf90b70e803e701475dd24d9885258ecd9c [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* POSIX module implementation */
3
Jesus Ceaab70e2a2012-10-05 01:48:08 +02004/* This file is also used for Windows NT/MS-Win. In that case the
5 module actually calls itself 'nt', not 'posix', and a few
Andrew MacIntyre6c73af22002-03-03 03:07:07 +00006 functions are either unimplemented or implemented differently. The source
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00007 assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent
Guido van Rossumad0ee831995-03-01 10:34:45 +00008 of the compiler used. Different compilers define their own feature
Victor Stinnerf427a142014-10-22 12:33:23 +02009 test macro, e.g. '_MSC_VER'. */
Guido van Rossumad0ee831995-03-01 10:34:45 +000010
Larry Hastings31826802013-10-19 00:09:25 -070011
12
Thomas Wouters477c8d52006-05-27 19:21:47 +000013#ifdef __APPLE__
14 /*
Victor Stinner8c62be82010-05-06 00:08:46 +000015 * Step 1 of support for weak-linking a number of symbols existing on
Thomas Wouters477c8d52006-05-27 19:21:47 +000016 * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block
17 * at the end of this file for more information.
18 */
19# pragma weak lchown
20# pragma weak statvfs
21# pragma weak fstatvfs
22
23#endif /* __APPLE__ */
24
Thomas Wouters68bc4f92006-03-01 01:05:10 +000025#define PY_SSIZE_T_CLEAN
26
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000027#include "Python.h"
Victor Stinnerd5d9e812019-05-13 12:35:37 +020028#ifdef MS_WINDOWS
29 /* include <windows.h> early to avoid conflict with pycore_condvar.h:
30
31 #define WIN32_LEAN_AND_MEAN
32 #include <windows.h>
33
34 FSCTL_GET_REPARSE_POINT is not exported with WIN32_LEAN_AND_MEAN. */
35# include <windows.h>
36#endif
37
38#include "pycore_ceval.h" /* _PyEval_ReInitThreads() */
Victor Stinner01b63ec2019-06-19 00:48:09 +020039#include "pycore_import.h" /* _PyImport_ReInitLock() */
Victor Stinnerd5d9e812019-05-13 12:35:37 +020040#include "pycore_pystate.h" /* _PyRuntime */
Antoine Pitrou346cbd32017-05-27 17:50:54 +020041#include "pythread.h"
Victor Stinner6036e442015-03-08 01:58:04 +010042#include "structmember.h"
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020043#ifndef MS_WINDOWS
Victor Stinnerd5d9e812019-05-13 12:35:37 +020044# include "posixmodule.h"
Tim Golden0321cf22014-05-05 19:46:17 +010045#else
Victor Stinnerd5d9e812019-05-13 12:35:37 +020046# include "winreparse.h"
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020047#endif
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000048
Stefan Krahfb7c8ae2016-04-26 17:04:18 +020049/* On android API level 21, 'AT_EACCESS' is not declared although
50 * HAVE_FACCESSAT is defined. */
51#ifdef __ANDROID__
52#undef HAVE_FACCESSAT
53#endif
54
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)fa76eee2016-05-28 21:03:48 +000055#include <stdio.h> /* needed for ctermid() */
56
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057#ifdef __cplusplus
58extern "C" {
59#endif
60
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000061PyDoc_STRVAR(posix__doc__,
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000062"This module provides access to operating system functionality that is\n\
63standardized by the C Standard and the POSIX standard (a thinly\n\
64disguised Unix interface). Refer to the library manual and\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000065corresponding Unix manual entries for more information on calls.");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000066
Martin v. Löwis0073f2e2002-11-21 23:52:35 +000067
Ross Lagerwall4d076da2011-03-18 06:56:53 +020068#ifdef HAVE_SYS_UIO_H
69#include <sys/uio.h>
70#endif
71
Christian Heimes75b96182017-09-05 15:53:09 +020072#ifdef HAVE_SYS_SYSMACROS_H
73/* GNU C Library: major(), minor(), makedev() */
74#include <sys/sysmacros.h>
75#endif
76
Thomas Wouters0e3f5912006-08-11 14:57:12 +000077#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000078#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000079#endif /* HAVE_SYS_TYPES_H */
80
81#ifdef HAVE_SYS_STAT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000082#include <sys/stat.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000083#endif /* HAVE_SYS_STAT_H */
Guido van Rossuma6535fd2001-10-18 19:44:10 +000084
Guido van Rossum36bc6801995-06-14 22:54:23 +000085#ifdef HAVE_SYS_WAIT_H
Victor Stinner8c62be82010-05-06 00:08:46 +000086#include <sys/wait.h> /* For WNOHANG */
Guido van Rossum36bc6801995-06-14 22:54:23 +000087#endif
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080088#ifdef HAVE_LINUX_WAIT_H
89#include <linux/wait.h> // For P_PIDFD
90#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +000091
Thomas Wouters0e3f5912006-08-11 14:57:12 +000092#ifdef HAVE_SIGNAL_H
Guido van Rossuma376cc51996-12-05 23:43:35 +000093#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000094#endif
Guido van Rossuma376cc51996-12-05 23:43:35 +000095
Guido van Rossumb6775db1994-08-01 11:34:53 +000096#ifdef HAVE_FCNTL_H
97#include <fcntl.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +000098#endif /* HAVE_FCNTL_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +000099
Guido van Rossuma6535fd2001-10-18 19:44:10 +0000100#ifdef HAVE_GRP_H
101#include <grp.h>
102#endif
103
Barry Warsaw5676bd12003-01-07 20:57:09 +0000104#ifdef HAVE_SYSEXITS_H
105#include <sysexits.h>
106#endif /* HAVE_SYSEXITS_H */
107
Anthony Baxter8a560de2004-10-13 15:30:56 +0000108#ifdef HAVE_SYS_LOADAVG_H
109#include <sys/loadavg.h>
110#endif
111
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000112#ifdef HAVE_SYS_SENDFILE_H
113#include <sys/sendfile.h>
114#endif
115
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +0200116#if defined(__APPLE__)
117#include <copyfile.h>
118#endif
119
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500120#ifdef HAVE_SCHED_H
121#include <sched.h>
122#endif
123
Pablo Galindoaac4d032019-05-31 19:39:47 +0100124#ifdef HAVE_COPY_FILE_RANGE
125#include <unistd.h>
126#endif
127
Benjamin Peterson2dbda072012-03-16 10:12:55 -0500128#if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
Benjamin Peterson7b51b8d2012-03-14 22:28:25 -0500129#undef HAVE_SCHED_SETAFFINITY
130#endif
131
doko@ubuntu.com4a173bc2014-04-17 19:47:16 +0200132#if defined(HAVE_SYS_XATTR_H) && defined(__GLIBC__) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
Benjamin Peterson9428d532011-09-14 11:45:52 -0400133#define USE_XATTRS
134#endif
135
136#ifdef USE_XATTRS
Benjamin Petersonb77fe172011-09-13 17:20:47 -0400137#include <sys/xattr.h>
Benjamin Peterson799bd802011-08-31 22:15:17 -0400138#endif
139
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000140#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
141#ifdef HAVE_SYS_SOCKET_H
142#include <sys/socket.h>
143#endif
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000144#endif
145
Victor Stinner8b905bd2011-10-25 13:34:04 +0200146#ifdef HAVE_DLFCN_H
147#include <dlfcn.h>
148#endif
149
Charles-Francois Natali44feda32013-05-20 14:40:46 +0200150#ifdef __hpux
151#include <sys/mpctl.h>
152#endif
153
154#if defined(__DragonFly__) || \
155 defined(__OpenBSD__) || \
156 defined(__FreeBSD__) || \
157 defined(__NetBSD__) || \
158 defined(__APPLE__)
159#include <sys/sysctl.h>
160#endif
161
Victor Stinner9b1f4742016-09-06 16:18:52 -0700162#ifdef HAVE_LINUX_RANDOM_H
163# include <linux/random.h>
164#endif
165#ifdef HAVE_GETRANDOM_SYSCALL
166# include <sys/syscall.h>
167#endif
168
Antoine Pitroubcf2b592012-02-08 23:28:36 +0100169#if defined(MS_WINDOWS)
170# define TERMSIZE_USE_CONIO
171#elif defined(HAVE_SYS_IOCTL_H)
172# include <sys/ioctl.h>
173# if defined(HAVE_TERMIOS_H)
174# include <termios.h>
175# endif
176# if defined(TIOCGWINSZ)
177# define TERMSIZE_USE_IOCTL
178# endif
179#endif /* MS_WINDOWS */
180
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000181/* Various compilers have only certain posix functions */
Martin v. Löwis4f1cd8b2001-07-26 13:41:06 +0000182/* XXX Gosh I wish these were all moved into pyconfig.h */
Victor Stinner8c62be82010-05-06 00:08:46 +0000183#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000184#define HAVE_OPENDIR 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000185#define HAVE_SYSTEM 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000186#include <process.h>
187#else
Victor Stinner8c62be82010-05-06 00:08:46 +0000188#ifdef _MSC_VER /* Microsoft compiler */
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +0000189#define HAVE_GETPPID 1
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000190#define HAVE_GETLOGIN 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000191#define HAVE_SPAWNV 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000192#define HAVE_EXECV 1
Steve Dowercc16be82016-09-08 10:35:16 -0700193#define HAVE_WSPAWNV 1
194#define HAVE_WEXECV 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000195#define HAVE_PIPE 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000196#define HAVE_SYSTEM 1
197#define HAVE_CWAIT 1
198#define HAVE_FSYNC 1
Tim Peters11b23062003-04-23 02:39:17 +0000199#define fsync _commit
Andrew MacIntyre6c73af22002-03-03 03:07:07 +0000200#else
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000201/* Unix functions that the configure script doesn't check for */
pxinwrf2d7ac72019-05-21 18:46:37 +0800202#ifndef __VXWORKS__
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000203#define HAVE_EXECV 1
204#define HAVE_FORK 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000205#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */
Guido van Rossum2242f2f2001-04-11 20:58:20 +0000206#define HAVE_FORK1 1
207#endif
pxinwrf2d7ac72019-05-21 18:46:37 +0800208#endif
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000209#define HAVE_GETEGID 1
210#define HAVE_GETEUID 1
211#define HAVE_GETGID 1
212#define HAVE_GETPPID 1
213#define HAVE_GETUID 1
214#define HAVE_KILL 1
215#define HAVE_OPENDIR 1
216#define HAVE_PIPE 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000217#define HAVE_SYSTEM 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000218#define HAVE_WAIT 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000219#define HAVE_TTYNAME 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000220#endif /* _MSC_VER */
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000221#endif /* ! __WATCOMC__ || __QNX__ */
Guido van Rossumad0ee831995-03-01 10:34:45 +0000222
Eddie Elizondob3966632019-11-05 07:16:14 -0800223_Py_IDENTIFIER(__fspath__);
Victor Stinnera2f7c002012-02-08 03:36:25 +0100224
Larry Hastings61272b72014-01-07 12:41:53 -0800225/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +1000226# one of the few times we lie about this name!
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800227module os
Larry Hastings61272b72014-01-07 12:41:53 -0800228[clinic start generated code]*/
Larry Hastings2f936352014-08-05 14:04:04 +1000229/*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
Victor Stinnera2f7c002012-02-08 03:36:25 +0100230
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000231#ifndef _MSC_VER
Guido van Rossum36bc6801995-06-14 22:54:23 +0000232
Martin v. Löwis8eb92a02002-09-19 08:03:21 +0000233#if defined(__sgi)&&_COMPILER_VERSION>=700
234/* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
235 (default) */
236extern char *ctermid_r(char *);
237#endif
238
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000239#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000240
pxinwrf2d7ac72019-05-21 18:46:37 +0800241#if defined(__VXWORKS__)
242#include <vxCpuLib.h>
243#include <rtpLib.h>
244#include <wait.h>
245#include <taskLib.h>
246#ifndef _P_WAIT
247#define _P_WAIT 0
248#define _P_NOWAIT 1
249#define _P_NOWAITO 1
250#endif
251#endif /* __VXWORKS__ */
252
Pablo Galindo6c6ddf92018-01-29 01:56:10 +0000253#ifdef HAVE_POSIX_SPAWN
254#include <spawn.h>
255#endif
256
Guido van Rossumb6775db1994-08-01 11:34:53 +0000257#ifdef HAVE_UTIME_H
258#include <utime.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000259#endif /* HAVE_UTIME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000260
Guido van Rossum14ed0b21994-09-29 09:50:09 +0000261#ifdef HAVE_SYS_UTIME_H
262#include <sys/utime.h>
263#define HAVE_UTIME_H /* pretend we do for the rest of this file */
264#endif /* HAVE_SYS_UTIME_H */
265
Guido van Rossumb6775db1994-08-01 11:34:53 +0000266#ifdef HAVE_SYS_TIMES_H
267#include <sys/times.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000268#endif /* HAVE_SYS_TIMES_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000269
270#ifdef HAVE_SYS_PARAM_H
271#include <sys/param.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000272#endif /* HAVE_SYS_PARAM_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000273
274#ifdef HAVE_SYS_UTSNAME_H
275#include <sys/utsname.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000276#endif /* HAVE_SYS_UTSNAME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000277
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000278#ifdef HAVE_DIRENT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000279#include <dirent.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000280#define NAMLEN(dirent) strlen((dirent)->d_name)
281#else
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000282#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000283#include <direct.h>
284#define NAMLEN(dirent) strlen((dirent)->d_name)
285#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000286#define dirent direct
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000287#define NAMLEN(dirent) (dirent)->d_namlen
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000288#endif
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000289#ifdef HAVE_SYS_NDIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000290#include <sys/ndir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000291#endif
292#ifdef HAVE_SYS_DIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000293#include <sys/dir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000294#endif
295#ifdef HAVE_NDIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000296#include <ndir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000297#endif
298#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000299
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000300#ifdef _MSC_VER
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000301#ifdef HAVE_DIRECT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000302#include <direct.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000303#endif
304#ifdef HAVE_IO_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000305#include <io.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000306#endif
307#ifdef HAVE_PROCESS_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000308#include <process.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000309#endif
Raymond Hettinger0291c9f2010-08-01 21:10:35 +0000310#ifndef IO_REPARSE_TAG_SYMLINK
Amaury Forgeot d'Arc844807e2010-08-16 22:16:51 +0000311#define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
Raymond Hettinger0291c9f2010-08-01 21:10:35 +0000312#endif
Tim Golden0321cf22014-05-05 19:46:17 +0100313#ifndef IO_REPARSE_TAG_MOUNT_POINT
314#define IO_REPARSE_TAG_MOUNT_POINT (0xA0000003L)
315#endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000316#include "osdefs.h"
Kristján Valur Jónssonf64e6512009-04-13 10:16:14 +0000317#include <malloc.h>
Guido van Rossumb6775db1994-08-01 11:34:53 +0000318#include <windows.h>
Victor Stinner8c62be82010-05-06 00:08:46 +0000319#include <shellapi.h> /* for ShellExecute() */
Brian Curtine8e4b3b2010-09-23 20:04:14 +0000320#include <lmcons.h> /* for UNLEN */
Brian Curtin52173d42010-12-02 18:29:18 +0000321#define HAVE_SYMLINK
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000322#endif /* _MSC_VER */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000323
Tim Petersbc2e10e2002-03-03 23:17:02 +0000324#ifndef MAXPATHLEN
Thomas Wouters477c8d52006-05-27 19:21:47 +0000325#if defined(PATH_MAX) && PATH_MAX > 1024
326#define MAXPATHLEN PATH_MAX
327#else
Tim Petersbc2e10e2002-03-03 23:17:02 +0000328#define MAXPATHLEN 1024
Thomas Wouters477c8d52006-05-27 19:21:47 +0000329#endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000330#endif /* MAXPATHLEN */
331
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000332#ifdef UNION_WAIT
333/* Emulate some macros on systems that have a union instead of macros */
334
335#ifndef WIFEXITED
336#define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
337#endif
338
339#ifndef WEXITSTATUS
340#define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
341#endif
342
343#ifndef WTERMSIG
344#define WTERMSIG(u_wait) ((u_wait).w_termsig)
345#endif
346
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000347#define WAIT_TYPE union wait
348#define WAIT_STATUS_INT(s) (s.w_status)
349
350#else /* !UNION_WAIT */
351#define WAIT_TYPE int
352#define WAIT_STATUS_INT(s) (s)
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000353#endif /* UNION_WAIT */
354
Greg Wardb48bc172000-03-01 21:51:56 +0000355/* Don't use the "_r" form if we don't need it (also, won't have a
356 prototype for it, at least on Solaris -- maybe others as well?). */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200357#if defined(HAVE_CTERMID_R)
Greg Wardb48bc172000-03-01 21:51:56 +0000358#define USE_CTERMID_R
359#endif
360
Fred Drake699f3522000-06-29 21:12:41 +0000361/* choose the appropriate stat and fstat functions and return structs */
Guido van Rossum64529cd2000-06-30 22:45:12 +0000362#undef STAT
Antoine Pitroue47e0932011-01-19 15:21:35 +0000363#undef FSTAT
364#undef STRUCT_STAT
Victor Stinner14b9b112013-06-25 00:37:25 +0200365#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +0000366# define STAT win32_stat
Larry Hastings9cf065c2012-06-22 16:30:09 -0700367# define LSTAT win32_lstat
Victor Stinnere134a7f2015-03-30 10:09:31 +0200368# define FSTAT _Py_fstat_noraise
Steve Dowerf2f373f2015-02-21 08:44:05 -0800369# define STRUCT_STAT struct _Py_stat_struct
Fred Drake699f3522000-06-29 21:12:41 +0000370#else
Victor Stinner8c62be82010-05-06 00:08:46 +0000371# define STAT stat
Larry Hastings9cf065c2012-06-22 16:30:09 -0700372# define LSTAT lstat
Victor Stinner8c62be82010-05-06 00:08:46 +0000373# define FSTAT fstat
374# define STRUCT_STAT struct stat
Fred Drake699f3522000-06-29 21:12:41 +0000375#endif
376
Tim Peters11b23062003-04-23 02:39:17 +0000377#if defined(MAJOR_IN_MKDEV)
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000378#include <sys/mkdev.h>
379#else
380#if defined(MAJOR_IN_SYSMACROS)
381#include <sys/sysmacros.h>
382#endif
Neal Norwitz3d949422002-04-20 13:46:43 +0000383#if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
384#include <sys/mkdev.h>
385#endif
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000386#endif
Fred Drake699f3522000-06-29 21:12:41 +0000387
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200388#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +0100389#define INITFUNC PyInit_nt
390#define MODNAME "nt"
391#else
392#define INITFUNC PyInit_posix
393#define MODNAME "posix"
394#endif
395
jcea6c51d512018-01-28 14:00:08 +0100396#if defined(__sun)
397/* Something to implement in autoconf, not present in autoconf 2.69 */
398#define HAVE_STRUCT_STAT_ST_FSTYPE 1
399#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200400
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600401/* memfd_create is either defined in sys/mman.h or sys/memfd.h
402 * linux/memfd.h defines additional flags
403 */
404#ifdef HAVE_SYS_MMAN_H
405#include <sys/mman.h>
406#endif
407#ifdef HAVE_SYS_MEMFD_H
408#include <sys/memfd.h>
409#endif
410#ifdef HAVE_LINUX_MEMFD_H
411#include <linux/memfd.h>
412#endif
413
Gregory P. Smith1d300ce2018-12-30 21:13:02 -0800414#ifdef _Py_MEMORY_SANITIZER
415# include <sanitizer/msan_interface.h>
416#endif
417
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200418#ifdef HAVE_FORK
419static void
420run_at_forkers(PyObject *lst, int reverse)
421{
422 Py_ssize_t i;
423 PyObject *cpy;
424
425 if (lst != NULL) {
426 assert(PyList_CheckExact(lst));
427
428 /* Use a list copy in case register_at_fork() is called from
429 * one of the callbacks.
430 */
431 cpy = PyList_GetSlice(lst, 0, PyList_GET_SIZE(lst));
432 if (cpy == NULL)
433 PyErr_WriteUnraisable(lst);
434 else {
435 if (reverse)
436 PyList_Reverse(cpy);
437 for (i = 0; i < PyList_GET_SIZE(cpy); i++) {
438 PyObject *func, *res;
439 func = PyList_GET_ITEM(cpy, i);
Jeroen Demeyer7f41c8e2019-07-04 12:35:31 +0200440 res = _PyObject_CallNoArg(func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200441 if (res == NULL)
442 PyErr_WriteUnraisable(func);
443 else
444 Py_DECREF(res);
445 }
446 Py_DECREF(cpy);
447 }
448 }
449}
450
451void
452PyOS_BeforeFork(void)
453{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200454 run_at_forkers(_PyInterpreterState_Get()->before_forkers, 1);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200455
456 _PyImport_AcquireLock();
457}
458
459void
460PyOS_AfterFork_Parent(void)
461{
462 if (_PyImport_ReleaseLock() <= 0)
463 Py_FatalError("failed releasing import lock after fork");
464
Victor Stinnercaba55b2018-08-03 15:33:52 +0200465 run_at_forkers(_PyInterpreterState_Get()->after_forkers_parent, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200466}
467
468void
469PyOS_AfterFork_Child(void)
470{
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200471 _PyRuntimeState *runtime = &_PyRuntime;
472 _PyGILState_Reinit(runtime);
Victor Stinnerd5d9e812019-05-13 12:35:37 +0200473 _PyEval_ReInitThreads(runtime);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200474 _PyImport_ReInitLock();
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200475 _PySignal_AfterFork();
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200476 _PyRuntimeState_ReInitThreads(runtime);
Victor Stinnerb49858b2019-05-24 15:20:23 +0200477 _PyInterpreterState_DeleteExceptMain(runtime);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200478
Victor Stinnercaba55b2018-08-03 15:33:52 +0200479 run_at_forkers(_PyInterpreterState_Get()->after_forkers_child, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200480}
481
482static int
483register_at_forker(PyObject **lst, PyObject *func)
484{
Gregory P. Smith163468a2017-05-29 10:03:41 -0700485 if (func == NULL) /* nothing to register? do nothing. */
486 return 0;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200487 if (*lst == NULL) {
488 *lst = PyList_New(0);
489 if (*lst == NULL)
490 return -1;
491 }
492 return PyList_Append(*lst, func);
493}
494#endif
495
496/* Legacy wrapper */
497void
498PyOS_AfterFork(void)
499{
500#ifdef HAVE_FORK
501 PyOS_AfterFork_Child();
502#endif
503}
504
505
Victor Stinner6036e442015-03-08 01:58:04 +0100506#ifdef MS_WINDOWS
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200507/* defined in fileutils.c */
Benjamin Petersone5024512018-09-12 12:06:42 -0700508void _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
509void _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *,
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200510 ULONG, struct _Py_stat_struct *);
511#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700512
Larry Hastings9cf065c2012-06-22 16:30:09 -0700513
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200514#ifndef MS_WINDOWS
515PyObject *
516_PyLong_FromUid(uid_t uid)
517{
518 if (uid == (uid_t)-1)
519 return PyLong_FromLong(-1);
520 return PyLong_FromUnsignedLong(uid);
521}
522
523PyObject *
524_PyLong_FromGid(gid_t gid)
525{
526 if (gid == (gid_t)-1)
527 return PyLong_FromLong(-1);
528 return PyLong_FromUnsignedLong(gid);
529}
530
531int
532_Py_Uid_Converter(PyObject *obj, void *p)
533{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700534 uid_t uid;
535 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200536 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200537 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700538 unsigned long uresult;
539
540 index = PyNumber_Index(obj);
541 if (index == NULL) {
542 PyErr_Format(PyExc_TypeError,
543 "uid should be integer, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800544 _PyType_Name(Py_TYPE(obj)));
Serhiy Storchakab4621892013-02-10 23:28:02 +0200545 return 0;
546 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700547
548 /*
549 * Handling uid_t is complicated for two reasons:
550 * * Although uid_t is (always?) unsigned, it still
551 * accepts -1.
552 * * We don't know its size in advance--it may be
553 * bigger than an int, or it may be smaller than
554 * a long.
555 *
556 * So a bit of defensive programming is in order.
557 * Start with interpreting the value passed
558 * in as a signed long and see if it works.
559 */
560
561 result = PyLong_AsLongAndOverflow(index, &overflow);
562
563 if (!overflow) {
564 uid = (uid_t)result;
565
566 if (result == -1) {
567 if (PyErr_Occurred())
568 goto fail;
569 /* It's a legitimate -1, we're done. */
570 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200571 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700572
573 /* Any other negative number is disallowed. */
574 if (result < 0)
575 goto underflow;
576
577 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200578 if (sizeof(uid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700579 (long)uid != result)
580 goto underflow;
581 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200582 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700583
584 if (overflow < 0)
585 goto underflow;
586
587 /*
588 * Okay, the value overflowed a signed long. If it
589 * fits in an *unsigned* long, it may still be okay,
590 * as uid_t may be unsigned long on this platform.
591 */
592 uresult = PyLong_AsUnsignedLong(index);
593 if (PyErr_Occurred()) {
594 if (PyErr_ExceptionMatches(PyExc_OverflowError))
595 goto overflow;
596 goto fail;
597 }
598
599 uid = (uid_t)uresult;
600
601 /*
602 * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
603 * but this value would get interpreted as (uid_t)-1 by chown
604 * and its siblings. That's not what the user meant! So we
605 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100606 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700607 */
608 if (uid == (uid_t)-1)
609 goto overflow;
610
611 /* Ensure the value wasn't truncated. */
612 if (sizeof(uid_t) < sizeof(long) &&
613 (unsigned long)uid != uresult)
614 goto overflow;
615 /* fallthrough */
616
617success:
618 Py_DECREF(index);
619 *(uid_t *)p = uid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200620 return 1;
621
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700622underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200623 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700624 "uid is less than minimum");
625 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200626
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700627overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200628 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700629 "uid is greater than maximum");
630 /* fallthrough */
631
632fail:
633 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200634 return 0;
635}
636
637int
638_Py_Gid_Converter(PyObject *obj, void *p)
639{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700640 gid_t gid;
641 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200642 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200643 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700644 unsigned long uresult;
645
646 index = PyNumber_Index(obj);
647 if (index == NULL) {
648 PyErr_Format(PyExc_TypeError,
649 "gid should be integer, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800650 _PyType_Name(Py_TYPE(obj)));
Serhiy Storchakab4621892013-02-10 23:28:02 +0200651 return 0;
652 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700653
654 /*
655 * Handling gid_t is complicated for two reasons:
656 * * Although gid_t is (always?) unsigned, it still
657 * accepts -1.
658 * * We don't know its size in advance--it may be
659 * bigger than an int, or it may be smaller than
660 * a long.
661 *
662 * So a bit of defensive programming is in order.
663 * Start with interpreting the value passed
664 * in as a signed long and see if it works.
665 */
666
667 result = PyLong_AsLongAndOverflow(index, &overflow);
668
669 if (!overflow) {
670 gid = (gid_t)result;
671
672 if (result == -1) {
673 if (PyErr_Occurred())
674 goto fail;
675 /* It's a legitimate -1, we're done. */
676 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200677 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700678
679 /* Any other negative number is disallowed. */
680 if (result < 0) {
681 goto underflow;
682 }
683
684 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200685 if (sizeof(gid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700686 (long)gid != result)
687 goto underflow;
688 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200689 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700690
691 if (overflow < 0)
692 goto underflow;
693
694 /*
695 * Okay, the value overflowed a signed long. If it
696 * fits in an *unsigned* long, it may still be okay,
697 * as gid_t may be unsigned long on this platform.
698 */
699 uresult = PyLong_AsUnsignedLong(index);
700 if (PyErr_Occurred()) {
701 if (PyErr_ExceptionMatches(PyExc_OverflowError))
702 goto overflow;
703 goto fail;
704 }
705
706 gid = (gid_t)uresult;
707
708 /*
709 * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
710 * but this value would get interpreted as (gid_t)-1 by chown
711 * and its siblings. That's not what the user meant! So we
712 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100713 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700714 */
715 if (gid == (gid_t)-1)
716 goto overflow;
717
718 /* Ensure the value wasn't truncated. */
719 if (sizeof(gid_t) < sizeof(long) &&
720 (unsigned long)gid != uresult)
721 goto overflow;
722 /* fallthrough */
723
724success:
725 Py_DECREF(index);
726 *(gid_t *)p = gid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200727 return 1;
728
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700729underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200730 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700731 "gid is less than minimum");
732 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200733
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700734overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200735 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700736 "gid is greater than maximum");
737 /* fallthrough */
738
739fail:
740 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200741 return 0;
742}
743#endif /* MS_WINDOWS */
744
745
Benjamin Petersoned4aa832016-09-05 17:44:18 -0700746#define _PyLong_FromDev PyLong_FromLongLong
Gregory P. Smith702dada2015-01-28 16:07:52 -0800747
748
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200749#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
750static int
751_Py_Dev_Converter(PyObject *obj, void *p)
752{
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200753 *((dev_t *)p) = PyLong_AsUnsignedLongLong(obj);
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200754 if (PyErr_Occurred())
755 return 0;
756 return 1;
757}
Gregory P. Smith702dada2015-01-28 16:07:52 -0800758#endif /* HAVE_MKNOD && HAVE_MAKEDEV */
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200759
760
Larry Hastings9cf065c2012-06-22 16:30:09 -0700761#ifdef AT_FDCWD
Trent Nelson9a461052012-09-18 21:50:06 -0400762/*
763 * Why the (int) cast? Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
764 * without the int cast, the value gets interpreted as uint (4291925331),
765 * which doesn't play nicely with all the initializer lines in this file that
766 * look like this:
767 * int dir_fd = DEFAULT_DIR_FD;
768 */
769#define DEFAULT_DIR_FD (int)AT_FDCWD
Larry Hastings9cf065c2012-06-22 16:30:09 -0700770#else
771#define DEFAULT_DIR_FD (-100)
772#endif
773
774static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300775_fd_converter(PyObject *o, int *p)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200776{
777 int overflow;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700778 long long_value;
779
780 PyObject *index = PyNumber_Index(o);
781 if (index == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700782 return 0;
783 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700784
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300785 assert(PyLong_Check(index));
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700786 long_value = PyLong_AsLongAndOverflow(index, &overflow);
787 Py_DECREF(index);
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300788 assert(!PyErr_Occurred());
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200789 if (overflow > 0 || long_value > INT_MAX) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700790 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700791 "fd is greater than maximum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700792 return 0;
793 }
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200794 if (overflow < 0 || long_value < INT_MIN) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700795 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700796 "fd is less than minimum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700797 return 0;
798 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700799
Larry Hastings9cf065c2012-06-22 16:30:09 -0700800 *p = (int)long_value;
801 return 1;
802}
803
804static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200805dir_fd_converter(PyObject *o, void *p)
806{
807 if (o == Py_None) {
808 *(int *)p = DEFAULT_DIR_FD;
809 return 1;
810 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300811 else if (PyIndex_Check(o)) {
812 return _fd_converter(o, (int *)p);
813 }
814 else {
815 PyErr_Format(PyExc_TypeError,
816 "argument should be integer or None, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800817 _PyType_Name(Py_TYPE(o)));
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300818 return 0;
819 }
Larry Hastings9cf065c2012-06-22 16:30:09 -0700820}
821
Eddie Elizondob3966632019-11-05 07:16:14 -0800822typedef struct {
823 PyObject *billion;
Eddie Elizondob3966632019-11-05 07:16:14 -0800824 PyObject *DirEntryType;
825 PyObject *ScandirIteratorType;
826#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
827 PyObject *SchedParamType;
828#endif
829 PyObject *StatResultType;
830 PyObject *StatVFSResultType;
831 PyObject *TerminalSizeType;
832 PyObject *TimesResultType;
833 PyObject *UnameResultType;
834#if defined(HAVE_WAITID) && !defined(__APPLE__)
835 PyObject *WaitidResultType;
836#endif
837#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
838 PyObject *struct_rusage;
839#endif
840 PyObject *st_mode;
841} _posixstate;
842
843static struct PyModuleDef posixmodule;
844
845#define _posixstate(o) ((_posixstate *)PyModule_GetState(o))
846#define _posixstate_global ((_posixstate *)PyModule_GetState(PyState_FindModule(&posixmodule)))
Larry Hastings9cf065c2012-06-22 16:30:09 -0700847
Larry Hastings9cf065c2012-06-22 16:30:09 -0700848/*
849 * A PyArg_ParseTuple "converter" function
850 * that handles filesystem paths in the manner
851 * preferred by the os module.
852 *
853 * path_converter accepts (Unicode) strings and their
854 * subclasses, and bytes and their subclasses. What
855 * it does with the argument depends on the platform:
856 *
857 * * On Windows, if we get a (Unicode) string we
858 * extract the wchar_t * and return it; if we get
Steve Dowercc16be82016-09-08 10:35:16 -0700859 * bytes we decode to wchar_t * and return that.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700860 *
861 * * On all other platforms, strings are encoded
862 * to bytes using PyUnicode_FSConverter, then we
863 * extract the char * from the bytes object and
864 * return that.
865 *
866 * path_converter also optionally accepts signed
867 * integers (representing open file descriptors) instead
868 * of path strings.
869 *
870 * Input fields:
871 * path.nullable
872 * If nonzero, the path is permitted to be None.
873 * path.allow_fd
874 * If nonzero, the path is permitted to be a file handle
875 * (a signed int) instead of a string.
876 * path.function_name
877 * If non-NULL, path_converter will use that as the name
878 * of the function in error messages.
Larry Hastings31826802013-10-19 00:09:25 -0700879 * (If path.function_name is NULL it omits the function name.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700880 * path.argument_name
881 * If non-NULL, path_converter will use that as the name
882 * of the parameter in error messages.
883 * (If path.argument_name is NULL it uses "path".)
884 *
885 * Output fields:
886 * path.wide
887 * Points to the path if it was expressed as Unicode
888 * and was not encoded. (Only used on Windows.)
889 * path.narrow
890 * Points to the path if it was expressed as bytes,
Steve Dowercc16be82016-09-08 10:35:16 -0700891 * or it was Unicode and was encoded to bytes. (On Windows,
Martin Panterb1321fb2016-10-10 00:38:21 +0000892 * is a non-zero integer if the path was expressed as bytes.
Steve Dowercc16be82016-09-08 10:35:16 -0700893 * The type is deliberately incompatible to prevent misuse.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700894 * path.fd
895 * Contains a file descriptor if path.accept_fd was true
896 * and the caller provided a signed integer instead of any
897 * sort of string.
898 *
899 * WARNING: if your "path" parameter is optional, and is
900 * unspecified, path_converter will never get called.
901 * So if you set allow_fd, you *MUST* initialize path.fd = -1
902 * yourself!
903 * path.length
904 * The length of the path in characters, if specified as
905 * a string.
906 * path.object
Xiang Zhang04316c42017-01-08 23:26:57 +0800907 * The original object passed in (if get a PathLike object,
908 * the result of PyOS_FSPath() is treated as the original object).
909 * Own a reference to the object.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700910 * path.cleanup
911 * For internal use only. May point to a temporary object.
912 * (Pay no attention to the man behind the curtain.)
913 *
914 * At most one of path.wide or path.narrow will be non-NULL.
915 * If path was None and path.nullable was set,
916 * or if path was an integer and path.allow_fd was set,
917 * both path.wide and path.narrow will be NULL
918 * and path.length will be 0.
Georg Brandlf7875592012-06-24 13:58:31 +0200919 *
Larry Hastings9cf065c2012-06-22 16:30:09 -0700920 * path_converter takes care to not write to the path_t
921 * unless it's successful. However it must reset the
922 * "cleanup" field each time it's called.
923 *
924 * Use as follows:
925 * path_t path;
926 * memset(&path, 0, sizeof(path));
927 * PyArg_ParseTuple(args, "O&", path_converter, &path);
928 * // ... use values from path ...
929 * path_cleanup(&path);
930 *
931 * (Note that if PyArg_Parse fails you don't need to call
932 * path_cleanup(). However it is safe to do so.)
933 */
934typedef struct {
Victor Stinner292c8352012-10-30 02:17:38 +0100935 const char *function_name;
936 const char *argument_name;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700937 int nullable;
938 int allow_fd;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300939 const wchar_t *wide;
Steve Dowercc16be82016-09-08 10:35:16 -0700940#ifdef MS_WINDOWS
941 BOOL narrow;
942#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300943 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700944#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700945 int fd;
946 Py_ssize_t length;
947 PyObject *object;
948 PyObject *cleanup;
949} path_t;
950
Steve Dowercc16be82016-09-08 10:35:16 -0700951#ifdef MS_WINDOWS
952#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
953 {function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
954#else
Larry Hastings2f936352014-08-05 14:04:04 +1000955#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
956 {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
Steve Dowercc16be82016-09-08 10:35:16 -0700957#endif
Larry Hastings31826802013-10-19 00:09:25 -0700958
Larry Hastings9cf065c2012-06-22 16:30:09 -0700959static void
Xiang Zhang04316c42017-01-08 23:26:57 +0800960path_cleanup(path_t *path)
961{
962 Py_CLEAR(path->object);
963 Py_CLEAR(path->cleanup);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700964}
965
966static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300967path_converter(PyObject *o, void *p)
968{
Larry Hastings9cf065c2012-06-22 16:30:09 -0700969 path_t *path = (path_t *)p;
Xiang Zhang04316c42017-01-08 23:26:57 +0800970 PyObject *bytes = NULL;
971 Py_ssize_t length = 0;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700972 int is_index, is_buffer, is_bytes, is_unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300973 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700974#ifdef MS_WINDOWS
Xiang Zhang04316c42017-01-08 23:26:57 +0800975 PyObject *wo = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700976 const wchar_t *wide;
977#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700978
979#define FORMAT_EXCEPTION(exc, fmt) \
980 PyErr_Format(exc, "%s%s" fmt, \
981 path->function_name ? path->function_name : "", \
982 path->function_name ? ": " : "", \
983 path->argument_name ? path->argument_name : "path")
984
985 /* Py_CLEANUP_SUPPORTED support */
986 if (o == NULL) {
987 path_cleanup(path);
988 return 1;
989 }
990
Brett Cannon3f9183b2016-08-26 14:44:48 -0700991 /* Ensure it's always safe to call path_cleanup(). */
Xiang Zhang04316c42017-01-08 23:26:57 +0800992 path->object = path->cleanup = NULL;
993 /* path->object owns a reference to the original object */
994 Py_INCREF(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700995
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300996 if ((o == Py_None) && path->nullable) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700997 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700998#ifdef MS_WINDOWS
999 path->narrow = FALSE;
1000#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001001 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001002#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07001003 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001004 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001005 }
1006
Brett Cannon3f9183b2016-08-26 14:44:48 -07001007 /* Only call this here so that we don't treat the return value of
1008 os.fspath() as an fd or buffer. */
1009 is_index = path->allow_fd && PyIndex_Check(o);
1010 is_buffer = PyObject_CheckBuffer(o);
1011 is_bytes = PyBytes_Check(o);
1012 is_unicode = PyUnicode_Check(o);
1013
1014 if (!is_index && !is_buffer && !is_unicode && !is_bytes) {
1015 /* Inline PyOS_FSPath() for better error messages. */
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001016 PyObject *func, *res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001017
1018 func = _PyObject_LookupSpecial(o, &PyId___fspath__);
1019 if (NULL == func) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001020 goto error_format;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001021 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001022 res = _PyObject_CallNoArg(func);
Brett Cannon3f9183b2016-08-26 14:44:48 -07001023 Py_DECREF(func);
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001024 if (NULL == res) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001025 goto error_exit;
1026 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001027 else if (PyUnicode_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001028 is_unicode = 1;
1029 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001030 else if (PyBytes_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001031 is_bytes = 1;
1032 }
1033 else {
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001034 PyErr_Format(PyExc_TypeError,
1035 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -08001036 "not %.200s", _PyType_Name(Py_TYPE(o)),
1037 _PyType_Name(Py_TYPE(res)));
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001038 Py_DECREF(res);
1039 goto error_exit;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001040 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001041
1042 /* still owns a reference to the original object */
1043 Py_DECREF(o);
1044 o = res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001045 }
1046
1047 if (is_unicode) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001048#ifdef MS_WINDOWS
Victor Stinner26c03bd2016-09-19 11:55:44 +02001049 wide = PyUnicode_AsUnicodeAndSize(o, &length);
Victor Stinner59799a82013-11-13 14:17:30 +01001050 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001051 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001052 }
Victor Stinner59799a82013-11-13 14:17:30 +01001053 if (length > 32767) {
1054 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001055 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001056 }
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001057 if (wcslen(wide) != length) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001058 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001059 goto error_exit;
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001060 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001061
1062 path->wide = wide;
Xiang Zhang04316c42017-01-08 23:26:57 +08001063 path->narrow = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001064 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001065 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001066#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001067 if (!PyUnicode_FSConverter(o, &bytes)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001068 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001069 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001070#endif
1071 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001072 else if (is_bytes) {
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001073 bytes = o;
1074 Py_INCREF(bytes);
1075 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001076 else if (is_buffer) {
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03001077 /* XXX Replace PyObject_CheckBuffer with PyBytes_Check in other code
Ville Skyttä49b27342017-08-03 09:00:59 +03001078 after removing support of non-bytes buffer objects. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001079 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1080 "%s%s%s should be %s, not %.200s",
1081 path->function_name ? path->function_name : "",
1082 path->function_name ? ": " : "",
1083 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001084 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1085 "integer or None" :
1086 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1087 path->nullable ? "string, bytes, os.PathLike or None" :
1088 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001089 _PyType_Name(Py_TYPE(o)))) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001090 goto error_exit;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001091 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001092 bytes = PyBytes_FromObject(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001093 if (!bytes) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001094 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001095 }
1096 }
Steve Dowercc16be82016-09-08 10:35:16 -07001097 else if (is_index) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001098 if (!_fd_converter(o, &path->fd)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001099 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001100 }
1101 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001102#ifdef MS_WINDOWS
1103 path->narrow = FALSE;
1104#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001105 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001106#endif
Xiang Zhang04316c42017-01-08 23:26:57 +08001107 goto success_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001108 }
1109 else {
Xiang Zhang04316c42017-01-08 23:26:57 +08001110 error_format:
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001111 PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
1112 path->function_name ? path->function_name : "",
1113 path->function_name ? ": " : "",
1114 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001115 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1116 "integer or None" :
1117 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1118 path->nullable ? "string, bytes, os.PathLike or None" :
1119 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001120 _PyType_Name(Py_TYPE(o)));
Xiang Zhang04316c42017-01-08 23:26:57 +08001121 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001122 }
1123
Larry Hastings9cf065c2012-06-22 16:30:09 -07001124 length = PyBytes_GET_SIZE(bytes);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001125 narrow = PyBytes_AS_STRING(bytes);
Victor Stinner706768c2014-08-16 01:03:39 +02001126 if ((size_t)length != strlen(narrow)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03001127 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001128 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001129 }
1130
Steve Dowercc16be82016-09-08 10:35:16 -07001131#ifdef MS_WINDOWS
1132 wo = PyUnicode_DecodeFSDefaultAndSize(
1133 narrow,
1134 length
1135 );
1136 if (!wo) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001137 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001138 }
1139
Xiang Zhang04316c42017-01-08 23:26:57 +08001140 wide = PyUnicode_AsUnicodeAndSize(wo, &length);
Steve Dowercc16be82016-09-08 10:35:16 -07001141 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001142 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001143 }
1144 if (length > 32767) {
1145 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001146 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001147 }
1148 if (wcslen(wide) != length) {
1149 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001150 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001151 }
1152 path->wide = wide;
1153 path->narrow = TRUE;
Xiang Zhang04316c42017-01-08 23:26:57 +08001154 path->cleanup = wo;
1155 Py_DECREF(bytes);
Steve Dowercc16be82016-09-08 10:35:16 -07001156#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001157 path->wide = NULL;
1158 path->narrow = narrow;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001159 if (bytes == o) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001160 /* Still a reference owned by path->object, don't have to
1161 worry about path->narrow is used after free. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001162 Py_DECREF(bytes);
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001163 }
1164 else {
1165 path->cleanup = bytes;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001166 }
Xiang Zhang04316c42017-01-08 23:26:57 +08001167#endif
1168 path->fd = -1;
1169
1170 success_exit:
1171 path->length = length;
1172 path->object = o;
1173 return Py_CLEANUP_SUPPORTED;
1174
1175 error_exit:
1176 Py_XDECREF(o);
1177 Py_XDECREF(bytes);
1178#ifdef MS_WINDOWS
1179 Py_XDECREF(wo);
1180#endif
1181 return 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001182}
1183
1184static void
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001185argument_unavailable_error(const char *function_name, const char *argument_name)
1186{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001187 PyErr_Format(PyExc_NotImplementedError,
1188 "%s%s%s unavailable on this platform",
1189 (function_name != NULL) ? function_name : "",
1190 (function_name != NULL) ? ": ": "",
1191 argument_name);
1192}
1193
1194static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001195dir_fd_unavailable(PyObject *o, void *p)
1196{
1197 int dir_fd;
1198 if (!dir_fd_converter(o, &dir_fd))
Larry Hastings9cf065c2012-06-22 16:30:09 -07001199 return 0;
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001200 if (dir_fd != DEFAULT_DIR_FD) {
1201 argument_unavailable_error(NULL, "dir_fd");
1202 return 0;
1203 }
1204 *(int *)p = dir_fd;
1205 return 1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001206}
1207
1208static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001209fd_specified(const char *function_name, int fd)
1210{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001211 if (fd == -1)
1212 return 0;
1213
1214 argument_unavailable_error(function_name, "fd");
1215 return 1;
1216}
1217
1218static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001219follow_symlinks_specified(const char *function_name, int follow_symlinks)
1220{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001221 if (follow_symlinks)
1222 return 0;
1223
1224 argument_unavailable_error(function_name, "follow_symlinks");
1225 return 1;
1226}
1227
1228static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001229path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
1230{
Steve Dowercc16be82016-09-08 10:35:16 -07001231 if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
1232#ifndef MS_WINDOWS
1233 && !path->narrow
1234#endif
1235 ) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001236 PyErr_Format(PyExc_ValueError,
1237 "%s: can't specify dir_fd without matching path",
1238 function_name);
1239 return 1;
1240 }
1241 return 0;
1242}
1243
1244static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001245dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
1246{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001247 if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
1248 PyErr_Format(PyExc_ValueError,
1249 "%s: can't specify both dir_fd and fd",
1250 function_name);
1251 return 1;
1252 }
1253 return 0;
1254}
1255
1256static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001257fd_and_follow_symlinks_invalid(const char *function_name, int fd,
1258 int follow_symlinks)
1259{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001260 if ((fd > 0) && (!follow_symlinks)) {
1261 PyErr_Format(PyExc_ValueError,
1262 "%s: cannot use fd and follow_symlinks together",
1263 function_name);
1264 return 1;
1265 }
1266 return 0;
1267}
1268
1269static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001270dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
1271 int follow_symlinks)
1272{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001273 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
1274 PyErr_Format(PyExc_ValueError,
1275 "%s: cannot use dir_fd and follow_symlinks together",
1276 function_name);
1277 return 1;
1278 }
1279 return 0;
1280}
1281
Larry Hastings2f936352014-08-05 14:04:04 +10001282#ifdef MS_WINDOWS
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001283 typedef long long Py_off_t;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001284#else
Larry Hastings2f936352014-08-05 14:04:04 +10001285 typedef off_t Py_off_t;
1286#endif
1287
1288static int
1289Py_off_t_converter(PyObject *arg, void *addr)
1290{
1291#ifdef HAVE_LARGEFILE_SUPPORT
1292 *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
1293#else
1294 *((Py_off_t *)addr) = PyLong_AsLong(arg);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001295#endif
1296 if (PyErr_Occurred())
1297 return 0;
1298 return 1;
1299}
Larry Hastings2f936352014-08-05 14:04:04 +10001300
1301static PyObject *
1302PyLong_FromPy_off_t(Py_off_t offset)
1303{
1304#ifdef HAVE_LARGEFILE_SUPPORT
1305 return PyLong_FromLongLong(offset);
1306#else
1307 return PyLong_FromLong(offset);
Ross Lagerwallb1e5d592011-09-19 08:30:43 +02001308#endif
Larry Hastings2f936352014-08-05 14:04:04 +10001309}
1310
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001311#ifdef HAVE_SIGSET_T
1312/* Convert an iterable of integers to a sigset.
1313 Return 1 on success, return 0 and raise an exception on error. */
1314int
1315_Py_Sigset_Converter(PyObject *obj, void *addr)
1316{
1317 sigset_t *mask = (sigset_t *)addr;
1318 PyObject *iterator, *item;
1319 long signum;
1320 int overflow;
1321
Rémi Lapeyref0900192019-05-04 01:30:53 +02001322 // The extra parens suppress the unreachable-code warning with clang on MacOS
1323 if (sigemptyset(mask) < (0)) {
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001324 /* Probably only if mask == NULL. */
1325 PyErr_SetFromErrno(PyExc_OSError);
1326 return 0;
1327 }
1328
1329 iterator = PyObject_GetIter(obj);
1330 if (iterator == NULL) {
1331 return 0;
1332 }
1333
1334 while ((item = PyIter_Next(iterator)) != NULL) {
1335 signum = PyLong_AsLongAndOverflow(item, &overflow);
1336 Py_DECREF(item);
1337 if (signum <= 0 || signum >= NSIG) {
1338 if (overflow || signum != -1 || !PyErr_Occurred()) {
1339 PyErr_Format(PyExc_ValueError,
1340 "signal number %ld out of range", signum);
1341 }
1342 goto error;
1343 }
1344 if (sigaddset(mask, (int)signum)) {
1345 if (errno != EINVAL) {
1346 /* Probably impossible */
1347 PyErr_SetFromErrno(PyExc_OSError);
1348 goto error;
1349 }
1350 /* For backwards compatibility, allow idioms such as
1351 * `range(1, NSIG)` but warn about invalid signal numbers
1352 */
1353 const char msg[] =
1354 "invalid signal number %ld, please use valid_signals()";
1355 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
1356 goto error;
1357 }
1358 }
1359 }
1360 if (!PyErr_Occurred()) {
1361 Py_DECREF(iterator);
1362 return 1;
1363 }
1364
1365error:
1366 Py_DECREF(iterator);
1367 return 0;
1368}
1369#endif /* HAVE_SIGSET_T */
1370
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001371#ifdef MS_WINDOWS
Brian Curtinf5e76d02010-11-24 13:14:05 +00001372
1373static int
Brian Curtind25aef52011-06-13 15:16:04 -05001374win32_get_reparse_tag(HANDLE reparse_point_handle, ULONG *reparse_tag)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001375{
Martin Panter70214ad2016-08-04 02:38:59 +00001376 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1377 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001378 DWORD n_bytes_returned;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001379
1380 if (0 == DeviceIoControl(
1381 reparse_point_handle,
1382 FSCTL_GET_REPARSE_POINT,
1383 NULL, 0, /* in buffer */
1384 target_buffer, sizeof(target_buffer),
1385 &n_bytes_returned,
1386 NULL)) /* we're not using OVERLAPPED_IO */
Brian Curtind25aef52011-06-13 15:16:04 -05001387 return FALSE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001388
1389 if (reparse_tag)
1390 *reparse_tag = rdb->ReparseTag;
1391
Brian Curtind25aef52011-06-13 15:16:04 -05001392 return TRUE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001393}
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001394
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001395#endif /* MS_WINDOWS */
Brian Curtinf5e76d02010-11-24 13:14:05 +00001396
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001397/* Return a dictionary corresponding to the POSIX environment table */
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001398#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Jack Jansenea0c3822002-08-01 21:57:49 +00001399/* On Darwin/MacOSX a shared library or framework has no access to
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001400** environ directly, we must obtain it with _NSGetEnviron(). See also
1401** man environ(7).
Jack Jansenea0c3822002-08-01 21:57:49 +00001402*/
1403#include <crt_externs.h>
pxinwrf2d7ac72019-05-21 18:46:37 +08001404#elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001405extern char **environ;
Guido van Rossuma4916fa1996-05-23 22:58:55 +00001406#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001407
Barry Warsaw53699e91996-12-10 23:23:01 +00001408static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001409convertenviron(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001410{
Victor Stinner8c62be82010-05-06 00:08:46 +00001411 PyObject *d;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001412#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00001413 wchar_t **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001414#else
Victor Stinner8c62be82010-05-06 00:08:46 +00001415 char **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001416#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +00001417
Victor Stinner8c62be82010-05-06 00:08:46 +00001418 d = PyDict_New();
1419 if (d == NULL)
1420 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001421#ifdef MS_WINDOWS
1422 /* _wenviron must be initialized in this way if the program is started
1423 through main() instead of wmain(). */
1424 _wgetenv(L"");
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001425 e = _wenviron;
Benoit Hudson723f71a2019-12-06 14:15:03 -05001426#elif defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
1427 /* environ is not accessible as an extern in a shared object on OSX; use
1428 _NSGetEnviron to resolve it. The value changes if you add environment
1429 variables between calls to Py_Initialize, so don't cache the value. */
1430 e = *_NSGetEnviron();
Victor Stinner8c62be82010-05-06 00:08:46 +00001431#else
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001432 e = environ;
1433#endif
1434 if (e == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +00001435 return d;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001436 for (; *e != NULL; e++) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001437 PyObject *k;
1438 PyObject *v;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001439#ifdef MS_WINDOWS
1440 const wchar_t *p = wcschr(*e, L'=');
1441#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03001442 const char *p = strchr(*e, '=');
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001443#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001444 if (p == NULL)
1445 continue;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001446#ifdef MS_WINDOWS
1447 k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
1448#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001449 k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001450#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001451 if (k == NULL) {
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001452 Py_DECREF(d);
1453 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001454 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001455#ifdef MS_WINDOWS
1456 v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
1457#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001458 v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001459#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001460 if (v == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001461 Py_DECREF(k);
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001462 Py_DECREF(d);
1463 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001464 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001465 if (PyDict_GetItemWithError(d, k) == NULL) {
1466 if (PyErr_Occurred() || PyDict_SetItem(d, k, v) != 0) {
1467 Py_DECREF(v);
1468 Py_DECREF(k);
1469 Py_DECREF(d);
1470 return NULL;
1471 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001472 }
1473 Py_DECREF(k);
1474 Py_DECREF(v);
Guido van Rossumd48f2521997-12-05 22:19:34 +00001475 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001476 return d;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001477}
1478
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001479/* Set a POSIX-specific error from errno, and return NULL */
1480
Barry Warsawd58d7641998-07-23 16:14:40 +00001481static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001482posix_error(void)
Guido van Rossumad0ee831995-03-01 10:34:45 +00001483{
Victor Stinner8c62be82010-05-06 00:08:46 +00001484 return PyErr_SetFromErrno(PyExc_OSError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001485}
Mark Hammondef8b6542001-05-13 08:04:26 +00001486
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001487#ifdef MS_WINDOWS
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001488static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001489win32_error(const char* function, const char* filename)
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001490{
Victor Stinner8c62be82010-05-06 00:08:46 +00001491 /* XXX We should pass the function name along in the future.
1492 (winreg.c also wants to pass the function name.)
1493 This would however require an additional param to the
1494 Windows error object, which is non-trivial.
1495 */
1496 errno = GetLastError();
1497 if (filename)
1498 return PyErr_SetFromWindowsErrWithFilename(errno, filename);
1499 else
1500 return PyErr_SetFromWindowsErr(errno);
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001501}
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001502
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001503static PyObject *
Steve Dower2438cdf2019-03-29 16:37:16 -07001504win32_error_object_err(const char* function, PyObject* filename, DWORD err)
Victor Stinnereb5657a2011-09-30 01:44:27 +02001505{
1506 /* XXX - see win32_error for comments on 'function' */
Victor Stinnereb5657a2011-09-30 01:44:27 +02001507 if (filename)
1508 return PyErr_SetExcFromWindowsErrWithFilenameObject(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001509 PyExc_OSError,
Steve Dower2438cdf2019-03-29 16:37:16 -07001510 err,
Victor Stinnereb5657a2011-09-30 01:44:27 +02001511 filename);
1512 else
Steve Dower2438cdf2019-03-29 16:37:16 -07001513 return PyErr_SetFromWindowsErr(err);
1514}
1515
1516static PyObject *
1517win32_error_object(const char* function, PyObject* filename)
1518{
1519 errno = GetLastError();
1520 return win32_error_object_err(function, filename, errno);
Victor Stinnereb5657a2011-09-30 01:44:27 +02001521}
1522
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001523#endif /* MS_WINDOWS */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001524
Larry Hastings9cf065c2012-06-22 16:30:09 -07001525static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001526posix_path_object_error(PyObject *path)
1527{
1528 return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
1529}
1530
1531static PyObject *
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001532path_object_error(PyObject *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001533{
1534#ifdef MS_WINDOWS
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001535 return PyErr_SetExcFromWindowsErrWithFilenameObject(
1536 PyExc_OSError, 0, path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001537#else
Alexey Izbyshev83460312018-10-20 03:28:22 +03001538 return posix_path_object_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001539#endif
1540}
1541
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001542static PyObject *
1543path_object_error2(PyObject *path, PyObject *path2)
1544{
1545#ifdef MS_WINDOWS
1546 return PyErr_SetExcFromWindowsErrWithFilenameObjects(
1547 PyExc_OSError, 0, path, path2);
1548#else
1549 return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
1550#endif
1551}
1552
1553static PyObject *
1554path_error(path_t *path)
1555{
1556 return path_object_error(path->object);
1557}
Larry Hastings31826802013-10-19 00:09:25 -07001558
Larry Hastingsb0827312014-02-09 22:05:19 -08001559static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001560posix_path_error(path_t *path)
1561{
1562 return posix_path_object_error(path->object);
1563}
1564
1565static PyObject *
Larry Hastingsb0827312014-02-09 22:05:19 -08001566path_error2(path_t *path, path_t *path2)
1567{
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001568 return path_object_error2(path->object, path2->object);
Larry Hastingsb0827312014-02-09 22:05:19 -08001569}
1570
1571
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001572/* POSIX generic methods */
1573
Larry Hastings2f936352014-08-05 14:04:04 +10001574static int
1575fildes_converter(PyObject *o, void *p)
Fred Drake4d1e64b2002-04-15 19:40:07 +00001576{
Victor Stinner8c62be82010-05-06 00:08:46 +00001577 int fd;
Larry Hastings2f936352014-08-05 14:04:04 +10001578 int *pointer = (int *)p;
1579 fd = PyObject_AsFileDescriptor(o);
Victor Stinner8c62be82010-05-06 00:08:46 +00001580 if (fd < 0)
Larry Hastings2f936352014-08-05 14:04:04 +10001581 return 0;
Larry Hastings2f936352014-08-05 14:04:04 +10001582 *pointer = fd;
1583 return 1;
1584}
1585
1586static PyObject *
1587posix_fildes_fd(int fd, int (*func)(int))
1588{
1589 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001590 int async_err = 0;
1591
1592 do {
1593 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001594 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001595 res = (*func)(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001596 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001597 Py_END_ALLOW_THREADS
1598 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1599 if (res != 0)
1600 return (!async_err) ? posix_error() : NULL;
1601 Py_RETURN_NONE;
Fred Drake4d1e64b2002-04-15 19:40:07 +00001602}
Guido van Rossum21142a01999-01-08 21:05:37 +00001603
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001604
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001605#ifdef MS_WINDOWS
Thomas Wouters477c8d52006-05-27 19:21:47 +00001606/* This is a reimplementation of the C library's chdir function,
1607 but one that produces Win32 errors instead of DOS error codes.
1608 chdir is essentially a wrapper around SetCurrentDirectory; however,
1609 it also needs to set "magic" environment variables indicating
1610 the per-drive current directory, which are of the form =<drive>: */
Benjamin Peterson206e3072008-10-19 14:07:49 +00001611static BOOL __stdcall
Thomas Wouters477c8d52006-05-27 19:21:47 +00001612win32_wchdir(LPCWSTR path)
1613{
Victor Stinnered537822015-12-13 21:40:26 +01001614 wchar_t path_buf[MAX_PATH], *new_path = path_buf;
Victor Stinner8c62be82010-05-06 00:08:46 +00001615 int result;
1616 wchar_t env[4] = L"=x:";
Thomas Wouters477c8d52006-05-27 19:21:47 +00001617
Victor Stinner8c62be82010-05-06 00:08:46 +00001618 if(!SetCurrentDirectoryW(path))
1619 return FALSE;
Victor Stinnered537822015-12-13 21:40:26 +01001620 result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001621 if (!result)
1622 return FALSE;
Victor Stinnere847d712015-12-14 00:21:50 +01001623 if (result > Py_ARRAY_LENGTH(path_buf)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001624 new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00001625 if (!new_path) {
1626 SetLastError(ERROR_OUTOFMEMORY);
1627 return FALSE;
1628 }
1629 result = GetCurrentDirectoryW(result, new_path);
1630 if (!result) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001631 PyMem_RawFree(new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001632 return FALSE;
1633 }
1634 }
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001635 int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
1636 wcsncmp(new_path, L"//", 2) == 0);
1637 if (!is_unc_like_path) {
1638 env[1] = new_path[0];
1639 result = SetEnvironmentVariableW(env, new_path);
1640 }
Victor Stinnered537822015-12-13 21:40:26 +01001641 if (new_path != path_buf)
Victor Stinnerb6404912013-07-07 16:21:41 +02001642 PyMem_RawFree(new_path);
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001643 return result ? TRUE : FALSE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001644}
1645#endif
1646
Martin v. Löwis14694662006-02-03 12:54:16 +00001647#ifdef MS_WINDOWS
1648/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
1649 - time stamps are restricted to second resolution
1650 - file modification times suffer from forth-and-back conversions between
1651 UTC and local time
1652 Therefore, we implement our own stat, based on the Win32 API directly.
1653*/
Victor Stinner8c62be82010-05-06 00:08:46 +00001654#define HAVE_STAT_NSEC 1
Zachary Ware63f277b2014-06-19 09:46:37 -05001655#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001656#define HAVE_STRUCT_STAT_ST_REPARSE_TAG 1
Martin v. Löwis14694662006-02-03 12:54:16 +00001657
Victor Stinner6036e442015-03-08 01:58:04 +01001658static void
Steve Dowercc16be82016-09-08 10:35:16 -07001659find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
1660 BY_HANDLE_FILE_INFORMATION *info,
1661 ULONG *reparse_tag)
Victor Stinner6036e442015-03-08 01:58:04 +01001662{
1663 memset(info, 0, sizeof(*info));
1664 info->dwFileAttributes = pFileData->dwFileAttributes;
1665 info->ftCreationTime = pFileData->ftCreationTime;
1666 info->ftLastAccessTime = pFileData->ftLastAccessTime;
1667 info->ftLastWriteTime = pFileData->ftLastWriteTime;
1668 info->nFileSizeHigh = pFileData->nFileSizeHigh;
1669 info->nFileSizeLow = pFileData->nFileSizeLow;
1670/* info->nNumberOfLinks = 1; */
1671 if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
1672 *reparse_tag = pFileData->dwReserved0;
1673 else
1674 *reparse_tag = 0;
1675}
1676
Guido van Rossumd8faa362007-04-27 19:54:29 +00001677static BOOL
Steve Dowercc16be82016-09-08 10:35:16 -07001678attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001679{
Victor Stinner8c62be82010-05-06 00:08:46 +00001680 HANDLE hFindFile;
1681 WIN32_FIND_DATAW FileData;
1682 hFindFile = FindFirstFileW(pszFile, &FileData);
1683 if (hFindFile == INVALID_HANDLE_VALUE)
1684 return FALSE;
1685 FindClose(hFindFile);
Steve Dowercc16be82016-09-08 10:35:16 -07001686 find_data_to_file_info(&FileData, info, reparse_tag);
Victor Stinner8c62be82010-05-06 00:08:46 +00001687 return TRUE;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001688}
1689
Brian Curtind25aef52011-06-13 15:16:04 -05001690static int
Steve Dowercc16be82016-09-08 10:35:16 -07001691win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
Brian Curtind25aef52011-06-13 15:16:04 -05001692 BOOL traverse)
1693{
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001694 HANDLE hFile;
1695 BY_HANDLE_FILE_INFORMATION fileInfo;
1696 FILE_ATTRIBUTE_TAG_INFO tagInfo = { 0 };
1697 DWORD fileType, error;
1698 BOOL isUnhandledTag = FALSE;
1699 int retval = 0;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001700
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001701 DWORD access = FILE_READ_ATTRIBUTES;
1702 DWORD flags = FILE_FLAG_BACKUP_SEMANTICS; /* Allow opening directories. */
1703 if (!traverse) {
1704 flags |= FILE_FLAG_OPEN_REPARSE_POINT;
1705 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001706
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001707 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING, flags, NULL);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001708 if (hFile == INVALID_HANDLE_VALUE) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001709 /* Either the path doesn't exist, or the caller lacks access. */
1710 error = GetLastError();
1711 switch (error) {
1712 case ERROR_ACCESS_DENIED: /* Cannot sync or read attributes. */
1713 case ERROR_SHARING_VIOLATION: /* It's a paging file. */
1714 /* Try reading the parent directory. */
1715 if (!attributes_from_dir(path, &fileInfo, &tagInfo.ReparseTag)) {
1716 /* Cannot read the parent directory. */
1717 SetLastError(error);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001718 return -1;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001719 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001720 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1721 if (traverse ||
1722 !IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1723 /* The stat call has to traverse but cannot, so fail. */
1724 SetLastError(error);
Brian Curtind25aef52011-06-13 15:16:04 -05001725 return -1;
Mark Becwarb82bfac2019-02-02 16:08:23 -05001726 }
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001727 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001728 break;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001729
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001730 case ERROR_INVALID_PARAMETER:
1731 /* \\.\con requires read or write access. */
1732 hFile = CreateFileW(path, access | GENERIC_READ,
1733 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1734 OPEN_EXISTING, flags, NULL);
1735 if (hFile == INVALID_HANDLE_VALUE) {
1736 SetLastError(error);
1737 return -1;
1738 }
1739 break;
1740
1741 case ERROR_CANT_ACCESS_FILE:
1742 /* bpo37834: open unhandled reparse points if traverse fails. */
1743 if (traverse) {
1744 traverse = FALSE;
1745 isUnhandledTag = TRUE;
1746 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING,
1747 flags | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
1748 }
1749 if (hFile == INVALID_HANDLE_VALUE) {
1750 SetLastError(error);
1751 return -1;
1752 }
1753 break;
1754
1755 default:
1756 return -1;
1757 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001758 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001759
1760 if (hFile != INVALID_HANDLE_VALUE) {
1761 /* Handle types other than files on disk. */
1762 fileType = GetFileType(hFile);
1763 if (fileType != FILE_TYPE_DISK) {
1764 if (fileType == FILE_TYPE_UNKNOWN && GetLastError() != 0) {
1765 retval = -1;
1766 goto cleanup;
1767 }
1768 DWORD fileAttributes = GetFileAttributesW(path);
1769 memset(result, 0, sizeof(*result));
1770 if (fileAttributes != INVALID_FILE_ATTRIBUTES &&
1771 fileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1772 /* \\.\pipe\ or \\.\mailslot\ */
1773 result->st_mode = _S_IFDIR;
1774 } else if (fileType == FILE_TYPE_CHAR) {
1775 /* \\.\nul */
1776 result->st_mode = _S_IFCHR;
1777 } else if (fileType == FILE_TYPE_PIPE) {
1778 /* \\.\pipe\spam */
1779 result->st_mode = _S_IFIFO;
1780 }
1781 /* FILE_TYPE_UNKNOWN, e.g. \\.\mailslot\waitfor.exe\spam */
1782 goto cleanup;
1783 }
1784
1785 /* Query the reparse tag, and traverse a non-link. */
1786 if (!traverse) {
1787 if (!GetFileInformationByHandleEx(hFile, FileAttributeTagInfo,
1788 &tagInfo, sizeof(tagInfo))) {
1789 /* Allow devices that do not support FileAttributeTagInfo. */
1790 switch (GetLastError()) {
1791 case ERROR_INVALID_PARAMETER:
1792 case ERROR_INVALID_FUNCTION:
1793 case ERROR_NOT_SUPPORTED:
1794 tagInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1795 tagInfo.ReparseTag = 0;
1796 break;
1797 default:
1798 retval = -1;
1799 goto cleanup;
1800 }
1801 } else if (tagInfo.FileAttributes &
1802 FILE_ATTRIBUTE_REPARSE_POINT) {
1803 if (IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1804 if (isUnhandledTag) {
1805 /* Traversing previously failed for either this link
1806 or its target. */
1807 SetLastError(ERROR_CANT_ACCESS_FILE);
1808 retval = -1;
1809 goto cleanup;
1810 }
1811 /* Traverse a non-link, but not if traversing already failed
1812 for an unhandled tag. */
1813 } else if (!isUnhandledTag) {
1814 CloseHandle(hFile);
1815 return win32_xstat_impl(path, result, TRUE);
1816 }
1817 }
1818 }
1819
1820 if (!GetFileInformationByHandle(hFile, &fileInfo)) {
1821 switch (GetLastError()) {
1822 case ERROR_INVALID_PARAMETER:
1823 case ERROR_INVALID_FUNCTION:
1824 case ERROR_NOT_SUPPORTED:
Steve Dower772ec0f2019-09-04 14:42:54 -07001825 /* Volumes and physical disks are block devices, e.g.
1826 \\.\C: and \\.\PhysicalDrive0. */
1827 memset(result, 0, sizeof(*result));
1828 result->st_mode = 0x6000; /* S_IFBLK */
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001829 goto cleanup;
1830 }
Steve Dower772ec0f2019-09-04 14:42:54 -07001831 retval = -1;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001832 goto cleanup;
1833 }
1834 }
1835
1836 _Py_attribute_data_to_stat(&fileInfo, tagInfo.ReparseTag, result);
1837
1838 if (!(fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
1839 /* Fix the file execute permissions. This hack sets S_IEXEC if
1840 the filename has an extension that is commonly used by files
1841 that CreateProcessW can execute. A real implementation calls
1842 GetSecurityInfo, OpenThreadToken/OpenProcessToken, and
1843 AccessCheck to check for generic read, write, and execute
1844 access. */
1845 const wchar_t *fileExtension = wcsrchr(path, '.');
1846 if (fileExtension) {
1847 if (_wcsicmp(fileExtension, L".exe") == 0 ||
1848 _wcsicmp(fileExtension, L".bat") == 0 ||
1849 _wcsicmp(fileExtension, L".cmd") == 0 ||
1850 _wcsicmp(fileExtension, L".com") == 0) {
1851 result->st_mode |= 0111;
1852 }
1853 }
1854 }
1855
1856cleanup:
1857 if (hFile != INVALID_HANDLE_VALUE) {
Steve Dower772ec0f2019-09-04 14:42:54 -07001858 /* Preserve last error if we are failing */
1859 error = retval ? GetLastError() : 0;
1860 if (!CloseHandle(hFile)) {
1861 retval = -1;
1862 } else if (retval) {
1863 /* Restore last error */
1864 SetLastError(error);
1865 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001866 }
1867
1868 return retval;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001869}
1870
1871static int
Steve Dowercc16be82016-09-08 10:35:16 -07001872win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001873{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001874 /* Protocol violation: we explicitly clear errno, instead of
1875 setting it to a POSIX error. Callers should use GetLastError. */
Brian Curtind25aef52011-06-13 15:16:04 -05001876 int code = win32_xstat_impl(path, result, traverse);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001877 errno = 0;
1878 return code;
1879}
Brian Curtind25aef52011-06-13 15:16:04 -05001880/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
Brian Curtind40e6f72010-07-08 21:39:08 +00001881
1882 In Posix, stat automatically traverses symlinks and returns the stat
1883 structure for the target. In Windows, the equivalent GetFileAttributes by
1884 default does not traverse symlinks and instead returns attributes for
1885 the symlink.
1886
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001887 Instead, we will open the file (which *does* traverse symlinks by default)
1888 and GetFileInformationByHandle(). */
Brian Curtind40e6f72010-07-08 21:39:08 +00001889
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001890static int
Steve Dowercc16be82016-09-08 10:35:16 -07001891win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
Martin v. Löwis14694662006-02-03 12:54:16 +00001892{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001893 return win32_xstat(path, result, FALSE);
Martin v. Löwis14694662006-02-03 12:54:16 +00001894}
1895
Victor Stinner8c62be82010-05-06 00:08:46 +00001896static int
Steve Dowercc16be82016-09-08 10:35:16 -07001897win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
Brian Curtind40e6f72010-07-08 21:39:08 +00001898{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001899 return win32_xstat(path, result, TRUE);
Brian Curtind40e6f72010-07-08 21:39:08 +00001900}
1901
Martin v. Löwis14694662006-02-03 12:54:16 +00001902#endif /* MS_WINDOWS */
1903
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001904PyDoc_STRVAR(stat_result__doc__,
Larry Hastings9cf065c2012-06-22 16:30:09 -07001905"stat_result: Result from stat, fstat, or lstat.\n\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001906This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001907 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001908or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1909\n\
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001910Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1911or st_flags, they are available as attributes only.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001912\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001913See os.stat for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001914
1915static PyStructSequence_Field stat_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001916 {"st_mode", "protection bits"},
1917 {"st_ino", "inode"},
1918 {"st_dev", "device"},
1919 {"st_nlink", "number of hard links"},
1920 {"st_uid", "user ID of owner"},
1921 {"st_gid", "group ID of owner"},
1922 {"st_size", "total size, in bytes"},
1923 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1924 {NULL, "integer time of last access"},
1925 {NULL, "integer time of last modification"},
1926 {NULL, "integer time of last change"},
1927 {"st_atime", "time of last access"},
1928 {"st_mtime", "time of last modification"},
1929 {"st_ctime", "time of last change"},
Larry Hastings6fe20b32012-04-19 15:07:49 -07001930 {"st_atime_ns", "time of last access in nanoseconds"},
1931 {"st_mtime_ns", "time of last modification in nanoseconds"},
1932 {"st_ctime_ns", "time of last change in nanoseconds"},
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001933#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00001934 {"st_blksize", "blocksize for filesystem I/O"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001935#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001936#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00001937 {"st_blocks", "number of blocks allocated"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001938#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001939#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00001940 {"st_rdev", "device type (if inode device)"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001941#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001942#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00001943 {"st_flags", "user defined flags for file"},
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001944#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001945#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00001946 {"st_gen", "generation number"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001947#endif
1948#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00001949 {"st_birthtime", "time of creation"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001950#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05001951#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1952 {"st_file_attributes", "Windows file attribute bits"},
1953#endif
jcea6c51d512018-01-28 14:00:08 +01001954#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1955 {"st_fstype", "Type of filesystem"},
1956#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001957#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
1958 {"st_reparse_tag", "Windows reparse tag"},
1959#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001960 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001961};
1962
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001963#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Larry Hastings6fe20b32012-04-19 15:07:49 -07001964#define ST_BLKSIZE_IDX 16
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001965#else
Larry Hastings6fe20b32012-04-19 15:07:49 -07001966#define ST_BLKSIZE_IDX 15
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001967#endif
1968
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001969#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001970#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
1971#else
1972#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
1973#endif
1974
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001975#ifdef HAVE_STRUCT_STAT_ST_RDEV
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001976#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
1977#else
1978#define ST_RDEV_IDX ST_BLOCKS_IDX
1979#endif
1980
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001981#ifdef HAVE_STRUCT_STAT_ST_FLAGS
1982#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
1983#else
1984#define ST_FLAGS_IDX ST_RDEV_IDX
1985#endif
1986
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001987#ifdef HAVE_STRUCT_STAT_ST_GEN
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001988#define ST_GEN_IDX (ST_FLAGS_IDX+1)
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001989#else
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001990#define ST_GEN_IDX ST_FLAGS_IDX
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001991#endif
1992
1993#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1994#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
1995#else
1996#define ST_BIRTHTIME_IDX ST_GEN_IDX
1997#endif
1998
Zachary Ware63f277b2014-06-19 09:46:37 -05001999#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2000#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_IDX+1)
2001#else
2002#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_IDX
2003#endif
2004
jcea6c51d512018-01-28 14:00:08 +01002005#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2006#define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
2007#else
2008#define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
2009#endif
2010
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002011#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2012#define ST_REPARSE_TAG_IDX (ST_FSTYPE_IDX+1)
2013#else
2014#define ST_REPARSE_TAG_IDX ST_FSTYPE_IDX
2015#endif
2016
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002017static PyStructSequence_Desc stat_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002018 "stat_result", /* name */
2019 stat_result__doc__, /* doc */
2020 stat_result_fields,
2021 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002022};
2023
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002024PyDoc_STRVAR(statvfs_result__doc__,
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002025"statvfs_result: Result from statvfs or fstatvfs.\n\n\
2026This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00002027 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
Guido van Rossuma4dc73e2001-10-18 20:53:15 +00002028or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002029\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002030See os.statvfs for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002031
2032static PyStructSequence_Field statvfs_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002033 {"f_bsize", },
2034 {"f_frsize", },
2035 {"f_blocks", },
2036 {"f_bfree", },
2037 {"f_bavail", },
2038 {"f_files", },
2039 {"f_ffree", },
2040 {"f_favail", },
2041 {"f_flag", },
2042 {"f_namemax",},
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +01002043 {"f_fsid", },
Victor Stinner8c62be82010-05-06 00:08:46 +00002044 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002045};
2046
2047static PyStructSequence_Desc statvfs_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002048 "statvfs_result", /* name */
2049 statvfs_result__doc__, /* doc */
2050 statvfs_result_fields,
2051 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002052};
2053
Ross Lagerwall7807c352011-03-17 20:20:30 +02002054#if defined(HAVE_WAITID) && !defined(__APPLE__)
2055PyDoc_STRVAR(waitid_result__doc__,
2056"waitid_result: Result from waitid.\n\n\
2057This object may be accessed either as a tuple of\n\
2058 (si_pid, si_uid, si_signo, si_status, si_code),\n\
2059or via the attributes si_pid, si_uid, and so on.\n\
2060\n\
2061See os.waitid for more information.");
2062
2063static PyStructSequence_Field waitid_result_fields[] = {
2064 {"si_pid", },
2065 {"si_uid", },
2066 {"si_signo", },
2067 {"si_status", },
2068 {"si_code", },
2069 {0}
2070};
2071
2072static PyStructSequence_Desc waitid_result_desc = {
2073 "waitid_result", /* name */
2074 waitid_result__doc__, /* doc */
2075 waitid_result_fields,
2076 5
2077};
Benjamin Petersonbad9c2f2011-08-02 18:42:14 -05002078#endif
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002079static newfunc structseq_new;
2080
2081static PyObject *
2082statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2083{
Victor Stinner8c62be82010-05-06 00:08:46 +00002084 PyStructSequence *result;
2085 int i;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002086
Victor Stinner8c62be82010-05-06 00:08:46 +00002087 result = (PyStructSequence*)structseq_new(type, args, kwds);
2088 if (!result)
2089 return NULL;
2090 /* If we have been initialized from a tuple,
2091 st_?time might be set to None. Initialize it
2092 from the int slots. */
2093 for (i = 7; i <= 9; i++) {
2094 if (result->ob_item[i+3] == Py_None) {
2095 Py_DECREF(Py_None);
2096 Py_INCREF(result->ob_item[i]);
2097 result->ob_item[i+3] = result->ob_item[i];
2098 }
2099 }
2100 return (PyObject*)result;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002101}
2102
Eddie Elizondob3966632019-11-05 07:16:14 -08002103static int
2104_posix_clear(PyObject *module)
2105{
2106 Py_CLEAR(_posixstate(module)->billion);
Eddie Elizondob3966632019-11-05 07:16:14 -08002107 Py_CLEAR(_posixstate(module)->DirEntryType);
2108 Py_CLEAR(_posixstate(module)->ScandirIteratorType);
2109#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
2110 Py_CLEAR(_posixstate(module)->SchedParamType);
2111#endif
2112 Py_CLEAR(_posixstate(module)->StatResultType);
2113 Py_CLEAR(_posixstate(module)->StatVFSResultType);
2114 Py_CLEAR(_posixstate(module)->TerminalSizeType);
2115 Py_CLEAR(_posixstate(module)->TimesResultType);
2116 Py_CLEAR(_posixstate(module)->UnameResultType);
2117#if defined(HAVE_WAITID) && !defined(__APPLE__)
2118 Py_CLEAR(_posixstate(module)->WaitidResultType);
2119#endif
2120#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
2121 Py_CLEAR(_posixstate(module)->struct_rusage);
2122#endif
2123 Py_CLEAR(_posixstate(module)->st_mode);
2124 return 0;
2125}
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002126
Eddie Elizondob3966632019-11-05 07:16:14 -08002127static int
2128_posix_traverse(PyObject *module, visitproc visit, void *arg)
2129{
2130 Py_VISIT(_posixstate(module)->billion);
Eddie Elizondob3966632019-11-05 07:16:14 -08002131 Py_VISIT(_posixstate(module)->DirEntryType);
2132 Py_VISIT(_posixstate(module)->ScandirIteratorType);
2133#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
2134 Py_VISIT(_posixstate(module)->SchedParamType);
2135#endif
2136 Py_VISIT(_posixstate(module)->StatResultType);
2137 Py_VISIT(_posixstate(module)->StatVFSResultType);
2138 Py_VISIT(_posixstate(module)->TerminalSizeType);
2139 Py_VISIT(_posixstate(module)->TimesResultType);
2140 Py_VISIT(_posixstate(module)->UnameResultType);
2141#if defined(HAVE_WAITID) && !defined(__APPLE__)
2142 Py_VISIT(_posixstate(module)->WaitidResultType);
2143#endif
2144#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
2145 Py_VISIT(_posixstate(module)->struct_rusage);
2146#endif
2147 Py_VISIT(_posixstate(module)->st_mode);
2148 return 0;
2149}
2150
2151static void
2152_posix_free(void *module)
2153{
2154 _posix_clear((PyObject *)module);
2155}
Larry Hastings6fe20b32012-04-19 15:07:49 -07002156
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002157static void
Victor Stinner4195b5c2012-02-08 23:03:19 +01002158fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002159{
Larry Hastings6fe20b32012-04-19 15:07:49 -07002160 PyObject *s = _PyLong_FromTime_t(sec);
2161 PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
2162 PyObject *s_in_ns = NULL;
2163 PyObject *ns_total = NULL;
2164 PyObject *float_s = NULL;
2165
2166 if (!(s && ns_fractional))
2167 goto exit;
2168
Eddie Elizondob3966632019-11-05 07:16:14 -08002169 s_in_ns = PyNumber_Multiply(s, _posixstate_global->billion);
Larry Hastings6fe20b32012-04-19 15:07:49 -07002170 if (!s_in_ns)
2171 goto exit;
2172
2173 ns_total = PyNumber_Add(s_in_ns, ns_fractional);
2174 if (!ns_total)
2175 goto exit;
2176
Victor Stinner01b5aab2017-10-24 02:02:00 -07002177 float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
2178 if (!float_s) {
2179 goto exit;
Larry Hastings6fe20b32012-04-19 15:07:49 -07002180 }
2181
2182 PyStructSequence_SET_ITEM(v, index, s);
2183 PyStructSequence_SET_ITEM(v, index+3, float_s);
2184 PyStructSequence_SET_ITEM(v, index+6, ns_total);
2185 s = NULL;
2186 float_s = NULL;
2187 ns_total = NULL;
2188exit:
2189 Py_XDECREF(s);
2190 Py_XDECREF(ns_fractional);
2191 Py_XDECREF(s_in_ns);
2192 Py_XDECREF(ns_total);
2193 Py_XDECREF(float_s);
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002194}
2195
Tim Peters5aa91602002-01-30 05:46:57 +00002196/* pack a system stat C structure into the Python stat tuple
Fred Drake699f3522000-06-29 21:12:41 +00002197 (used by posix_stat() and posix_fstat()) */
2198static PyObject*
Victor Stinner4195b5c2012-02-08 23:03:19 +01002199_pystat_fromstructstat(STRUCT_STAT *st)
Fred Drake699f3522000-06-29 21:12:41 +00002200{
Victor Stinner8c62be82010-05-06 00:08:46 +00002201 unsigned long ansec, mnsec, cnsec;
Eddie Elizondob3966632019-11-05 07:16:14 -08002202 PyObject *StatResultType = _posixstate_global->StatResultType;
2203 PyObject *v = PyStructSequence_New((PyTypeObject *)StatResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +00002204 if (v == NULL)
2205 return NULL;
Fred Drake699f3522000-06-29 21:12:41 +00002206
Victor Stinner8c62be82010-05-06 00:08:46 +00002207 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode));
Victor Stinner0f6d7332017-03-09 17:34:28 +01002208 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(st->st_ino));
xdegaye50e86032017-05-22 11:15:08 +02002209 PyStructSequence_SET_ITEM(v, 1, PyLong_FromUnsignedLongLong(st->st_ino));
Serhiy Storchaka404fa922013-01-02 18:22:23 +02002210#ifdef MS_WINDOWS
2211 PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002212#else
Serhiy Storchakab2653b32015-01-18 11:12:11 +02002213 PyStructSequence_SET_ITEM(v, 2, _PyLong_FromDev(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002214#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002215 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02002216#if defined(MS_WINDOWS)
2217 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong(0));
2218 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong(0));
2219#else
2220 PyStructSequence_SET_ITEM(v, 4, _PyLong_FromUid(st->st_uid));
2221 PyStructSequence_SET_ITEM(v, 5, _PyLong_FromGid(st->st_gid));
2222#endif
xdegaye50e86032017-05-22 11:15:08 +02002223 Py_BUILD_ASSERT(sizeof(long long) >= sizeof(st->st_size));
2224 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLongLong(st->st_size));
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002225
Martin v. Löwis14694662006-02-03 12:54:16 +00002226#if defined(HAVE_STAT_TV_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002227 ansec = st->st_atim.tv_nsec;
2228 mnsec = st->st_mtim.tv_nsec;
2229 cnsec = st->st_ctim.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002230#elif defined(HAVE_STAT_TV_NSEC2)
Victor Stinner8c62be82010-05-06 00:08:46 +00002231 ansec = st->st_atimespec.tv_nsec;
2232 mnsec = st->st_mtimespec.tv_nsec;
2233 cnsec = st->st_ctimespec.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002234#elif defined(HAVE_STAT_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002235 ansec = st->st_atime_nsec;
2236 mnsec = st->st_mtime_nsec;
2237 cnsec = st->st_ctime_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002238#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002239 ansec = mnsec = cnsec = 0;
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002240#endif
Victor Stinner4195b5c2012-02-08 23:03:19 +01002241 fill_time(v, 7, st->st_atime, ansec);
2242 fill_time(v, 8, st->st_mtime, mnsec);
2243 fill_time(v, 9, st->st_ctime, cnsec);
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002244
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002245#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00002246 PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
2247 PyLong_FromLong((long)st->st_blksize));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002248#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002249#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00002250 PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
2251 PyLong_FromLong((long)st->st_blocks));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002252#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002253#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00002254 PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
2255 PyLong_FromLong((long)st->st_rdev));
Fred Drake699f3522000-06-29 21:12:41 +00002256#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002257#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00002258 PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
2259 PyLong_FromLong((long)st->st_gen));
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002260#endif
2261#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00002262 {
Victor Stinner4195b5c2012-02-08 23:03:19 +01002263 PyObject *val;
2264 unsigned long bsec,bnsec;
2265 bsec = (long)st->st_birthtime;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002266#ifdef HAVE_STAT_TV_NSEC2
Victor Stinner4195b5c2012-02-08 23:03:19 +01002267 bnsec = st->st_birthtimespec.tv_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002268#else
Victor Stinner4195b5c2012-02-08 23:03:19 +01002269 bnsec = 0;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002270#endif
Victor Stinner01b5aab2017-10-24 02:02:00 -07002271 val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
Victor Stinner4195b5c2012-02-08 23:03:19 +01002272 PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
2273 val);
Victor Stinner8c62be82010-05-06 00:08:46 +00002274 }
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002275#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002276#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00002277 PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
2278 PyLong_FromLong((long)st->st_flags));
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002279#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05002280#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2281 PyStructSequence_SET_ITEM(v, ST_FILE_ATTRIBUTES_IDX,
2282 PyLong_FromUnsignedLong(st->st_file_attributes));
2283#endif
jcea6c51d512018-01-28 14:00:08 +01002284#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2285 PyStructSequence_SET_ITEM(v, ST_FSTYPE_IDX,
2286 PyUnicode_FromString(st->st_fstype));
2287#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002288#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2289 PyStructSequence_SET_ITEM(v, ST_REPARSE_TAG_IDX,
2290 PyLong_FromUnsignedLong(st->st_reparse_tag));
2291#endif
Fred Drake699f3522000-06-29 21:12:41 +00002292
Victor Stinner8c62be82010-05-06 00:08:46 +00002293 if (PyErr_Occurred()) {
2294 Py_DECREF(v);
2295 return NULL;
2296 }
Fred Drake699f3522000-06-29 21:12:41 +00002297
Victor Stinner8c62be82010-05-06 00:08:46 +00002298 return v;
Fred Drake699f3522000-06-29 21:12:41 +00002299}
2300
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002301/* POSIX methods */
2302
Guido van Rossum94f6f721999-01-06 18:42:14 +00002303
2304static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002305posix_do_stat(const char *function_name, path_t *path,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002306 int dir_fd, int follow_symlinks)
Guido van Rossum94f6f721999-01-06 18:42:14 +00002307{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002308 STRUCT_STAT st;
2309 int result;
2310
2311#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
2312 if (follow_symlinks_specified(function_name, follow_symlinks))
2313 return NULL;
2314#endif
2315
2316 if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
2317 dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
2318 fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
2319 return NULL;
2320
2321 Py_BEGIN_ALLOW_THREADS
2322 if (path->fd != -1)
2323 result = FSTAT(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002324#ifdef MS_WINDOWS
Steve Dower513d7472016-09-08 10:41:50 -07002325 else if (follow_symlinks)
Steve Dowercc16be82016-09-08 10:35:16 -07002326 result = win32_stat(path->wide, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002327 else
Steve Dowercc16be82016-09-08 10:35:16 -07002328 result = win32_lstat(path->wide, &st);
2329#else
2330 else
2331#if defined(HAVE_LSTAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002332 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
2333 result = LSTAT(path->narrow, &st);
2334 else
Steve Dowercc16be82016-09-08 10:35:16 -07002335#endif /* HAVE_LSTAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002336#ifdef HAVE_FSTATAT
2337 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks)
2338 result = fstatat(dir_fd, path->narrow, &st,
2339 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2340 else
Steve Dowercc16be82016-09-08 10:35:16 -07002341#endif /* HAVE_FSTATAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002342 result = STAT(path->narrow, &st);
Steve Dowercc16be82016-09-08 10:35:16 -07002343#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002344 Py_END_ALLOW_THREADS
2345
Victor Stinner292c8352012-10-30 02:17:38 +01002346 if (result != 0) {
2347 return path_error(path);
2348 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07002349
2350 return _pystat_fromstructstat(&st);
2351}
2352
Larry Hastings2f936352014-08-05 14:04:04 +10002353/*[python input]
2354
2355for s in """
2356
2357FACCESSAT
2358FCHMODAT
2359FCHOWNAT
2360FSTATAT
2361LINKAT
2362MKDIRAT
2363MKFIFOAT
2364MKNODAT
2365OPENAT
2366READLINKAT
2367SYMLINKAT
2368UNLINKAT
2369
2370""".strip().split():
2371 s = s.strip()
2372 print("""
2373#ifdef HAVE_{s}
2374 #define {s}_DIR_FD_CONVERTER dir_fd_converter
Larry Hastings31826802013-10-19 00:09:25 -07002375#else
Larry Hastings2f936352014-08-05 14:04:04 +10002376 #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings31826802013-10-19 00:09:25 -07002377#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002378""".rstrip().format(s=s))
2379
2380for s in """
2381
2382FCHDIR
2383FCHMOD
2384FCHOWN
2385FDOPENDIR
2386FEXECVE
2387FPATHCONF
2388FSTATVFS
2389FTRUNCATE
2390
2391""".strip().split():
2392 s = s.strip()
2393 print("""
2394#ifdef HAVE_{s}
2395 #define PATH_HAVE_{s} 1
2396#else
2397 #define PATH_HAVE_{s} 0
2398#endif
2399
2400""".rstrip().format(s=s))
2401[python start generated code]*/
2402
2403#ifdef HAVE_FACCESSAT
2404 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
2405#else
2406 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
2407#endif
2408
2409#ifdef HAVE_FCHMODAT
2410 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
2411#else
2412 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
2413#endif
2414
2415#ifdef HAVE_FCHOWNAT
2416 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
2417#else
2418 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
2419#endif
2420
2421#ifdef HAVE_FSTATAT
2422 #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
2423#else
2424 #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
2425#endif
2426
2427#ifdef HAVE_LINKAT
2428 #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
2429#else
2430 #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2431#endif
2432
2433#ifdef HAVE_MKDIRAT
2434 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
2435#else
2436 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
2437#endif
2438
2439#ifdef HAVE_MKFIFOAT
2440 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
2441#else
2442 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
2443#endif
2444
2445#ifdef HAVE_MKNODAT
2446 #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
2447#else
2448 #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
2449#endif
2450
2451#ifdef HAVE_OPENAT
2452 #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
2453#else
2454 #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
2455#endif
2456
2457#ifdef HAVE_READLINKAT
2458 #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
2459#else
2460 #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2461#endif
2462
2463#ifdef HAVE_SYMLINKAT
2464 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
2465#else
2466 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2467#endif
2468
2469#ifdef HAVE_UNLINKAT
2470 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
2471#else
2472 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2473#endif
2474
2475#ifdef HAVE_FCHDIR
2476 #define PATH_HAVE_FCHDIR 1
2477#else
2478 #define PATH_HAVE_FCHDIR 0
2479#endif
2480
2481#ifdef HAVE_FCHMOD
2482 #define PATH_HAVE_FCHMOD 1
2483#else
2484 #define PATH_HAVE_FCHMOD 0
2485#endif
2486
2487#ifdef HAVE_FCHOWN
2488 #define PATH_HAVE_FCHOWN 1
2489#else
2490 #define PATH_HAVE_FCHOWN 0
2491#endif
2492
2493#ifdef HAVE_FDOPENDIR
2494 #define PATH_HAVE_FDOPENDIR 1
2495#else
2496 #define PATH_HAVE_FDOPENDIR 0
2497#endif
2498
2499#ifdef HAVE_FEXECVE
2500 #define PATH_HAVE_FEXECVE 1
2501#else
2502 #define PATH_HAVE_FEXECVE 0
2503#endif
2504
2505#ifdef HAVE_FPATHCONF
2506 #define PATH_HAVE_FPATHCONF 1
2507#else
2508 #define PATH_HAVE_FPATHCONF 0
2509#endif
2510
2511#ifdef HAVE_FSTATVFS
2512 #define PATH_HAVE_FSTATVFS 1
2513#else
2514 #define PATH_HAVE_FSTATVFS 0
2515#endif
2516
2517#ifdef HAVE_FTRUNCATE
2518 #define PATH_HAVE_FTRUNCATE 1
2519#else
2520 #define PATH_HAVE_FTRUNCATE 0
2521#endif
2522/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
Larry Hastings31826802013-10-19 00:09:25 -07002523
Steve Dowerfe0a41a2015-03-20 19:50:46 -07002524#ifdef MS_WINDOWS
2525 #undef PATH_HAVE_FTRUNCATE
2526 #define PATH_HAVE_FTRUNCATE 1
2527#endif
Larry Hastings31826802013-10-19 00:09:25 -07002528
Larry Hastings61272b72014-01-07 12:41:53 -08002529/*[python input]
Larry Hastings31826802013-10-19 00:09:25 -07002530
2531class path_t_converter(CConverter):
2532
2533 type = "path_t"
2534 impl_by_reference = True
2535 parse_by_reference = True
2536
2537 converter = 'path_converter'
2538
2539 def converter_init(self, *, allow_fd=False, nullable=False):
Larry Hastings31826802013-10-19 00:09:25 -07002540 # right now path_t doesn't support default values.
2541 # to support a default value, you'll need to override initialize().
Larry Hastings2f936352014-08-05 14:04:04 +10002542 if self.default not in (unspecified, None):
Larry Hastings7726ac92014-01-31 22:03:12 -08002543 fail("Can't specify a default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002544
Larry Hastings2f936352014-08-05 14:04:04 +10002545 if self.c_default not in (None, 'Py_None'):
2546 raise RuntimeError("Can't specify a c_default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002547
2548 self.nullable = nullable
2549 self.allow_fd = allow_fd
2550
Larry Hastings7726ac92014-01-31 22:03:12 -08002551 def pre_render(self):
2552 def strify(value):
Larry Hastings2f936352014-08-05 14:04:04 +10002553 if isinstance(value, str):
2554 return value
Larry Hastings7726ac92014-01-31 22:03:12 -08002555 return str(int(bool(value)))
2556
2557 # add self.py_name here when merging with posixmodule conversion
Larry Hastings2f936352014-08-05 14:04:04 +10002558 self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
Larry Hastings31826802013-10-19 00:09:25 -07002559 self.function.name,
Larry Hastings2f936352014-08-05 14:04:04 +10002560 self.name,
Larry Hastings7726ac92014-01-31 22:03:12 -08002561 strify(self.nullable),
2562 strify(self.allow_fd),
Larry Hastings31826802013-10-19 00:09:25 -07002563 )
2564
2565 def cleanup(self):
2566 return "path_cleanup(&" + self.name + ");\n"
2567
2568
2569class dir_fd_converter(CConverter):
2570 type = 'int'
Larry Hastings31826802013-10-19 00:09:25 -07002571
Larry Hastings2f936352014-08-05 14:04:04 +10002572 def converter_init(self, requires=None):
Larry Hastings31826802013-10-19 00:09:25 -07002573 if self.default in (unspecified, None):
2574 self.c_default = 'DEFAULT_DIR_FD'
Larry Hastings2f936352014-08-05 14:04:04 +10002575 if isinstance(requires, str):
2576 self.converter = requires.upper() + '_DIR_FD_CONVERTER'
2577 else:
2578 self.converter = 'dir_fd_converter'
Larry Hastings31826802013-10-19 00:09:25 -07002579
Larry Hastings2f936352014-08-05 14:04:04 +10002580class fildes_converter(CConverter):
2581 type = 'int'
2582 converter = 'fildes_converter'
2583
2584class uid_t_converter(CConverter):
2585 type = "uid_t"
2586 converter = '_Py_Uid_Converter'
2587
2588class gid_t_converter(CConverter):
2589 type = "gid_t"
2590 converter = '_Py_Gid_Converter'
2591
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02002592class dev_t_converter(CConverter):
2593 type = 'dev_t'
2594 converter = '_Py_Dev_Converter'
2595
2596class dev_t_return_converter(unsigned_long_return_converter):
2597 type = 'dev_t'
2598 conversion_fn = '_PyLong_FromDev'
2599 unsigned_cast = '(dev_t)'
2600
Larry Hastings2f936352014-08-05 14:04:04 +10002601class FSConverter_converter(CConverter):
2602 type = 'PyObject *'
2603 converter = 'PyUnicode_FSConverter'
2604 def converter_init(self):
2605 if self.default is not unspecified:
2606 fail("FSConverter_converter does not support default values")
2607 self.c_default = 'NULL'
2608
2609 def cleanup(self):
2610 return "Py_XDECREF(" + self.name + ");\n"
2611
2612class pid_t_converter(CConverter):
2613 type = 'pid_t'
2614 format_unit = '" _Py_PARSE_PID "'
2615
2616class idtype_t_converter(int_converter):
2617 type = 'idtype_t'
2618
2619class id_t_converter(CConverter):
2620 type = 'id_t'
2621 format_unit = '" _Py_PARSE_PID "'
2622
Benjamin Petersonca470632016-09-06 13:47:26 -07002623class intptr_t_converter(CConverter):
2624 type = 'intptr_t'
Larry Hastings2f936352014-08-05 14:04:04 +10002625 format_unit = '" _Py_PARSE_INTPTR "'
2626
2627class Py_off_t_converter(CConverter):
2628 type = 'Py_off_t'
2629 converter = 'Py_off_t_converter'
2630
2631class Py_off_t_return_converter(long_return_converter):
2632 type = 'Py_off_t'
2633 conversion_fn = 'PyLong_FromPy_off_t'
2634
2635class path_confname_converter(CConverter):
2636 type="int"
2637 converter="conv_path_confname"
2638
2639class confstr_confname_converter(path_confname_converter):
2640 converter='conv_confstr_confname'
2641
2642class sysconf_confname_converter(path_confname_converter):
2643 converter="conv_sysconf_confname"
2644
2645class sched_param_converter(CConverter):
2646 type = 'struct sched_param'
2647 converter = 'convert_sched_param'
2648 impl_by_reference = True;
Larry Hastings31826802013-10-19 00:09:25 -07002649
Larry Hastings61272b72014-01-07 12:41:53 -08002650[python start generated code]*/
Victor Stinner581139c2016-09-06 15:54:20 -07002651/*[python end generated code: output=da39a3ee5e6b4b0d input=418fce0e01144461]*/
Larry Hastings31826802013-10-19 00:09:25 -07002652
Larry Hastings61272b72014-01-07 12:41:53 -08002653/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002654
Larry Hastings2a727912014-01-16 11:32:01 -08002655os.stat
Larry Hastings31826802013-10-19 00:09:25 -07002656
2657 path : path_t(allow_fd=True)
BNMetricsb9427072018-11-02 15:20:19 +00002658 Path to be examined; can be string, bytes, a path-like object or
Xiang Zhang4459e002017-01-22 13:04:17 +08002659 open-file-descriptor int.
Larry Hastings31826802013-10-19 00:09:25 -07002660
2661 *
2662
Larry Hastings2f936352014-08-05 14:04:04 +10002663 dir_fd : dir_fd(requires='fstatat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002664 If not None, it should be a file descriptor open to a directory,
2665 and path should be a relative string; path will then be relative to
2666 that directory.
2667
2668 follow_symlinks: bool = True
2669 If False, and the last element of the path is a symbolic link,
2670 stat will examine the symbolic link itself instead of the file
2671 the link points to.
2672
2673Perform a stat system call on the given path.
2674
2675dir_fd and follow_symlinks may not be implemented
2676 on your platform. If they are unavailable, using them will raise a
2677 NotImplementedError.
2678
2679It's an error to use dir_fd or follow_symlinks when specifying path as
2680 an open file descriptor.
2681
Larry Hastings61272b72014-01-07 12:41:53 -08002682[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002683
Larry Hastings31826802013-10-19 00:09:25 -07002684static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002685os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002686/*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
Larry Hastings31826802013-10-19 00:09:25 -07002687{
2688 return posix_do_stat("stat", path, dir_fd, follow_symlinks);
2689}
2690
Larry Hastings2f936352014-08-05 14:04:04 +10002691
2692/*[clinic input]
2693os.lstat
2694
2695 path : path_t
2696
2697 *
2698
2699 dir_fd : dir_fd(requires='fstatat') = None
2700
2701Perform a stat system call on the given path, without following symbolic links.
2702
2703Like stat(), but do not follow symbolic links.
2704Equivalent to stat(path, follow_symlinks=False).
2705[clinic start generated code]*/
2706
Larry Hastings2f936352014-08-05 14:04:04 +10002707static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002708os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
2709/*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002710{
2711 int follow_symlinks = 0;
2712 return posix_do_stat("lstat", path, dir_fd, follow_symlinks);
2713}
Larry Hastings31826802013-10-19 00:09:25 -07002714
Larry Hastings2f936352014-08-05 14:04:04 +10002715
Larry Hastings61272b72014-01-07 12:41:53 -08002716/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10002717os.access -> bool
Larry Hastings31826802013-10-19 00:09:25 -07002718
Benjamin Peterson768f3b42016-09-05 15:29:33 -07002719 path: path_t
BNMetricsb9427072018-11-02 15:20:19 +00002720 Path to be tested; can be string, bytes, or a path-like object.
Larry Hastings31826802013-10-19 00:09:25 -07002721
2722 mode: int
2723 Operating-system mode bitfield. Can be F_OK to test existence,
2724 or the inclusive-OR of R_OK, W_OK, and X_OK.
2725
2726 *
2727
Larry Hastings2f936352014-08-05 14:04:04 +10002728 dir_fd : dir_fd(requires='faccessat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002729 If not None, it should be a file descriptor open to a directory,
2730 and path should be relative; path will then be relative to that
2731 directory.
2732
2733 effective_ids: bool = False
2734 If True, access will use the effective uid/gid instead of
2735 the real uid/gid.
2736
2737 follow_symlinks: bool = True
2738 If False, and the last element of the path is a symbolic link,
2739 access will examine the symbolic link itself instead of the file
2740 the link points to.
2741
2742Use the real uid/gid to test for access to a path.
2743
2744{parameters}
2745dir_fd, effective_ids, and follow_symlinks may not be implemented
2746 on your platform. If they are unavailable, using them will raise a
2747 NotImplementedError.
2748
2749Note that most operations will use the effective uid/gid, therefore this
2750 routine can be used in a suid/sgid environment to test if the invoking user
2751 has the specified access to the path.
2752
Larry Hastings61272b72014-01-07 12:41:53 -08002753[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002754
Larry Hastings2f936352014-08-05 14:04:04 +10002755static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002756os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002757 int effective_ids, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002758/*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
Larry Hastings31826802013-10-19 00:09:25 -07002759{
Larry Hastings2f936352014-08-05 14:04:04 +10002760 int return_value;
Victor Stinner8c62be82010-05-06 00:08:46 +00002761
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002762#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002763 DWORD attr;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002764#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07002765 int result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002766#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07002767
Larry Hastings9cf065c2012-06-22 16:30:09 -07002768#ifndef HAVE_FACCESSAT
2769 if (follow_symlinks_specified("access", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002770 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002771
2772 if (effective_ids) {
2773 argument_unavailable_error("access", "effective_ids");
Larry Hastings2f936352014-08-05 14:04:04 +10002774 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002775 }
2776#endif
2777
2778#ifdef MS_WINDOWS
2779 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002780 attr = GetFileAttributesW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002781 Py_END_ALLOW_THREADS
2782
2783 /*
Georg Brandlf7875592012-06-24 13:58:31 +02002784 * Access is possible if
Larry Hastings9cf065c2012-06-22 16:30:09 -07002785 * * we didn't get a -1, and
2786 * * write access wasn't requested,
2787 * * or the file isn't read-only,
2788 * * or it's a directory.
2789 * (Directories cannot be read-only on Windows.)
2790 */
Larry Hastings2f936352014-08-05 14:04:04 +10002791 return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
Georg Brandl5bb7aa92012-06-23 12:48:40 +02002792 (!(mode & 2) ||
Larry Hastings9cf065c2012-06-22 16:30:09 -07002793 !(attr & FILE_ATTRIBUTE_READONLY) ||
Larry Hastings2f936352014-08-05 14:04:04 +10002794 (attr & FILE_ATTRIBUTE_DIRECTORY));
Larry Hastings9cf065c2012-06-22 16:30:09 -07002795#else
2796
2797 Py_BEGIN_ALLOW_THREADS
2798#ifdef HAVE_FACCESSAT
2799 if ((dir_fd != DEFAULT_DIR_FD) ||
2800 effective_ids ||
2801 !follow_symlinks) {
2802 int flags = 0;
2803 if (!follow_symlinks)
2804 flags |= AT_SYMLINK_NOFOLLOW;
2805 if (effective_ids)
2806 flags |= AT_EACCESS;
Larry Hastings31826802013-10-19 00:09:25 -07002807 result = faccessat(dir_fd, path->narrow, mode, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002808 }
2809 else
2810#endif
Larry Hastings31826802013-10-19 00:09:25 -07002811 result = access(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002812 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10002813 return_value = !result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002814#endif
2815
Larry Hastings9cf065c2012-06-22 16:30:09 -07002816 return return_value;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002817}
2818
Guido van Rossumd371ff11999-01-25 16:12:23 +00002819#ifndef F_OK
2820#define F_OK 0
2821#endif
2822#ifndef R_OK
2823#define R_OK 4
2824#endif
2825#ifndef W_OK
2826#define W_OK 2
2827#endif
2828#ifndef X_OK
2829#define X_OK 1
2830#endif
2831
Larry Hastings31826802013-10-19 00:09:25 -07002832
Guido van Rossumd371ff11999-01-25 16:12:23 +00002833#ifdef HAVE_TTYNAME
Larry Hastings61272b72014-01-07 12:41:53 -08002834/*[clinic input]
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002835os.ttyname
Larry Hastings31826802013-10-19 00:09:25 -07002836
2837 fd: int
2838 Integer file descriptor handle.
2839
2840 /
2841
2842Return the name of the terminal device connected to 'fd'.
Larry Hastings61272b72014-01-07 12:41:53 -08002843[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002844
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002845static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002846os_ttyname_impl(PyObject *module, int fd)
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002847/*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
Larry Hastings31826802013-10-19 00:09:25 -07002848{
Guido van Rossum94f6f721999-01-06 18:42:14 +00002849
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002850 long size = sysconf(_SC_TTY_NAME_MAX);
2851 if (size == -1) {
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002852 return posix_error();
2853 }
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002854 char *buffer = (char *)PyMem_RawMalloc(size);
2855 if (buffer == NULL) {
2856 return PyErr_NoMemory();
2857 }
2858 int ret = ttyname_r(fd, buffer, size);
2859 if (ret != 0) {
2860 PyMem_RawFree(buffer);
2861 errno = ret;
2862 return posix_error();
2863 }
2864 PyObject *res = PyUnicode_DecodeFSDefault(buffer);
2865 PyMem_RawFree(buffer);
2866 return res;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002867}
Guido van Rossumd371ff11999-01-25 16:12:23 +00002868#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +00002869
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002870#ifdef HAVE_CTERMID
Larry Hastings2f936352014-08-05 14:04:04 +10002871/*[clinic input]
2872os.ctermid
2873
2874Return the name of the controlling terminal for this process.
2875[clinic start generated code]*/
2876
Larry Hastings2f936352014-08-05 14:04:04 +10002877static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002878os_ctermid_impl(PyObject *module)
2879/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002880{
Victor Stinner8c62be82010-05-06 00:08:46 +00002881 char *ret;
2882 char buffer[L_ctermid];
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002883
Greg Wardb48bc172000-03-01 21:51:56 +00002884#ifdef USE_CTERMID_R
Victor Stinner8c62be82010-05-06 00:08:46 +00002885 ret = ctermid_r(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002886#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002887 ret = ctermid(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002888#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002889 if (ret == NULL)
2890 return posix_error();
Victor Stinner5fe6de82010-08-15 09:12:51 +00002891 return PyUnicode_DecodeFSDefault(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002892}
Larry Hastings2f936352014-08-05 14:04:04 +10002893#endif /* HAVE_CTERMID */
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002894
Larry Hastings2f936352014-08-05 14:04:04 +10002895
2896/*[clinic input]
2897os.chdir
2898
2899 path: path_t(allow_fd='PATH_HAVE_FCHDIR')
2900
2901Change the current working directory to the specified path.
2902
2903path may always be specified as a string.
2904On some platforms, path may also be specified as an open file descriptor.
2905 If this functionality is unavailable, using it raises an exception.
2906[clinic start generated code]*/
2907
Larry Hastings2f936352014-08-05 14:04:04 +10002908static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002909os_chdir_impl(PyObject *module, path_t *path)
2910/*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002911{
2912 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002913
2914 Py_BEGIN_ALLOW_THREADS
2915#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07002916 /* on unix, success = 0, on windows, success = !0 */
2917 result = !win32_wchdir(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002918#else
2919#ifdef HAVE_FCHDIR
Larry Hastings2f936352014-08-05 14:04:04 +10002920 if (path->fd != -1)
2921 result = fchdir(path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002922 else
2923#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002924 result = chdir(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002925#endif
2926 Py_END_ALLOW_THREADS
2927
2928 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002929 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002930 }
2931
Larry Hastings2f936352014-08-05 14:04:04 +10002932 Py_RETURN_NONE;
2933}
2934
2935
2936#ifdef HAVE_FCHDIR
2937/*[clinic input]
2938os.fchdir
2939
2940 fd: fildes
2941
2942Change to the directory of the given file descriptor.
2943
2944fd must be opened on a directory, not a file.
2945Equivalent to os.chdir(fd).
2946
2947[clinic start generated code]*/
2948
Fred Drake4d1e64b2002-04-15 19:40:07 +00002949static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002950os_fchdir_impl(PyObject *module, int fd)
2951/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
Fred Drake4d1e64b2002-04-15 19:40:07 +00002952{
Larry Hastings2f936352014-08-05 14:04:04 +10002953 return posix_fildes_fd(fd, fchdir);
Fred Drake4d1e64b2002-04-15 19:40:07 +00002954}
2955#endif /* HAVE_FCHDIR */
2956
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00002957
Larry Hastings2f936352014-08-05 14:04:04 +10002958/*[clinic input]
2959os.chmod
2960
2961 path: path_t(allow_fd='PATH_HAVE_FCHMOD')
BNMetricsb9427072018-11-02 15:20:19 +00002962 Path to be modified. May always be specified as a str, bytes, or a path-like object.
Larry Hastings2f936352014-08-05 14:04:04 +10002963 On some platforms, path may also be specified as an open file descriptor.
2964 If this functionality is unavailable, using it raises an exception.
2965
2966 mode: int
2967 Operating-system mode bitfield.
2968
2969 *
2970
2971 dir_fd : dir_fd(requires='fchmodat') = None
2972 If not None, it should be a file descriptor open to a directory,
2973 and path should be relative; path will then be relative to that
2974 directory.
2975
2976 follow_symlinks: bool = True
2977 If False, and the last element of the path is a symbolic link,
2978 chmod will modify the symbolic link itself instead of the file
2979 the link points to.
2980
2981Change the access permissions of a file.
2982
2983It is an error to use dir_fd or follow_symlinks when specifying path as
2984 an open file descriptor.
2985dir_fd and follow_symlinks may not be implemented on your platform.
2986 If they are unavailable, using them will raise a NotImplementedError.
2987
2988[clinic start generated code]*/
2989
Larry Hastings2f936352014-08-05 14:04:04 +10002990static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002991os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002992 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002993/*[clinic end generated code: output=5cf6a94915cc7bff input=989081551c00293b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002994{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002995 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002996
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002997#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002998 DWORD attr;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002999#endif
Hirokazu Yamamoto892a37a2009-06-28 11:07:03 +00003000
Larry Hastings9cf065c2012-06-22 16:30:09 -07003001#ifdef HAVE_FCHMODAT
3002 int fchmodat_nofollow_unsupported = 0;
3003#endif
3004
Larry Hastings9cf065c2012-06-22 16:30:09 -07003005#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
3006 if (follow_symlinks_specified("chmod", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003007 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003008#endif
3009
3010#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003011 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003012 attr = GetFileAttributesW(path->wide);
Tim Golden23005082013-10-25 11:22:37 +01003013 if (attr == INVALID_FILE_ATTRIBUTES)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003014 result = 0;
3015 else {
3016 if (mode & _S_IWRITE)
Victor Stinner8c62be82010-05-06 00:08:46 +00003017 attr &= ~FILE_ATTRIBUTE_READONLY;
3018 else
3019 attr |= FILE_ATTRIBUTE_READONLY;
Steve Dowercc16be82016-09-08 10:35:16 -07003020 result = SetFileAttributesW(path->wide, attr);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003021 }
3022 Py_END_ALLOW_THREADS
3023
3024 if (!result) {
Larry Hastings2f936352014-08-05 14:04:04 +10003025 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003026 }
3027#else /* MS_WINDOWS */
3028 Py_BEGIN_ALLOW_THREADS
3029#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003030 if (path->fd != -1)
3031 result = fchmod(path->fd, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003032 else
3033#endif
3034#ifdef HAVE_LCHMOD
3035 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003036 result = lchmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003037 else
3038#endif
3039#ifdef HAVE_FCHMODAT
3040 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
3041 /*
3042 * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
3043 * The documentation specifically shows how to use it,
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003044 * and then says it isn't implemented yet.
3045 * (true on linux with glibc 2.15, and openindiana 3.x)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003046 *
3047 * Once it is supported, os.chmod will automatically
3048 * support dir_fd and follow_symlinks=False. (Hopefully.)
3049 * Until then, we need to be careful what exception we raise.
3050 */
Larry Hastings2f936352014-08-05 14:04:04 +10003051 result = fchmodat(dir_fd, path->narrow, mode,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003052 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3053 /*
3054 * But wait! We can't throw the exception without allowing threads,
3055 * and we can't do that in this nested scope. (Macro trickery, sigh.)
3056 */
3057 fchmodat_nofollow_unsupported =
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003058 result &&
3059 ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
3060 !follow_symlinks;
Victor Stinner8c62be82010-05-06 00:08:46 +00003061 }
3062 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00003063#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003064 result = chmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003065 Py_END_ALLOW_THREADS
3066
3067 if (result) {
3068#ifdef HAVE_FCHMODAT
3069 if (fchmodat_nofollow_unsupported) {
3070 if (dir_fd != DEFAULT_DIR_FD)
3071 dir_fd_and_follow_symlinks_invalid("chmod",
3072 dir_fd, follow_symlinks);
3073 else
3074 follow_symlinks_specified("chmod", follow_symlinks);
Anthony Sottile233ef242017-12-14 08:57:55 -08003075 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003076 }
3077 else
3078#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003079 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003080 }
3081#endif
3082
Larry Hastings2f936352014-08-05 14:04:04 +10003083 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003084}
3085
Larry Hastings9cf065c2012-06-22 16:30:09 -07003086
Christian Heimes4e30a842007-11-30 22:12:06 +00003087#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003088/*[clinic input]
3089os.fchmod
3090
3091 fd: int
3092 mode: int
3093
3094Change the access permissions of the file given by file descriptor fd.
3095
3096Equivalent to os.chmod(fd, mode).
3097[clinic start generated code]*/
3098
Larry Hastings2f936352014-08-05 14:04:04 +10003099static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003100os_fchmod_impl(PyObject *module, int fd, int mode)
3101/*[clinic end generated code: output=afd9bc05b4e426b3 input=8ab11975ca01ee5b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003102{
3103 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003104 int async_err = 0;
3105
3106 do {
3107 Py_BEGIN_ALLOW_THREADS
3108 res = fchmod(fd, mode);
3109 Py_END_ALLOW_THREADS
3110 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3111 if (res != 0)
3112 return (!async_err) ? posix_error() : NULL;
3113
Victor Stinner8c62be82010-05-06 00:08:46 +00003114 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003115}
3116#endif /* HAVE_FCHMOD */
3117
Larry Hastings2f936352014-08-05 14:04:04 +10003118
Christian Heimes4e30a842007-11-30 22:12:06 +00003119#ifdef HAVE_LCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003120/*[clinic input]
3121os.lchmod
3122
3123 path: path_t
3124 mode: int
3125
3126Change the access permissions of a file, without following symbolic links.
3127
3128If path is a symlink, this affects the link itself rather than the target.
3129Equivalent to chmod(path, mode, follow_symlinks=False)."
3130[clinic start generated code]*/
3131
Larry Hastings2f936352014-08-05 14:04:04 +10003132static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003133os_lchmod_impl(PyObject *module, path_t *path, int mode)
3134/*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003135{
Victor Stinner8c62be82010-05-06 00:08:46 +00003136 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003137 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003138 res = lchmod(path->narrow, mode);
Victor Stinner8c62be82010-05-06 00:08:46 +00003139 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003140 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003141 path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003142 return NULL;
3143 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003144 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003145}
3146#endif /* HAVE_LCHMOD */
3147
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003148
Thomas Wouterscf297e42007-02-23 15:07:44 +00003149#ifdef HAVE_CHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003150/*[clinic input]
3151os.chflags
3152
3153 path: path_t
3154 flags: unsigned_long(bitwise=True)
3155 follow_symlinks: bool=True
3156
3157Set file flags.
3158
3159If follow_symlinks is False, and the last element of the path is a symbolic
3160 link, chflags will change flags on the symbolic link itself instead of the
3161 file the link points to.
3162follow_symlinks may not be implemented on your platform. If it is
3163unavailable, using it will raise a NotImplementedError.
3164
3165[clinic start generated code]*/
3166
Larry Hastings2f936352014-08-05 14:04:04 +10003167static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003168os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
Larry Hastings89964c42015-04-14 18:07:59 -04003169 int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003170/*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003171{
3172 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003173
3174#ifndef HAVE_LCHFLAGS
3175 if (follow_symlinks_specified("chflags", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003176 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003177#endif
3178
Victor Stinner8c62be82010-05-06 00:08:46 +00003179 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003180#ifdef HAVE_LCHFLAGS
3181 if (!follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +10003182 result = lchflags(path->narrow, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003183 else
3184#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003185 result = chflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003186 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003187
Larry Hastings2f936352014-08-05 14:04:04 +10003188 if (result)
3189 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003190
Larry Hastings2f936352014-08-05 14:04:04 +10003191 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003192}
3193#endif /* HAVE_CHFLAGS */
3194
Larry Hastings2f936352014-08-05 14:04:04 +10003195
Thomas Wouterscf297e42007-02-23 15:07:44 +00003196#ifdef HAVE_LCHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003197/*[clinic input]
3198os.lchflags
3199
3200 path: path_t
3201 flags: unsigned_long(bitwise=True)
3202
3203Set file flags.
3204
3205This function will not follow symbolic links.
3206Equivalent to chflags(path, flags, follow_symlinks=False).
3207[clinic start generated code]*/
3208
Larry Hastings2f936352014-08-05 14:04:04 +10003209static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003210os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
3211/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003212{
Victor Stinner8c62be82010-05-06 00:08:46 +00003213 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003214 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003215 res = lchflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003216 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003217 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003218 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003219 }
Victor Stinner292c8352012-10-30 02:17:38 +01003220 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003221}
3222#endif /* HAVE_LCHFLAGS */
3223
Larry Hastings2f936352014-08-05 14:04:04 +10003224
Martin v. Löwis244edc82001-10-04 22:44:26 +00003225#ifdef HAVE_CHROOT
Larry Hastings2f936352014-08-05 14:04:04 +10003226/*[clinic input]
3227os.chroot
3228 path: path_t
3229
3230Change root directory to path.
3231
3232[clinic start generated code]*/
3233
Larry Hastings2f936352014-08-05 14:04:04 +10003234static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003235os_chroot_impl(PyObject *module, path_t *path)
3236/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003237{
3238 int res;
3239 Py_BEGIN_ALLOW_THREADS
3240 res = chroot(path->narrow);
3241 Py_END_ALLOW_THREADS
3242 if (res < 0)
3243 return path_error(path);
3244 Py_RETURN_NONE;
3245}
3246#endif /* HAVE_CHROOT */
3247
Martin v. Löwis244edc82001-10-04 22:44:26 +00003248
Guido van Rossum21142a01999-01-08 21:05:37 +00003249#ifdef HAVE_FSYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003250/*[clinic input]
3251os.fsync
3252
3253 fd: fildes
3254
3255Force write of fd to disk.
3256[clinic start generated code]*/
3257
Larry Hastings2f936352014-08-05 14:04:04 +10003258static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003259os_fsync_impl(PyObject *module, int fd)
3260/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003261{
3262 return posix_fildes_fd(fd, fsync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003263}
3264#endif /* HAVE_FSYNC */
3265
Larry Hastings2f936352014-08-05 14:04:04 +10003266
Ross Lagerwall7807c352011-03-17 20:20:30 +02003267#ifdef HAVE_SYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003268/*[clinic input]
3269os.sync
3270
3271Force write of everything to disk.
3272[clinic start generated code]*/
3273
Larry Hastings2f936352014-08-05 14:04:04 +10003274static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003275os_sync_impl(PyObject *module)
3276/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
Ross Lagerwall7807c352011-03-17 20:20:30 +02003277{
3278 Py_BEGIN_ALLOW_THREADS
3279 sync();
3280 Py_END_ALLOW_THREADS
3281 Py_RETURN_NONE;
3282}
Larry Hastings2f936352014-08-05 14:04:04 +10003283#endif /* HAVE_SYNC */
3284
Ross Lagerwall7807c352011-03-17 20:20:30 +02003285
Guido van Rossum21142a01999-01-08 21:05:37 +00003286#ifdef HAVE_FDATASYNC
Guido van Rossum7f58e2e2000-09-22 17:26:14 +00003287#ifdef __hpux
Guido van Rossumecc23b02000-09-22 16:01:05 +00003288extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
3289#endif
3290
Larry Hastings2f936352014-08-05 14:04:04 +10003291/*[clinic input]
3292os.fdatasync
3293
3294 fd: fildes
3295
3296Force write of fd to disk without forcing update of metadata.
3297[clinic start generated code]*/
3298
Larry Hastings2f936352014-08-05 14:04:04 +10003299static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003300os_fdatasync_impl(PyObject *module, int fd)
3301/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003302{
3303 return posix_fildes_fd(fd, fdatasync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003304}
3305#endif /* HAVE_FDATASYNC */
3306
3307
Fredrik Lundh10723342000-07-10 16:38:09 +00003308#ifdef HAVE_CHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003309/*[clinic input]
3310os.chown
3311
3312 path : path_t(allow_fd='PATH_HAVE_FCHOWN')
BNMetricsb9427072018-11-02 15:20:19 +00003313 Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
Larry Hastings2f936352014-08-05 14:04:04 +10003314
3315 uid: uid_t
3316
3317 gid: gid_t
3318
3319 *
3320
3321 dir_fd : dir_fd(requires='fchownat') = None
3322 If not None, it should be a file descriptor open to a directory,
3323 and path should be relative; path will then be relative to that
3324 directory.
3325
3326 follow_symlinks: bool = True
3327 If False, and the last element of the path is a symbolic link,
3328 stat will examine the symbolic link itself instead of the file
3329 the link points to.
3330
3331Change the owner and group id of path to the numeric uid and gid.\
3332
3333path may always be specified as a string.
3334On some platforms, path may also be specified as an open file descriptor.
3335 If this functionality is unavailable, using it raises an exception.
3336If dir_fd is not None, it should be a file descriptor open to a directory,
3337 and path should be relative; path will then be relative to that directory.
3338If follow_symlinks is False, and the last element of the path is a symbolic
3339 link, chown will modify the symbolic link itself instead of the file the
3340 link points to.
3341It is an error to use dir_fd or follow_symlinks when specifying path as
3342 an open file descriptor.
3343dir_fd and follow_symlinks may not be implemented on your platform.
3344 If they are unavailable, using them will raise a NotImplementedError.
3345
3346[clinic start generated code]*/
3347
Larry Hastings2f936352014-08-05 14:04:04 +10003348static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003349os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
Larry Hastings89964c42015-04-14 18:07:59 -04003350 int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003351/*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003352{
3353 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003354
3355#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
3356 if (follow_symlinks_specified("chown", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003357 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003358#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003359 if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
3360 fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
3361 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003362
3363#ifdef __APPLE__
3364 /*
3365 * This is for Mac OS X 10.3, which doesn't have lchown.
3366 * (But we still have an lchown symbol because of weak-linking.)
3367 * It doesn't have fchownat either. So there's no possibility
3368 * of a graceful failover.
Georg Brandlf7875592012-06-24 13:58:31 +02003369 */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003370 if ((!follow_symlinks) && (lchown == NULL)) {
3371 follow_symlinks_specified("chown", follow_symlinks);
Larry Hastings2f936352014-08-05 14:04:04 +10003372 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003373 }
3374#endif
3375
Victor Stinner8c62be82010-05-06 00:08:46 +00003376 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003377#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003378 if (path->fd != -1)
3379 result = fchown(path->fd, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003380 else
3381#endif
3382#ifdef HAVE_LCHOWN
3383 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003384 result = lchown(path->narrow, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003385 else
3386#endif
3387#ifdef HAVE_FCHOWNAT
3388 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003389 result = fchownat(dir_fd, path->narrow, uid, gid,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003390 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3391 else
3392#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003393 result = chown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003394 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003395
Larry Hastings2f936352014-08-05 14:04:04 +10003396 if (result)
3397 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003398
Larry Hastings2f936352014-08-05 14:04:04 +10003399 Py_RETURN_NONE;
Guido van Rossumb6775db1994-08-01 11:34:53 +00003400}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003401#endif /* HAVE_CHOWN */
Guido van Rossumb6775db1994-08-01 11:34:53 +00003402
Larry Hastings2f936352014-08-05 14:04:04 +10003403
Christian Heimes4e30a842007-11-30 22:12:06 +00003404#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003405/*[clinic input]
3406os.fchown
3407
3408 fd: int
3409 uid: uid_t
3410 gid: gid_t
3411
3412Change the owner and group id of the file specified by file descriptor.
3413
3414Equivalent to os.chown(fd, uid, gid).
3415
3416[clinic start generated code]*/
3417
Larry Hastings2f936352014-08-05 14:04:04 +10003418static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003419os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
3420/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003421{
Victor Stinner8c62be82010-05-06 00:08:46 +00003422 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003423 int async_err = 0;
3424
3425 do {
3426 Py_BEGIN_ALLOW_THREADS
3427 res = fchown(fd, uid, gid);
3428 Py_END_ALLOW_THREADS
3429 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3430 if (res != 0)
3431 return (!async_err) ? posix_error() : NULL;
3432
Victor Stinner8c62be82010-05-06 00:08:46 +00003433 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003434}
3435#endif /* HAVE_FCHOWN */
3436
Larry Hastings2f936352014-08-05 14:04:04 +10003437
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003438#ifdef HAVE_LCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003439/*[clinic input]
3440os.lchown
3441
3442 path : path_t
3443 uid: uid_t
3444 gid: gid_t
3445
3446Change the owner and group id of path to the numeric uid and gid.
3447
3448This function will not follow symbolic links.
3449Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
3450[clinic start generated code]*/
3451
Larry Hastings2f936352014-08-05 14:04:04 +10003452static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003453os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
3454/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003455{
Victor Stinner8c62be82010-05-06 00:08:46 +00003456 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003457 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10003458 res = lchown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003459 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003460 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003461 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003462 }
Larry Hastings2f936352014-08-05 14:04:04 +10003463 Py_RETURN_NONE;
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003464}
3465#endif /* HAVE_LCHOWN */
3466
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003467
Barry Warsaw53699e91996-12-10 23:23:01 +00003468static PyObject *
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003469posix_getcwd(int use_bytes)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003470{
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003471#ifdef MS_WINDOWS
Victor Stinner689830e2019-06-26 17:31:12 +02003472 wchar_t wbuf[MAXPATHLEN];
3473 wchar_t *wbuf2 = wbuf;
3474 DWORD len;
3475
3476 Py_BEGIN_ALLOW_THREADS
3477 len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
3478 /* If the buffer is large enough, len does not include the
3479 terminating \0. If the buffer is too small, len includes
3480 the space needed for the terminator. */
3481 if (len >= Py_ARRAY_LENGTH(wbuf)) {
Victor Stinnerec3e20a2019-06-28 18:01:59 +02003482 if (len <= PY_SSIZE_T_MAX / sizeof(wchar_t)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02003483 wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00003484 }
Victor Stinner689830e2019-06-26 17:31:12 +02003485 else {
3486 wbuf2 = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003487 }
Victor Stinner689830e2019-06-26 17:31:12 +02003488 if (wbuf2) {
3489 len = GetCurrentDirectoryW(len, wbuf2);
Victor Stinner8c62be82010-05-06 00:08:46 +00003490 }
Victor Stinner689830e2019-06-26 17:31:12 +02003491 }
3492 Py_END_ALLOW_THREADS
3493
3494 if (!wbuf2) {
3495 PyErr_NoMemory();
3496 return NULL;
3497 }
3498 if (!len) {
Victor Stinnerb024e842012-10-31 22:24:06 +01003499 if (wbuf2 != wbuf)
Victor Stinnerb6404912013-07-07 16:21:41 +02003500 PyMem_RawFree(wbuf2);
Victor Stinner689830e2019-06-26 17:31:12 +02003501 return PyErr_SetFromWindowsErr(0);
Victor Stinner8c62be82010-05-06 00:08:46 +00003502 }
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01003503
Victor Stinner689830e2019-06-26 17:31:12 +02003504 PyObject *resobj = PyUnicode_FromWideChar(wbuf2, len);
3505 if (wbuf2 != wbuf) {
3506 PyMem_RawFree(wbuf2);
3507 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003508
Victor Stinner689830e2019-06-26 17:31:12 +02003509 if (use_bytes) {
3510 if (resobj == NULL) {
3511 return NULL;
3512 }
3513 Py_SETREF(resobj, PyUnicode_EncodeFSDefault(resobj));
3514 }
3515
3516 return resobj;
3517#else
3518 const size_t chunk = 1024;
3519
3520 char *buf = NULL;
3521 char *cwd = NULL;
3522 size_t buflen = 0;
3523
Victor Stinner8c62be82010-05-06 00:08:46 +00003524 Py_BEGIN_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003525 do {
Victor Stinner689830e2019-06-26 17:31:12 +02003526 char *newbuf;
3527 if (buflen <= PY_SSIZE_T_MAX - chunk) {
3528 buflen += chunk;
3529 newbuf = PyMem_RawRealloc(buf, buflen);
3530 }
3531 else {
3532 newbuf = NULL;
3533 }
3534 if (newbuf == NULL) {
3535 PyMem_RawFree(buf);
3536 buf = NULL;
Victor Stinnerc44f7072016-03-14 18:07:53 +01003537 break;
3538 }
Victor Stinner689830e2019-06-26 17:31:12 +02003539 buf = newbuf;
Victor Stinner4403d7d2015-04-25 00:16:10 +02003540
Victor Stinner4403d7d2015-04-25 00:16:10 +02003541 cwd = getcwd(buf, buflen);
3542 } while (cwd == NULL && errno == ERANGE);
Victor Stinner8c62be82010-05-06 00:08:46 +00003543 Py_END_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003544
Victor Stinner689830e2019-06-26 17:31:12 +02003545 if (buf == NULL) {
3546 return PyErr_NoMemory();
3547 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003548 if (cwd == NULL) {
3549 PyMem_RawFree(buf);
Victor Stinner8c62be82010-05-06 00:08:46 +00003550 return posix_error();
Victor Stinner4403d7d2015-04-25 00:16:10 +02003551 }
3552
Victor Stinner689830e2019-06-26 17:31:12 +02003553 PyObject *obj;
3554 if (use_bytes) {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003555 obj = PyBytes_FromStringAndSize(buf, strlen(buf));
Victor Stinner689830e2019-06-26 17:31:12 +02003556 }
3557 else {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003558 obj = PyUnicode_DecodeFSDefault(buf);
Victor Stinner689830e2019-06-26 17:31:12 +02003559 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003560 PyMem_RawFree(buf);
3561
3562 return obj;
Victor Stinner689830e2019-06-26 17:31:12 +02003563#endif /* !MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003564}
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003565
Larry Hastings2f936352014-08-05 14:04:04 +10003566
3567/*[clinic input]
3568os.getcwd
3569
3570Return a unicode string representing the current working directory.
3571[clinic start generated code]*/
3572
Larry Hastings2f936352014-08-05 14:04:04 +10003573static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003574os_getcwd_impl(PyObject *module)
3575/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003576{
3577 return posix_getcwd(0);
3578}
3579
Larry Hastings2f936352014-08-05 14:04:04 +10003580
3581/*[clinic input]
3582os.getcwdb
3583
3584Return a bytes string representing the current working directory.
3585[clinic start generated code]*/
3586
Larry Hastings2f936352014-08-05 14:04:04 +10003587static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003588os_getcwdb_impl(PyObject *module)
3589/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003590{
3591 return posix_getcwd(1);
3592}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003593
Larry Hastings2f936352014-08-05 14:04:04 +10003594
Larry Hastings9cf065c2012-06-22 16:30:09 -07003595#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
3596#define HAVE_LINK 1
3597#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003598
Guido van Rossumb6775db1994-08-01 11:34:53 +00003599#ifdef HAVE_LINK
Larry Hastings2f936352014-08-05 14:04:04 +10003600/*[clinic input]
3601
3602os.link
3603
3604 src : path_t
3605 dst : path_t
3606 *
3607 src_dir_fd : dir_fd = None
3608 dst_dir_fd : dir_fd = None
3609 follow_symlinks: bool = True
3610
3611Create a hard link to a file.
3612
3613If either src_dir_fd or dst_dir_fd is not None, it should be a file
3614 descriptor open to a directory, and the respective path string (src or dst)
3615 should be relative; the path will then be relative to that directory.
3616If follow_symlinks is False, and the last element of src is a symbolic
3617 link, link will create a link to the symbolic link itself instead of the
3618 file the link points to.
3619src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
3620 platform. If they are unavailable, using them will raise a
3621 NotImplementedError.
3622[clinic start generated code]*/
3623
Larry Hastings2f936352014-08-05 14:04:04 +10003624static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003625os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003626 int dst_dir_fd, int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003627/*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003628{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003629#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07003630 BOOL result = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003631#else
3632 int result;
3633#endif
3634
Larry Hastings9cf065c2012-06-22 16:30:09 -07003635#ifndef HAVE_LINKAT
3636 if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
3637 argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10003638 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003639 }
3640#endif
3641
Steve Dowercc16be82016-09-08 10:35:16 -07003642#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10003643 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003644 PyErr_SetString(PyExc_NotImplementedError,
3645 "link: src and dst must be the same type");
Larry Hastings2f936352014-08-05 14:04:04 +10003646 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003647 }
Steve Dowercc16be82016-09-08 10:35:16 -07003648#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003649
Brian Curtin1b9df392010-11-24 20:24:31 +00003650#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003651 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08003652 result = CreateHardLinkW(dst->wide, src->wide, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003653 Py_END_ALLOW_THREADS
Brian Curtin1b9df392010-11-24 20:24:31 +00003654
Larry Hastings2f936352014-08-05 14:04:04 +10003655 if (!result)
3656 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003657#else
3658 Py_BEGIN_ALLOW_THREADS
Larry Hastings67cbf7b2012-06-22 17:06:48 -07003659#ifdef HAVE_LINKAT
Larry Hastings9cf065c2012-06-22 16:30:09 -07003660 if ((src_dir_fd != DEFAULT_DIR_FD) ||
3661 (dst_dir_fd != DEFAULT_DIR_FD) ||
3662 (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003663 result = linkat(src_dir_fd, src->narrow,
3664 dst_dir_fd, dst->narrow,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003665 follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
3666 else
Steve Dowercc16be82016-09-08 10:35:16 -07003667#endif /* HAVE_LINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10003668 result = link(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003669 Py_END_ALLOW_THREADS
Brian Curtinfc889c42010-11-28 23:59:46 +00003670
Larry Hastings2f936352014-08-05 14:04:04 +10003671 if (result)
3672 return path_error2(src, dst);
Steve Dowercc16be82016-09-08 10:35:16 -07003673#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003674
Larry Hastings2f936352014-08-05 14:04:04 +10003675 Py_RETURN_NONE;
Brian Curtin1b9df392010-11-24 20:24:31 +00003676}
Larry Hastings9cf065c2012-06-22 16:30:09 -07003677#endif
3678
Brian Curtin1b9df392010-11-24 20:24:31 +00003679
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003680#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
Barry Warsaw53699e91996-12-10 23:23:01 +00003681static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003682_listdir_windows_no_opendir(path_t *path, PyObject *list)
Guido van Rossumb6775db1994-08-01 11:34:53 +00003683{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003684 PyObject *v;
3685 HANDLE hFindFile = INVALID_HANDLE_VALUE;
3686 BOOL result;
Steve Dowercc16be82016-09-08 10:35:16 -07003687 wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003688 /* only claim to have space for MAX_PATH */
Victor Stinner75875072013-11-24 19:23:25 +01003689 Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003690 wchar_t *wnamebuf = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003691
Steve Dowercc16be82016-09-08 10:35:16 -07003692 WIN32_FIND_DATAW wFileData;
3693 const wchar_t *po_wchars;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003694
Steve Dowercc16be82016-09-08 10:35:16 -07003695 if (!path->wide) { /* Default arg: "." */
3696 po_wchars = L".";
3697 len = 1;
3698 } else {
3699 po_wchars = path->wide;
3700 len = wcslen(path->wide);
3701 }
3702 /* The +5 is so we can append "\\*.*\0" */
3703 wnamebuf = PyMem_New(wchar_t, len + 5);
3704 if (!wnamebuf) {
3705 PyErr_NoMemory();
Larry Hastings9cf065c2012-06-22 16:30:09 -07003706 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003707 }
Steve Dowercc16be82016-09-08 10:35:16 -07003708 wcscpy(wnamebuf, po_wchars);
Victor Stinner8c62be82010-05-06 00:08:46 +00003709 if (len > 0) {
Steve Dowercc16be82016-09-08 10:35:16 -07003710 wchar_t wch = wnamebuf[len-1];
3711 if (wch != SEP && wch != ALTSEP && wch != L':')
3712 wnamebuf[len++] = SEP;
3713 wcscpy(wnamebuf + len, L"*.*");
Victor Stinner8c62be82010-05-06 00:08:46 +00003714 }
Steve Dowercc16be82016-09-08 10:35:16 -07003715 if ((list = PyList_New(0)) == NULL) {
3716 goto exit;
3717 }
Antoine Pitroub73caab2010-08-09 23:39:31 +00003718 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003719 hFindFile = FindFirstFileW(wnamebuf, &wFileData);
Antoine Pitroub73caab2010-08-09 23:39:31 +00003720 Py_END_ALLOW_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +00003721 if (hFindFile == INVALID_HANDLE_VALUE) {
3722 int error = GetLastError();
3723 if (error == ERROR_FILE_NOT_FOUND)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003724 goto exit;
3725 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003726 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003727 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003728 }
3729 do {
3730 /* Skip over . and .. */
Steve Dowercc16be82016-09-08 10:35:16 -07003731 if (wcscmp(wFileData.cFileName, L".") != 0 &&
3732 wcscmp(wFileData.cFileName, L"..") != 0) {
3733 v = PyUnicode_FromWideChar(wFileData.cFileName,
3734 wcslen(wFileData.cFileName));
3735 if (path->narrow && v) {
3736 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3737 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003738 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003739 Py_DECREF(list);
3740 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003741 break;
3742 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003743 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003744 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003745 Py_DECREF(list);
3746 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003747 break;
3748 }
3749 Py_DECREF(v);
3750 }
3751 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003752 result = FindNextFileW(hFindFile, &wFileData);
Victor Stinner8c62be82010-05-06 00:08:46 +00003753 Py_END_ALLOW_THREADS
3754 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
3755 it got to the end of the directory. */
3756 if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003757 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003758 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003759 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003760 }
3761 } while (result == TRUE);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003762
Larry Hastings9cf065c2012-06-22 16:30:09 -07003763exit:
3764 if (hFindFile != INVALID_HANDLE_VALUE) {
3765 if (FindClose(hFindFile) == FALSE) {
3766 if (list != NULL) {
3767 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003768 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003769 }
3770 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003771 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003772 PyMem_Free(wnamebuf);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003773
Larry Hastings9cf065c2012-06-22 16:30:09 -07003774 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003775} /* end of _listdir_windows_no_opendir */
3776
3777#else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
3778
3779static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003780_posix_listdir(path_t *path, PyObject *list)
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003781{
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003782 PyObject *v;
3783 DIR *dirp = NULL;
3784 struct dirent *ep;
3785 int return_str; /* if false, return bytes */
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003786#ifdef HAVE_FDOPENDIR
3787 int fd = -1;
3788#endif
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003789
Victor Stinner8c62be82010-05-06 00:08:46 +00003790 errno = 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003791#ifdef HAVE_FDOPENDIR
Gregory P. Smith40a21602013-03-20 20:52:50 -07003792 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003793 /* closedir() closes the FD, so we duplicate it */
Victor Stinnerdaf45552013-08-28 00:53:59 +02003794 fd = _Py_dup(path->fd);
Victor Stinnerf3266652013-12-19 13:24:49 +01003795 if (fd == -1)
3796 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003797
Larry Hastingsfdaea062012-06-25 04:42:23 -07003798 return_str = 1;
3799
Larry Hastings9cf065c2012-06-22 16:30:09 -07003800 Py_BEGIN_ALLOW_THREADS
3801 dirp = fdopendir(fd);
3802 Py_END_ALLOW_THREADS
3803 }
3804 else
3805#endif
3806 {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003807 const char *name;
Gregory P. Smith40a21602013-03-20 20:52:50 -07003808 if (path->narrow) {
3809 name = path->narrow;
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03003810 /* only return bytes if they specified a bytes-like object */
3811 return_str = !PyObject_CheckBuffer(path->object);
Larry Hastingsfdaea062012-06-25 04:42:23 -07003812 }
3813 else {
3814 name = ".";
3815 return_str = 1;
3816 }
3817
Larry Hastings9cf065c2012-06-22 16:30:09 -07003818 Py_BEGIN_ALLOW_THREADS
3819 dirp = opendir(name);
3820 Py_END_ALLOW_THREADS
3821 }
3822
3823 if (dirp == NULL) {
Gregory P. Smith40a21602013-03-20 20:52:50 -07003824 list = path_error(path);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003825#ifdef HAVE_FDOPENDIR
3826 if (fd != -1) {
3827 Py_BEGIN_ALLOW_THREADS
3828 close(fd);
3829 Py_END_ALLOW_THREADS
3830 }
3831#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003832 goto exit;
3833 }
3834 if ((list = PyList_New(0)) == NULL) {
3835 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003836 }
3837 for (;;) {
3838 errno = 0;
3839 Py_BEGIN_ALLOW_THREADS
3840 ep = readdir(dirp);
3841 Py_END_ALLOW_THREADS
3842 if (ep == NULL) {
3843 if (errno == 0) {
3844 break;
3845 } else {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003846 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003847 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003848 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003849 }
3850 }
3851 if (ep->d_name[0] == '.' &&
3852 (NAMLEN(ep) == 1 ||
3853 (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
3854 continue;
Larry Hastingsfdaea062012-06-25 04:42:23 -07003855 if (return_str)
Victor Stinnera45598a2010-05-14 16:35:39 +00003856 v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
3857 else
3858 v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
Victor Stinner8c62be82010-05-06 00:08:46 +00003859 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003860 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003861 break;
3862 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003863 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003864 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003865 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003866 break;
3867 }
3868 Py_DECREF(v);
3869 }
Guido van Rossum0ee42cd1991-04-08 21:01:03 +00003870
Larry Hastings9cf065c2012-06-22 16:30:09 -07003871exit:
3872 if (dirp != NULL) {
3873 Py_BEGIN_ALLOW_THREADS
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003874#ifdef HAVE_FDOPENDIR
Larry Hastings9cf065c2012-06-22 16:30:09 -07003875 if (fd > -1)
3876 rewinddir(dirp);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003877#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003878 closedir(dirp);
3879 Py_END_ALLOW_THREADS
3880 }
3881
Larry Hastings9cf065c2012-06-22 16:30:09 -07003882 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003883} /* end of _posix_listdir */
3884#endif /* which OS */
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003885
Larry Hastings2f936352014-08-05 14:04:04 +10003886
3887/*[clinic input]
3888os.listdir
3889
3890 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
3891
3892Return a list containing the names of the files in the directory.
3893
BNMetricsb9427072018-11-02 15:20:19 +00003894path can be specified as either str, bytes, or a path-like object. If path is bytes,
Larry Hastings2f936352014-08-05 14:04:04 +10003895 the filenames returned will also be bytes; in all other circumstances
3896 the filenames returned will be str.
3897If path is None, uses the path='.'.
3898On some platforms, path may also be specified as an open file descriptor;\
3899 the file descriptor must refer to a directory.
3900 If this functionality is unavailable, using it raises NotImplementedError.
3901
3902The list is in arbitrary order. It does not include the special
3903entries '.' and '..' even if they are present in the directory.
3904
3905
3906[clinic start generated code]*/
3907
Larry Hastings2f936352014-08-05 14:04:04 +10003908static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003909os_listdir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +00003910/*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003911{
Steve Dower60419a72019-06-24 08:42:54 -07003912 if (PySys_Audit("os.listdir", "O",
3913 path->object ? path->object : Py_None) < 0) {
3914 return NULL;
3915 }
Larry Hastings2f936352014-08-05 14:04:04 +10003916#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
3917 return _listdir_windows_no_opendir(path, NULL);
3918#else
3919 return _posix_listdir(path, NULL);
3920#endif
3921}
3922
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00003923#ifdef MS_WINDOWS
Mark Hammondef8b6542001-05-13 08:04:26 +00003924/* A helper function for abspath on win32 */
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003925/*[clinic input]
3926os._getfullpathname
Victor Stinnereb5657a2011-09-30 01:44:27 +02003927
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003928 path: path_t
3929 /
3930
3931[clinic start generated code]*/
3932
3933static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003934os__getfullpathname_impl(PyObject *module, path_t *path)
3935/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003936{
Victor Stinner3939c322019-06-25 15:02:43 +02003937 wchar_t *abspath;
Victor Stinnereb5657a2011-09-30 01:44:27 +02003938
Victor Stinner3939c322019-06-25 15:02:43 +02003939 /* _Py_abspath() is implemented with GetFullPathNameW() on Windows */
3940 if (_Py_abspath(path->wide, &abspath) < 0) {
3941 return win32_error_object("GetFullPathNameW", path->object);
Victor Stinner8c62be82010-05-06 00:08:46 +00003942 }
Victor Stinner3939c322019-06-25 15:02:43 +02003943 if (abspath == NULL) {
3944 return PyErr_NoMemory();
3945 }
3946
3947 PyObject *str = PyUnicode_FromWideChar(abspath, wcslen(abspath));
3948 PyMem_RawFree(abspath);
3949 if (str == NULL) {
3950 return NULL;
3951 }
3952 if (path->narrow) {
3953 Py_SETREF(str, PyUnicode_EncodeFSDefault(str));
3954 }
3955 return str;
Larry Hastings2f936352014-08-05 14:04:04 +10003956}
Brian Curtind40e6f72010-07-08 21:39:08 +00003957
Brian Curtind25aef52011-06-13 15:16:04 -05003958
Larry Hastings2f936352014-08-05 14:04:04 +10003959/*[clinic input]
3960os._getfinalpathname
Brian Curtinf5e76d02010-11-24 13:14:05 +00003961
Steve Dower23ad6d02018-02-22 10:39:10 -08003962 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10003963 /
3964
3965A helper function for samepath on windows.
3966[clinic start generated code]*/
3967
Larry Hastings2f936352014-08-05 14:04:04 +10003968static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08003969os__getfinalpathname_impl(PyObject *module, path_t *path)
3970/*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
Brian Curtind40e6f72010-07-08 21:39:08 +00003971{
3972 HANDLE hFile;
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003973 wchar_t buf[MAXPATHLEN], *target_path = buf;
3974 int buf_size = Py_ARRAY_LENGTH(buf);
Brian Curtind40e6f72010-07-08 21:39:08 +00003975 int result_length;
Larry Hastings2f936352014-08-05 14:04:04 +10003976 PyObject *result;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003977
Steve Dower23ad6d02018-02-22 10:39:10 -08003978 Py_BEGIN_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00003979 hFile = CreateFileW(
Steve Dower23ad6d02018-02-22 10:39:10 -08003980 path->wide,
Brian Curtind40e6f72010-07-08 21:39:08 +00003981 0, /* desired access */
3982 0, /* share mode */
3983 NULL, /* security attributes */
3984 OPEN_EXISTING,
3985 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
3986 FILE_FLAG_BACKUP_SEMANTICS,
3987 NULL);
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003988 Py_END_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003989
Steve Dower23ad6d02018-02-22 10:39:10 -08003990 if (hFile == INVALID_HANDLE_VALUE) {
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003991 return win32_error_object("CreateFileW", path->object);
Steve Dower23ad6d02018-02-22 10:39:10 -08003992 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003993
3994 /* We have a good handle to the target, use it to determine the
3995 target path name. */
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003996 while (1) {
3997 Py_BEGIN_ALLOW_THREADS
3998 result_length = GetFinalPathNameByHandleW(hFile, target_path,
3999 buf_size, VOLUME_NAME_DOS);
4000 Py_END_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00004001
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004002 if (!result_length) {
4003 result = win32_error_object("GetFinalPathNameByHandleW",
4004 path->object);
4005 goto cleanup;
4006 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004007
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004008 if (result_length < buf_size) {
4009 break;
4010 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004011
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004012 wchar_t *tmp;
4013 tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
4014 result_length * sizeof(*tmp));
4015 if (!tmp) {
4016 result = PyErr_NoMemory();
4017 goto cleanup;
4018 }
4019
4020 buf_size = result_length;
4021 target_path = tmp;
Steve Dower23ad6d02018-02-22 10:39:10 -08004022 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004023
Victor Stinner9d3b93b2011-11-22 02:27:30 +01004024 result = PyUnicode_FromWideChar(target_path, result_length);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004025 if (result && path->narrow) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004026 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004027 }
Steve Dower23ad6d02018-02-22 10:39:10 -08004028
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004029cleanup:
4030 if (target_path != buf) {
4031 PyMem_Free(target_path);
4032 }
4033 CloseHandle(hFile);
4034 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10004035}
Brian Curtin62857742010-09-06 17:07:27 +00004036
Tim Golden6b528062013-08-01 12:44:00 +01004037
Larry Hastings2f936352014-08-05 14:04:04 +10004038/*[clinic input]
4039os._getvolumepathname
4040
Steve Dower23ad6d02018-02-22 10:39:10 -08004041 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10004042
4043A helper function for ismount on Win32.
4044[clinic start generated code]*/
4045
Larry Hastings2f936352014-08-05 14:04:04 +10004046static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08004047os__getvolumepathname_impl(PyObject *module, path_t *path)
4048/*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004049{
4050 PyObject *result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004051 wchar_t *mountpath=NULL;
Victor Stinner6edddfa2013-11-24 19:22:57 +01004052 size_t buflen;
Tim Golden6b528062013-08-01 12:44:00 +01004053 BOOL ret;
4054
Tim Golden6b528062013-08-01 12:44:00 +01004055 /* Volume path should be shorter than entire path */
Steve Dower23ad6d02018-02-22 10:39:10 -08004056 buflen = Py_MAX(path->length, MAX_PATH);
Victor Stinner6edddfa2013-11-24 19:22:57 +01004057
Victor Stinner850a18e2017-10-24 16:53:32 -07004058 if (buflen > PY_DWORD_MAX) {
Victor Stinner6edddfa2013-11-24 19:22:57 +01004059 PyErr_SetString(PyExc_OverflowError, "path too long");
4060 return NULL;
4061 }
4062
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004063 mountpath = PyMem_New(wchar_t, buflen);
Tim Golden6b528062013-08-01 12:44:00 +01004064 if (mountpath == NULL)
4065 return PyErr_NoMemory();
4066
4067 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -08004068 ret = GetVolumePathNameW(path->wide, mountpath,
Victor Stinner6edddfa2013-11-24 19:22:57 +01004069 Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
Tim Golden6b528062013-08-01 12:44:00 +01004070 Py_END_ALLOW_THREADS
4071
4072 if (!ret) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004073 result = win32_error_object("_getvolumepathname", path->object);
Tim Golden6b528062013-08-01 12:44:00 +01004074 goto exit;
4075 }
4076 result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
Steve Dower23ad6d02018-02-22 10:39:10 -08004077 if (path->narrow)
4078 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Tim Golden6b528062013-08-01 12:44:00 +01004079
4080exit:
4081 PyMem_Free(mountpath);
4082 return result;
4083}
Tim Golden6b528062013-08-01 12:44:00 +01004084
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004085#endif /* MS_WINDOWS */
Mark Hammondef8b6542001-05-13 08:04:26 +00004086
Larry Hastings2f936352014-08-05 14:04:04 +10004087
4088/*[clinic input]
4089os.mkdir
4090
4091 path : path_t
4092
4093 mode: int = 0o777
4094
4095 *
4096
4097 dir_fd : dir_fd(requires='mkdirat') = None
4098
4099# "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
4100
4101Create a directory.
4102
4103If dir_fd is not None, it should be a file descriptor open to a directory,
4104 and path should be relative; path will then be relative to that directory.
4105dir_fd may not be implemented on your platform.
4106 If it is unavailable, using it will raise a NotImplementedError.
4107
4108The mode argument is ignored on Windows.
4109[clinic start generated code]*/
4110
Larry Hastings2f936352014-08-05 14:04:04 +10004111static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004112os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
4113/*[clinic end generated code: output=a70446903abe821f input=e965f68377e9b1ce]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004114{
4115 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004116
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004117#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004118 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004119 result = CreateDirectoryW(path->wide, NULL);
Victor Stinner8c62be82010-05-06 00:08:46 +00004120 Py_END_ALLOW_THREADS
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004121
Larry Hastings2f936352014-08-05 14:04:04 +10004122 if (!result)
4123 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004124#else
Victor Stinner8c62be82010-05-06 00:08:46 +00004125 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004126#if HAVE_MKDIRAT
4127 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004128 result = mkdirat(dir_fd, path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004129 else
4130#endif
Erik Bray03eb11f2017-10-27 14:27:06 +02004131#if defined(__WATCOMC__) && !defined(__QNX__)
Larry Hastings2f936352014-08-05 14:04:04 +10004132 result = mkdir(path->narrow);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004133#else
Larry Hastings2f936352014-08-05 14:04:04 +10004134 result = mkdir(path->narrow, mode);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004135#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004136 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004137 if (result < 0)
4138 return path_error(path);
Steve Dowercc16be82016-09-08 10:35:16 -07004139#endif /* MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10004140 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004141}
4142
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004143
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004144/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
4145#if defined(HAVE_SYS_RESOURCE_H)
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004146#include <sys/resource.h>
4147#endif
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004148
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004149
4150#ifdef HAVE_NICE
Larry Hastings2f936352014-08-05 14:04:04 +10004151/*[clinic input]
4152os.nice
4153
4154 increment: int
4155 /
4156
4157Add increment to the priority of process and return the new priority.
4158[clinic start generated code]*/
4159
Larry Hastings2f936352014-08-05 14:04:04 +10004160static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004161os_nice_impl(PyObject *module, int increment)
4162/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004163{
4164 int value;
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004165
Victor Stinner8c62be82010-05-06 00:08:46 +00004166 /* There are two flavours of 'nice': one that returns the new
4167 priority (as required by almost all standards out there) and the
Benjamin Peterson288d1da2017-09-28 22:44:27 -07004168 Linux/FreeBSD one, which returns '0' on success and advices
Victor Stinner8c62be82010-05-06 00:08:46 +00004169 the use of getpriority() to get the new priority.
Tim Peters5aa91602002-01-30 05:46:57 +00004170
Victor Stinner8c62be82010-05-06 00:08:46 +00004171 If we are of the nice family that returns the new priority, we
4172 need to clear errno before the call, and check if errno is filled
4173 before calling posix_error() on a returnvalue of -1, because the
4174 -1 may be the actual new priority! */
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004175
Victor Stinner8c62be82010-05-06 00:08:46 +00004176 errno = 0;
4177 value = nice(increment);
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004178#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
Victor Stinner8c62be82010-05-06 00:08:46 +00004179 if (value == 0)
4180 value = getpriority(PRIO_PROCESS, 0);
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004181#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004182 if (value == -1 && errno != 0)
4183 /* either nice() or getpriority() returned an error */
4184 return posix_error();
4185 return PyLong_FromLong((long) value);
Guido van Rossum775f4da1993-01-09 17:18:52 +00004186}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004187#endif /* HAVE_NICE */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004188
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004189
4190#ifdef HAVE_GETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004191/*[clinic input]
4192os.getpriority
4193
4194 which: int
4195 who: int
4196
4197Return program scheduling priority.
4198[clinic start generated code]*/
4199
Larry Hastings2f936352014-08-05 14:04:04 +10004200static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004201os_getpriority_impl(PyObject *module, int which, int who)
4202/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004203{
4204 int retval;
4205
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004206 errno = 0;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004207 retval = getpriority(which, who);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004208 if (errno != 0)
4209 return posix_error();
4210 return PyLong_FromLong((long)retval);
4211}
4212#endif /* HAVE_GETPRIORITY */
4213
4214
4215#ifdef HAVE_SETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004216/*[clinic input]
4217os.setpriority
4218
4219 which: int
4220 who: int
4221 priority: int
4222
4223Set program scheduling priority.
4224[clinic start generated code]*/
4225
Larry Hastings2f936352014-08-05 14:04:04 +10004226static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004227os_setpriority_impl(PyObject *module, int which, int who, int priority)
4228/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004229{
4230 int retval;
4231
4232 retval = setpriority(which, who, priority);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004233 if (retval == -1)
4234 return posix_error();
4235 Py_RETURN_NONE;
4236}
4237#endif /* HAVE_SETPRIORITY */
4238
4239
Barry Warsaw53699e91996-12-10 23:23:01 +00004240static PyObject *
Larry Hastings2f936352014-08-05 14:04:04 +10004241internal_rename(path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd, int is_replace)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004242{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004243 const char *function_name = is_replace ? "replace" : "rename";
Larry Hastings9cf065c2012-06-22 16:30:09 -07004244 int dir_fd_specified;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004245
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004246#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004247 BOOL result;
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004248 int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004249#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004250 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004251#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004252
Larry Hastings9cf065c2012-06-22 16:30:09 -07004253 dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
4254 (dst_dir_fd != DEFAULT_DIR_FD);
4255#ifndef HAVE_RENAMEAT
4256 if (dir_fd_specified) {
4257 argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10004258 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004259 }
4260#endif
4261
Larry Hastings9cf065c2012-06-22 16:30:09 -07004262#ifdef MS_WINDOWS
4263 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004264 result = MoveFileExW(src->wide, dst->wide, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004265 Py_END_ALLOW_THREADS
4266
Larry Hastings2f936352014-08-05 14:04:04 +10004267 if (!result)
4268 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004269
4270#else
Steve Dowercc16be82016-09-08 10:35:16 -07004271 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
4272 PyErr_Format(PyExc_ValueError,
4273 "%s: src and dst must be the same type", function_name);
4274 return NULL;
4275 }
4276
Larry Hastings9cf065c2012-06-22 16:30:09 -07004277 Py_BEGIN_ALLOW_THREADS
4278#ifdef HAVE_RENAMEAT
4279 if (dir_fd_specified)
Larry Hastings2f936352014-08-05 14:04:04 +10004280 result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004281 else
4282#endif
Steve Dowercc16be82016-09-08 10:35:16 -07004283 result = rename(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004284 Py_END_ALLOW_THREADS
4285
Larry Hastings2f936352014-08-05 14:04:04 +10004286 if (result)
4287 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004288#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004289 Py_RETURN_NONE;
4290}
Larry Hastings9cf065c2012-06-22 16:30:09 -07004291
Larry Hastings2f936352014-08-05 14:04:04 +10004292
4293/*[clinic input]
4294os.rename
4295
4296 src : path_t
4297 dst : path_t
4298 *
4299 src_dir_fd : dir_fd = None
4300 dst_dir_fd : dir_fd = None
4301
4302Rename a file or directory.
4303
4304If either src_dir_fd or dst_dir_fd is not None, it should be a file
4305 descriptor open to a directory, and the respective path string (src or dst)
4306 should be relative; the path will then be relative to that directory.
4307src_dir_fd and dst_dir_fd, may not be implemented on your platform.
4308 If they are unavailable, using them will raise a NotImplementedError.
4309[clinic start generated code]*/
4310
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004311static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004312os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04004313 int dst_dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004314/*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004315{
Larry Hastings2f936352014-08-05 14:04:04 +10004316 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004317}
4318
Larry Hastings2f936352014-08-05 14:04:04 +10004319
4320/*[clinic input]
4321os.replace = os.rename
4322
4323Rename a file or directory, overwriting the destination.
4324
4325If either src_dir_fd or dst_dir_fd is not None, it should be a file
4326 descriptor open to a directory, and the respective path string (src or dst)
4327 should be relative; the path will then be relative to that directory.
4328src_dir_fd and dst_dir_fd, may not be implemented on your platform.
Anthony Sottile73d60022019-02-12 23:15:54 -05004329 If they are unavailable, using them will raise a NotImplementedError.
Larry Hastings2f936352014-08-05 14:04:04 +10004330[clinic start generated code]*/
4331
Larry Hastings2f936352014-08-05 14:04:04 +10004332static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004333os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
4334 int dst_dir_fd)
Anthony Sottile73d60022019-02-12 23:15:54 -05004335/*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004336{
4337 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
4338}
4339
4340
4341/*[clinic input]
4342os.rmdir
4343
4344 path: path_t
4345 *
4346 dir_fd: dir_fd(requires='unlinkat') = None
4347
4348Remove a directory.
4349
4350If dir_fd is not None, it should be a file descriptor open to a directory,
4351 and path should be relative; path will then be relative to that directory.
4352dir_fd may not be implemented on your platform.
4353 If it is unavailable, using it will raise a NotImplementedError.
4354[clinic start generated code]*/
4355
Larry Hastings2f936352014-08-05 14:04:04 +10004356static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004357os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
4358/*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004359{
4360 int result;
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004361
4362 Py_BEGIN_ALLOW_THREADS
4363#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004364 /* Windows, success=1, UNIX, success=0 */
4365 result = !RemoveDirectoryW(path->wide);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004366#else
4367#ifdef HAVE_UNLINKAT
4368 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004369 result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004370 else
4371#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004372 result = rmdir(path->narrow);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004373#endif
4374 Py_END_ALLOW_THREADS
4375
Larry Hastings2f936352014-08-05 14:04:04 +10004376 if (result)
4377 return path_error(path);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004378
Larry Hastings2f936352014-08-05 14:04:04 +10004379 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004380}
4381
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004382
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004383#ifdef HAVE_SYSTEM
Larry Hastings2f936352014-08-05 14:04:04 +10004384#ifdef MS_WINDOWS
4385/*[clinic input]
4386os.system -> long
4387
4388 command: Py_UNICODE
4389
4390Execute the command in a subshell.
4391[clinic start generated code]*/
4392
Larry Hastings2f936352014-08-05 14:04:04 +10004393static long
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02004394os_system_impl(PyObject *module, const Py_UNICODE *command)
4395/*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004396{
4397 long result;
Steve Dowerb82e17e2019-05-23 08:45:22 -07004398
Steve Dowerfbe3c762019-10-18 00:52:15 -07004399 if (PySys_Audit("os.system", "(u)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004400 return -1;
4401 }
4402
Victor Stinner8c62be82010-05-06 00:08:46 +00004403 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08004404 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10004405 result = _wsystem(command);
Steve Dowerc3630612016-11-19 18:41:16 -08004406 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00004407 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004408 return result;
4409}
4410#else /* MS_WINDOWS */
4411/*[clinic input]
4412os.system -> long
4413
4414 command: FSConverter
4415
4416Execute the command in a subshell.
4417[clinic start generated code]*/
4418
Larry Hastings2f936352014-08-05 14:04:04 +10004419static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004420os_system_impl(PyObject *module, PyObject *command)
4421/*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004422{
4423 long result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004424 const char *bytes = PyBytes_AsString(command);
Steve Dowerb82e17e2019-05-23 08:45:22 -07004425
Steve Dowerfbe3c762019-10-18 00:52:15 -07004426 if (PySys_Audit("os.system", "(O)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004427 return -1;
4428 }
4429
Larry Hastings2f936352014-08-05 14:04:04 +10004430 Py_BEGIN_ALLOW_THREADS
4431 result = system(bytes);
4432 Py_END_ALLOW_THREADS
4433 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004434}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004435#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004436#endif /* HAVE_SYSTEM */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004437
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004438
Larry Hastings2f936352014-08-05 14:04:04 +10004439/*[clinic input]
4440os.umask
4441
4442 mask: int
4443 /
4444
4445Set the current numeric umask and return the previous umask.
4446[clinic start generated code]*/
4447
Larry Hastings2f936352014-08-05 14:04:04 +10004448static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004449os_umask_impl(PyObject *module, int mask)
4450/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004451{
4452 int i = (int)umask(mask);
Victor Stinner8c62be82010-05-06 00:08:46 +00004453 if (i < 0)
4454 return posix_error();
4455 return PyLong_FromLong((long)i);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004456}
4457
Brian Curtind40e6f72010-07-08 21:39:08 +00004458#ifdef MS_WINDOWS
4459
4460/* override the default DeleteFileW behavior so that directory
4461symlinks can be removed with this function, the same as with
4462Unix symlinks */
4463BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
4464{
4465 WIN32_FILE_ATTRIBUTE_DATA info;
4466 WIN32_FIND_DATAW find_data;
4467 HANDLE find_data_handle;
4468 int is_directory = 0;
4469 int is_link = 0;
4470
4471 if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
4472 is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004473
Brian Curtind40e6f72010-07-08 21:39:08 +00004474 /* Get WIN32_FIND_DATA structure for the path to determine if
4475 it is a symlink */
4476 if(is_directory &&
4477 info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
4478 find_data_handle = FindFirstFileW(lpFileName, &find_data);
4479
4480 if(find_data_handle != INVALID_HANDLE_VALUE) {
Tim Golden0321cf22014-05-05 19:46:17 +01004481 /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
4482 IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
4483 is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
4484 find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
Brian Curtind40e6f72010-07-08 21:39:08 +00004485 FindClose(find_data_handle);
4486 }
4487 }
4488 }
4489
4490 if (is_directory && is_link)
4491 return RemoveDirectoryW(lpFileName);
4492
4493 return DeleteFileW(lpFileName);
4494}
4495#endif /* MS_WINDOWS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004496
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004497
Larry Hastings2f936352014-08-05 14:04:04 +10004498/*[clinic input]
4499os.unlink
4500
4501 path: path_t
4502 *
4503 dir_fd: dir_fd(requires='unlinkat')=None
4504
4505Remove a file (same as remove()).
4506
4507If dir_fd is not None, it should be a file descriptor open to a directory,
4508 and path should be relative; path will then be relative to that directory.
4509dir_fd may not be implemented on your platform.
4510 If it is unavailable, using it will raise a NotImplementedError.
4511
4512[clinic start generated code]*/
4513
Larry Hastings2f936352014-08-05 14:04:04 +10004514static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004515os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
4516/*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004517{
4518 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004519
4520 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04004521 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004522#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004523 /* Windows, success=1, UNIX, success=0 */
4524 result = !Py_DeleteFileW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004525#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004526#ifdef HAVE_UNLINKAT
4527 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004528 result = unlinkat(dir_fd, path->narrow, 0);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004529 else
4530#endif /* HAVE_UNLINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10004531 result = unlink(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004532#endif
Steve Dower8fc89802015-04-12 00:26:27 -04004533 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004534 Py_END_ALLOW_THREADS
4535
Larry Hastings2f936352014-08-05 14:04:04 +10004536 if (result)
4537 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004538
Larry Hastings2f936352014-08-05 14:04:04 +10004539 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004540}
4541
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004542
Larry Hastings2f936352014-08-05 14:04:04 +10004543/*[clinic input]
4544os.remove = os.unlink
4545
4546Remove a file (same as unlink()).
4547
4548If dir_fd is not None, it should be a file descriptor open to a directory,
4549 and path should be relative; path will then be relative to that directory.
4550dir_fd may not be implemented on your platform.
4551 If it is unavailable, using it will raise a NotImplementedError.
4552[clinic start generated code]*/
4553
Larry Hastings2f936352014-08-05 14:04:04 +10004554static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004555os_remove_impl(PyObject *module, path_t *path, int dir_fd)
4556/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004557{
4558 return os_unlink_impl(module, path, dir_fd);
4559}
4560
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004561
Larry Hastings605a62d2012-06-24 04:33:36 -07004562static PyStructSequence_Field uname_result_fields[] = {
4563 {"sysname", "operating system name"},
4564 {"nodename", "name of machine on network (implementation-defined)"},
4565 {"release", "operating system release"},
4566 {"version", "operating system version"},
4567 {"machine", "hardware identifier"},
4568 {NULL}
4569};
4570
4571PyDoc_STRVAR(uname_result__doc__,
4572"uname_result: Result from os.uname().\n\n\
4573This object may be accessed either as a tuple of\n\
4574 (sysname, nodename, release, version, machine),\n\
4575or via the attributes sysname, nodename, release, version, and machine.\n\
4576\n\
4577See os.uname for more information.");
4578
4579static PyStructSequence_Desc uname_result_desc = {
Eddie Elizondob3966632019-11-05 07:16:14 -08004580 MODNAME ".uname_result", /* name */
Larry Hastings605a62d2012-06-24 04:33:36 -07004581 uname_result__doc__, /* doc */
4582 uname_result_fields,
4583 5
4584};
4585
Larry Hastings605a62d2012-06-24 04:33:36 -07004586#ifdef HAVE_UNAME
Larry Hastings2f936352014-08-05 14:04:04 +10004587/*[clinic input]
4588os.uname
4589
4590Return an object identifying the current operating system.
4591
4592The object behaves like a named tuple with the following fields:
4593 (sysname, nodename, release, version, machine)
4594
4595[clinic start generated code]*/
4596
Larry Hastings2f936352014-08-05 14:04:04 +10004597static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004598os_uname_impl(PyObject *module)
4599/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004600{
Victor Stinner8c62be82010-05-06 00:08:46 +00004601 struct utsname u;
4602 int res;
Larry Hastings605a62d2012-06-24 04:33:36 -07004603 PyObject *value;
Neal Norwitze241ce82003-02-17 18:17:05 +00004604
Victor Stinner8c62be82010-05-06 00:08:46 +00004605 Py_BEGIN_ALLOW_THREADS
4606 res = uname(&u);
4607 Py_END_ALLOW_THREADS
4608 if (res < 0)
4609 return posix_error();
Larry Hastings605a62d2012-06-24 04:33:36 -07004610
Eddie Elizondob3966632019-11-05 07:16:14 -08004611 PyObject *UnameResultType = _posixstate(module)->UnameResultType;
4612 value = PyStructSequence_New((PyTypeObject *)UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07004613 if (value == NULL)
4614 return NULL;
4615
4616#define SET(i, field) \
4617 { \
Victor Stinnera534fc42013-06-03 22:07:27 +02004618 PyObject *o = PyUnicode_DecodeFSDefault(field); \
Larry Hastings605a62d2012-06-24 04:33:36 -07004619 if (!o) { \
4620 Py_DECREF(value); \
4621 return NULL; \
4622 } \
4623 PyStructSequence_SET_ITEM(value, i, o); \
4624 } \
4625
4626 SET(0, u.sysname);
4627 SET(1, u.nodename);
4628 SET(2, u.release);
4629 SET(3, u.version);
4630 SET(4, u.machine);
4631
4632#undef SET
4633
4634 return value;
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004635}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004636#endif /* HAVE_UNAME */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004637
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004638
Larry Hastings9cf065c2012-06-22 16:30:09 -07004639
4640typedef struct {
4641 int now;
4642 time_t atime_s;
4643 long atime_ns;
4644 time_t mtime_s;
4645 long mtime_ns;
4646} utime_t;
4647
4648/*
Victor Stinner484df002014-10-09 13:52:31 +02004649 * these macros assume that "ut" is a pointer to a utime_t
Larry Hastings9cf065c2012-06-22 16:30:09 -07004650 * they also intentionally leak the declaration of a pointer named "time"
4651 */
4652#define UTIME_TO_TIMESPEC \
4653 struct timespec ts[2]; \
4654 struct timespec *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004655 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004656 time = NULL; \
4657 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004658 ts[0].tv_sec = ut->atime_s; \
4659 ts[0].tv_nsec = ut->atime_ns; \
4660 ts[1].tv_sec = ut->mtime_s; \
4661 ts[1].tv_nsec = ut->mtime_ns; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004662 time = ts; \
4663 } \
4664
4665#define UTIME_TO_TIMEVAL \
4666 struct timeval tv[2]; \
4667 struct timeval *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004668 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004669 time = NULL; \
4670 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004671 tv[0].tv_sec = ut->atime_s; \
4672 tv[0].tv_usec = ut->atime_ns / 1000; \
4673 tv[1].tv_sec = ut->mtime_s; \
4674 tv[1].tv_usec = ut->mtime_ns / 1000; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004675 time = tv; \
4676 } \
4677
4678#define UTIME_TO_UTIMBUF \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004679 struct utimbuf u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004680 struct utimbuf *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004681 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004682 time = NULL; \
4683 else { \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004684 u.actime = ut->atime_s; \
4685 u.modtime = ut->mtime_s; \
4686 time = &u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004687 }
4688
4689#define UTIME_TO_TIME_T \
4690 time_t timet[2]; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004691 time_t *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004692 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004693 time = NULL; \
4694 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004695 timet[0] = ut->atime_s; \
4696 timet[1] = ut->mtime_s; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004697 time = timet; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004698 } \
4699
4700
Victor Stinner528a9ab2015-09-03 21:30:26 +02004701#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004702
4703static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004704utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004705{
4706#ifdef HAVE_UTIMENSAT
4707 int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
4708 UTIME_TO_TIMESPEC;
4709 return utimensat(dir_fd, path, time, flags);
4710#elif defined(HAVE_FUTIMESAT)
4711 UTIME_TO_TIMEVAL;
4712 /*
4713 * follow_symlinks will never be false here;
4714 * we only allow !follow_symlinks and dir_fd together
4715 * if we have utimensat()
4716 */
4717 assert(follow_symlinks);
4718 return futimesat(dir_fd, path, time);
4719#endif
4720}
4721
Larry Hastings2f936352014-08-05 14:04:04 +10004722 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
4723#else
4724 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings9cf065c2012-06-22 16:30:09 -07004725#endif
4726
Victor Stinner528a9ab2015-09-03 21:30:26 +02004727#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004728
4729static int
Victor Stinner484df002014-10-09 13:52:31 +02004730utime_fd(utime_t *ut, int fd)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004731{
4732#ifdef HAVE_FUTIMENS
4733 UTIME_TO_TIMESPEC;
4734 return futimens(fd, time);
4735#else
4736 UTIME_TO_TIMEVAL;
4737 return futimes(fd, time);
4738#endif
4739}
4740
Larry Hastings2f936352014-08-05 14:04:04 +10004741 #define PATH_UTIME_HAVE_FD 1
4742#else
4743 #define PATH_UTIME_HAVE_FD 0
Larry Hastings9cf065c2012-06-22 16:30:09 -07004744#endif
4745
Victor Stinner5ebae872015-09-22 01:29:33 +02004746#if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
4747# define UTIME_HAVE_NOFOLLOW_SYMLINKS
4748#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004749
Victor Stinner4552ced2015-09-21 22:37:15 +02004750#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004751
4752static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004753utime_nofollow_symlinks(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004754{
4755#ifdef HAVE_UTIMENSAT
4756 UTIME_TO_TIMESPEC;
4757 return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
4758#else
4759 UTIME_TO_TIMEVAL;
4760 return lutimes(path, time);
4761#endif
4762}
4763
4764#endif
4765
4766#ifndef MS_WINDOWS
4767
4768static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004769utime_default(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004770{
4771#ifdef HAVE_UTIMENSAT
4772 UTIME_TO_TIMESPEC;
4773 return utimensat(DEFAULT_DIR_FD, path, time, 0);
4774#elif defined(HAVE_UTIMES)
4775 UTIME_TO_TIMEVAL;
4776 return utimes(path, time);
4777#elif defined(HAVE_UTIME_H)
4778 UTIME_TO_UTIMBUF;
4779 return utime(path, time);
4780#else
4781 UTIME_TO_TIME_T;
4782 return utime(path, time);
4783#endif
4784}
4785
4786#endif
4787
Larry Hastings76ad59b2012-05-03 00:30:07 -07004788static int
4789split_py_long_to_s_and_ns(PyObject *py_long, time_t *s, long *ns)
4790{
4791 int result = 0;
Benjamin Petersonfbd85a02012-05-04 11:06:09 -04004792 PyObject *divmod;
Eddie Elizondob3966632019-11-05 07:16:14 -08004793 divmod = PyNumber_Divmod(py_long, _posixstate_global->billion);
Larry Hastings76ad59b2012-05-03 00:30:07 -07004794 if (!divmod)
4795 goto exit;
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004796 if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
4797 PyErr_Format(PyExc_TypeError,
4798 "%.200s.__divmod__() must return a 2-tuple, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -08004799 _PyType_Name(Py_TYPE(py_long)), _PyType_Name(Py_TYPE(divmod)));
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004800 goto exit;
4801 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004802 *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
4803 if ((*s == -1) && PyErr_Occurred())
4804 goto exit;
4805 *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
Benjamin Peterson35a8f0d2012-05-04 01:10:59 -04004806 if ((*ns == -1) && PyErr_Occurred())
Larry Hastings76ad59b2012-05-03 00:30:07 -07004807 goto exit;
4808
4809 result = 1;
4810exit:
4811 Py_XDECREF(divmod);
4812 return result;
4813}
4814
Larry Hastings2f936352014-08-05 14:04:04 +10004815
4816/*[clinic input]
4817os.utime
4818
4819 path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004820 times: object = None
Larry Hastings2f936352014-08-05 14:04:04 +10004821 *
4822 ns: object = NULL
4823 dir_fd: dir_fd(requires='futimensat') = None
4824 follow_symlinks: bool=True
4825
Martin Panter0ff89092015-09-09 01:56:53 +00004826# "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
Larry Hastings2f936352014-08-05 14:04:04 +10004827
4828Set the access and modified time of path.
4829
4830path may always be specified as a string.
4831On some platforms, path may also be specified as an open file descriptor.
4832 If this functionality is unavailable, using it raises an exception.
4833
4834If times is not None, it must be a tuple (atime, mtime);
4835 atime and mtime should be expressed as float seconds since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004836If ns is specified, it must be a tuple (atime_ns, mtime_ns);
Larry Hastings2f936352014-08-05 14:04:04 +10004837 atime_ns and mtime_ns should be expressed as integer nanoseconds
4838 since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004839If times is None and ns is unspecified, utime uses the current time.
Larry Hastings2f936352014-08-05 14:04:04 +10004840Specifying tuples for both times and ns is an error.
4841
4842If dir_fd is not None, it should be a file descriptor open to a directory,
4843 and path should be relative; path will then be relative to that directory.
4844If follow_symlinks is False, and the last element of the path is a symbolic
4845 link, utime will modify the symbolic link itself instead of the file the
4846 link points to.
4847It is an error to use dir_fd or follow_symlinks when specifying path
4848 as an open file descriptor.
4849dir_fd and follow_symlinks may not be available on your platform.
4850 If they are unavailable, using them will raise a NotImplementedError.
4851
4852[clinic start generated code]*/
4853
Larry Hastings2f936352014-08-05 14:04:04 +10004854static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004855os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
4856 int dir_fd, int follow_symlinks)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004857/*[clinic end generated code: output=cfcac69d027b82cf input=2fbd62a2f228f8f4]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004858{
Larry Hastings9cf065c2012-06-22 16:30:09 -07004859#ifdef MS_WINDOWS
4860 HANDLE hFile;
4861 FILETIME atime, mtime;
4862#else
4863 int result;
4864#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004865
Larry Hastings2f936352014-08-05 14:04:04 +10004866 utime_t utime;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004867
Christian Heimesb3c87242013-08-01 00:08:16 +02004868 memset(&utime, 0, sizeof(utime_t));
Larry Hastings76ad59b2012-05-03 00:30:07 -07004869
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004870 if (times != Py_None && ns) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004871 PyErr_SetString(PyExc_ValueError,
4872 "utime: you may specify either 'times'"
4873 " or 'ns' but not both");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004874 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004875 }
4876
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004877 if (times != Py_None) {
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004878 time_t a_sec, m_sec;
4879 long a_nsec, m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004880 if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004881 PyErr_SetString(PyExc_TypeError,
4882 "utime: 'times' must be either"
4883 " a tuple of two ints or None");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004884 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004885 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004886 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004887 if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004888 &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004889 _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004890 &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004891 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004892 }
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004893 utime.atime_s = a_sec;
4894 utime.atime_ns = a_nsec;
4895 utime.mtime_s = m_sec;
4896 utime.mtime_ns = m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004897 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004898 else if (ns) {
Larry Hastings76ad59b2012-05-03 00:30:07 -07004899 if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004900 PyErr_SetString(PyExc_TypeError,
4901 "utime: 'ns' must be a tuple of two ints");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004902 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004903 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004904 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004905 if (!split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 0),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004906 &utime.atime_s, &utime.atime_ns) ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004907 !split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 1),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004908 &utime.mtime_s, &utime.mtime_ns)) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004909 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004910 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004911 }
4912 else {
4913 /* times and ns are both None/unspecified. use "now". */
4914 utime.now = 1;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004915 }
4916
Victor Stinner4552ced2015-09-21 22:37:15 +02004917#if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004918 if (follow_symlinks_specified("utime", follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004919 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004920#endif
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004921
Larry Hastings2f936352014-08-05 14:04:04 +10004922 if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
4923 dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
4924 fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004925 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004926
Larry Hastings9cf065c2012-06-22 16:30:09 -07004927#if !defined(HAVE_UTIMENSAT)
4928 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
Georg Brandl969288e2012-06-26 09:25:44 +02004929 PyErr_SetString(PyExc_ValueError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07004930 "utime: cannot use dir_fd and follow_symlinks "
4931 "together on this platform");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004932 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004933 }
4934#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004935
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004936#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004937 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004938 hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
4939 NULL, OPEN_EXISTING,
4940 FILE_FLAG_BACKUP_SEMANTICS, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004941 Py_END_ALLOW_THREADS
4942 if (hFile == INVALID_HANDLE_VALUE) {
Larry Hastings2f936352014-08-05 14:04:04 +10004943 path_error(path);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004944 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004945 }
4946
Larry Hastings9cf065c2012-06-22 16:30:09 -07004947 if (utime.now) {
Antoine Pitrou91a7af32013-11-23 15:23:26 +01004948 GetSystemTimeAsFileTime(&mtime);
4949 atime = mtime;
Victor Stinner8c62be82010-05-06 00:08:46 +00004950 }
Victor Stinner8c62be82010-05-06 00:08:46 +00004951 else {
Steve Dowerbf1f3762015-02-21 15:26:02 -08004952 _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
4953 _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
Victor Stinner8c62be82010-05-06 00:08:46 +00004954 }
4955 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
4956 /* Avoid putting the file name into the error here,
4957 as that may confuse the user into believing that
4958 something is wrong with the file, when it also
4959 could be the time stamp that gives a problem. */
Victor Stinnerb024e842012-10-31 22:24:06 +01004960 PyErr_SetFromWindowsErr(0);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004961 CloseHandle(hFile);
4962 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004963 }
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004964 CloseHandle(hFile);
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004965#else /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07004966 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004967
Victor Stinner4552ced2015-09-21 22:37:15 +02004968#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004969 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10004970 result = utime_nofollow_symlinks(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004971 else
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004972#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004973
Victor Stinner528a9ab2015-09-03 21:30:26 +02004974#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004975 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10004976 result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004977 else
4978#endif
4979
Victor Stinner528a9ab2015-09-03 21:30:26 +02004980#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings2f936352014-08-05 14:04:04 +10004981 if (path->fd != -1)
4982 result = utime_fd(&utime, path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004983 else
4984#endif
4985
Larry Hastings2f936352014-08-05 14:04:04 +10004986 result = utime_default(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004987
4988 Py_END_ALLOW_THREADS
4989
4990 if (result < 0) {
4991 /* see previous comment about not putting filename in error here */
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004992 posix_error();
4993 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004994 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004995
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004996#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07004997
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004998 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004999}
5000
Guido van Rossum3b066191991-06-04 19:40:25 +00005001/* Process operations */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005002
Larry Hastings2f936352014-08-05 14:04:04 +10005003
5004/*[clinic input]
5005os._exit
5006
5007 status: int
5008
5009Exit to the system with specified status, without normal exit processing.
5010[clinic start generated code]*/
5011
Larry Hastings2f936352014-08-05 14:04:04 +10005012static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005013os__exit_impl(PyObject *module, int status)
5014/*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005015{
5016 _exit(status);
Victor Stinner8c62be82010-05-06 00:08:46 +00005017 return NULL; /* Make gcc -Wall happy */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005018}
5019
Steve Dowercc16be82016-09-08 10:35:16 -07005020#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5021#define EXECV_CHAR wchar_t
5022#else
5023#define EXECV_CHAR char
5024#endif
5025
pxinwrf2d7ac72019-05-21 18:46:37 +08005026#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005027static void
Steve Dowercc16be82016-09-08 10:35:16 -07005028free_string_array(EXECV_CHAR **array, Py_ssize_t count)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005029{
Victor Stinner8c62be82010-05-06 00:08:46 +00005030 Py_ssize_t i;
5031 for (i = 0; i < count; i++)
5032 PyMem_Free(array[i]);
5033 PyMem_DEL(array);
Martin v. Löwis114619e2002-10-07 06:44:21 +00005034}
Martin v. Löwis011e8422009-05-05 04:43:17 +00005035
Berker Peksag81816462016-09-15 20:19:47 +03005036static int
5037fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
Martin v. Löwis011e8422009-05-05 04:43:17 +00005038{
Victor Stinner8c62be82010-05-06 00:08:46 +00005039 Py_ssize_t size;
Berker Peksag81816462016-09-15 20:19:47 +03005040 PyObject *ub;
5041 int result = 0;
Steve Dowercc16be82016-09-08 10:35:16 -07005042#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
Berker Peksag81816462016-09-15 20:19:47 +03005043 if (!PyUnicode_FSDecoder(o, &ub))
Steve Dowercc16be82016-09-08 10:35:16 -07005044 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005045 *out = PyUnicode_AsWideCharString(ub, &size);
5046 if (*out)
5047 result = 1;
Steve Dowercc16be82016-09-08 10:35:16 -07005048#else
Berker Peksag81816462016-09-15 20:19:47 +03005049 if (!PyUnicode_FSConverter(o, &ub))
Victor Stinner8c62be82010-05-06 00:08:46 +00005050 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005051 size = PyBytes_GET_SIZE(ub);
5052 *out = PyMem_Malloc(size + 1);
5053 if (*out) {
5054 memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
5055 result = 1;
5056 } else
Victor Stinner50abf222013-11-07 23:56:10 +01005057 PyErr_NoMemory();
Steve Dowercc16be82016-09-08 10:35:16 -07005058#endif
Berker Peksag81816462016-09-15 20:19:47 +03005059 Py_DECREF(ub);
5060 return result;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005061}
Martin v. Löwis114619e2002-10-07 06:44:21 +00005062#endif
5063
pxinwrf2d7ac72019-05-21 18:46:37 +08005064#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
Steve Dowercc16be82016-09-08 10:35:16 -07005065static EXECV_CHAR**
Victor Stinner13bb71c2010-04-23 21:41:56 +00005066parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
5067{
Victor Stinner8c62be82010-05-06 00:08:46 +00005068 Py_ssize_t i, pos, envc;
5069 PyObject *keys=NULL, *vals=NULL;
Berker Peksag81816462016-09-15 20:19:47 +03005070 PyObject *key, *val, *key2, *val2, *keyval;
Steve Dowercc16be82016-09-08 10:35:16 -07005071 EXECV_CHAR **envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005072
Victor Stinner8c62be82010-05-06 00:08:46 +00005073 i = PyMapping_Size(env);
5074 if (i < 0)
5075 return NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07005076 envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005077 if (envlist == NULL) {
5078 PyErr_NoMemory();
5079 return NULL;
5080 }
5081 envc = 0;
5082 keys = PyMapping_Keys(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005083 if (!keys)
5084 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00005085 vals = PyMapping_Values(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005086 if (!vals)
Victor Stinner8c62be82010-05-06 00:08:46 +00005087 goto error;
5088 if (!PyList_Check(keys) || !PyList_Check(vals)) {
5089 PyErr_Format(PyExc_TypeError,
5090 "env.keys() or env.values() is not a list");
5091 goto error;
5092 }
Victor Stinner13bb71c2010-04-23 21:41:56 +00005093
Victor Stinner8c62be82010-05-06 00:08:46 +00005094 for (pos = 0; pos < i; pos++) {
5095 key = PyList_GetItem(keys, pos);
5096 val = PyList_GetItem(vals, pos);
5097 if (!key || !val)
5098 goto error;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005099
Berker Peksag81816462016-09-15 20:19:47 +03005100#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5101 if (!PyUnicode_FSDecoder(key, &key2))
5102 goto error;
5103 if (!PyUnicode_FSDecoder(val, &val2)) {
5104 Py_DECREF(key2);
5105 goto error;
5106 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005107 /* Search from index 1 because on Windows starting '=' is allowed for
5108 defining hidden environment variables. */
5109 if (PyUnicode_GET_LENGTH(key2) == 0 ||
5110 PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
5111 {
5112 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005113 Py_DECREF(key2);
5114 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005115 goto error;
5116 }
Berker Peksag81816462016-09-15 20:19:47 +03005117 keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
5118#else
5119 if (!PyUnicode_FSConverter(key, &key2))
5120 goto error;
5121 if (!PyUnicode_FSConverter(val, &val2)) {
5122 Py_DECREF(key2);
5123 goto error;
5124 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005125 if (PyBytes_GET_SIZE(key2) == 0 ||
5126 strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
5127 {
5128 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005129 Py_DECREF(key2);
5130 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005131 goto error;
5132 }
Berker Peksag81816462016-09-15 20:19:47 +03005133 keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
5134 PyBytes_AS_STRING(val2));
5135#endif
5136 Py_DECREF(key2);
5137 Py_DECREF(val2);
Steve Dowercc16be82016-09-08 10:35:16 -07005138 if (!keyval)
Victor Stinner8c62be82010-05-06 00:08:46 +00005139 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -07005140
5141 if (!fsconvert_strdup(keyval, &envlist[envc++])) {
5142 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005143 goto error;
5144 }
Berker Peksag81816462016-09-15 20:19:47 +03005145
Steve Dowercc16be82016-09-08 10:35:16 -07005146 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005147 }
5148 Py_DECREF(vals);
5149 Py_DECREF(keys);
Victor Stinner13bb71c2010-04-23 21:41:56 +00005150
Victor Stinner8c62be82010-05-06 00:08:46 +00005151 envlist[envc] = 0;
5152 *envc_ptr = envc;
5153 return envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005154
5155error:
Victor Stinner8c62be82010-05-06 00:08:46 +00005156 Py_XDECREF(keys);
5157 Py_XDECREF(vals);
Steve Dowercc16be82016-09-08 10:35:16 -07005158 free_string_array(envlist, envc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005159 return NULL;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005160}
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005161
Steve Dowercc16be82016-09-08 10:35:16 -07005162static EXECV_CHAR**
Ross Lagerwall7807c352011-03-17 20:20:30 +02005163parse_arglist(PyObject* argv, Py_ssize_t *argc)
5164{
5165 int i;
Steve Dowercc16be82016-09-08 10:35:16 -07005166 EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005167 if (argvlist == NULL) {
5168 PyErr_NoMemory();
5169 return NULL;
5170 }
5171 for (i = 0; i < *argc; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005172 PyObject* item = PySequence_ITEM(argv, i);
5173 if (item == NULL)
5174 goto fail;
5175 if (!fsconvert_strdup(item, &argvlist[i])) {
5176 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005177 goto fail;
5178 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005179 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005180 }
5181 argvlist[*argc] = NULL;
5182 return argvlist;
5183fail:
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005184 *argc = i;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005185 free_string_array(argvlist, *argc);
5186 return NULL;
5187}
Steve Dowercc16be82016-09-08 10:35:16 -07005188
Ross Lagerwall7807c352011-03-17 20:20:30 +02005189#endif
5190
Larry Hastings2f936352014-08-05 14:04:04 +10005191
Ross Lagerwall7807c352011-03-17 20:20:30 +02005192#ifdef HAVE_EXECV
Larry Hastings2f936352014-08-05 14:04:04 +10005193/*[clinic input]
5194os.execv
5195
Steve Dowercc16be82016-09-08 10:35:16 -07005196 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005197 Path of executable file.
5198 argv: object
5199 Tuple or list of strings.
5200 /
5201
5202Execute an executable path with arguments, replacing current process.
5203[clinic start generated code]*/
5204
Larry Hastings2f936352014-08-05 14:04:04 +10005205static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005206os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
5207/*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005208{
Steve Dowercc16be82016-09-08 10:35:16 -07005209 EXECV_CHAR **argvlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005210 Py_ssize_t argc;
5211
5212 /* execv has two arguments: (path, argv), where
5213 argv is a list or tuple of strings. */
5214
Ross Lagerwall7807c352011-03-17 20:20:30 +02005215 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
5216 PyErr_SetString(PyExc_TypeError,
5217 "execv() arg 2 must be a tuple or list");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005218 return NULL;
5219 }
5220 argc = PySequence_Size(argv);
5221 if (argc < 1) {
5222 PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005223 return NULL;
5224 }
5225
5226 argvlist = parse_arglist(argv, &argc);
5227 if (argvlist == NULL) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02005228 return NULL;
5229 }
Steve Dowerbce26262016-11-19 19:17:26 -08005230 if (!argvlist[0][0]) {
5231 PyErr_SetString(PyExc_ValueError,
5232 "execv() arg 2 first element cannot be empty");
5233 free_string_array(argvlist, argc);
5234 return NULL;
5235 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005236
Steve Dowerbce26262016-11-19 19:17:26 -08005237 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005238#ifdef HAVE_WEXECV
5239 _wexecv(path->wide, argvlist);
5240#else
5241 execv(path->narrow, argvlist);
5242#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005243 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005244
5245 /* If we get here it's definitely an error */
5246
5247 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005248 return posix_error();
5249}
5250
Larry Hastings2f936352014-08-05 14:04:04 +10005251
5252/*[clinic input]
5253os.execve
5254
5255 path: path_t(allow_fd='PATH_HAVE_FEXECVE')
5256 Path of executable file.
5257 argv: object
5258 Tuple or list of strings.
5259 env: object
5260 Dictionary of strings mapping to strings.
5261
5262Execute an executable path with arguments, replacing current process.
5263[clinic start generated code]*/
5264
Larry Hastings2f936352014-08-05 14:04:04 +10005265static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005266os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
5267/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005268{
Steve Dowercc16be82016-09-08 10:35:16 -07005269 EXECV_CHAR **argvlist = NULL;
5270 EXECV_CHAR **envlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005271 Py_ssize_t argc, envc;
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005272
Victor Stinner8c62be82010-05-06 00:08:46 +00005273 /* execve has three arguments: (path, argv, env), where
5274 argv is a list or tuple of strings and env is a dictionary
5275 like posix.environ. */
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005276
Ross Lagerwall7807c352011-03-17 20:20:30 +02005277 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005278 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005279 "execve: argv must be a tuple or list");
5280 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005281 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005282 argc = PySequence_Size(argv);
Steve Dowerbce26262016-11-19 19:17:26 -08005283 if (argc < 1) {
5284 PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
5285 return NULL;
5286 }
5287
Victor Stinner8c62be82010-05-06 00:08:46 +00005288 if (!PyMapping_Check(env)) {
5289 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005290 "execve: environment must be a mapping object");
5291 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005292 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005293
Ross Lagerwall7807c352011-03-17 20:20:30 +02005294 argvlist = parse_arglist(argv, &argc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005295 if (argvlist == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07005296 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005297 }
Steve Dowerbce26262016-11-19 19:17:26 -08005298 if (!argvlist[0][0]) {
5299 PyErr_SetString(PyExc_ValueError,
5300 "execve: argv first element cannot be empty");
5301 goto fail;
5302 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005303
Victor Stinner8c62be82010-05-06 00:08:46 +00005304 envlist = parse_envlist(env, &envc);
5305 if (envlist == NULL)
Ross Lagerwall7807c352011-03-17 20:20:30 +02005306 goto fail;
5307
Steve Dowerbce26262016-11-19 19:17:26 -08005308 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07005309#ifdef HAVE_FEXECVE
Larry Hastings2f936352014-08-05 14:04:04 +10005310 if (path->fd > -1)
5311 fexecve(path->fd, argvlist, envlist);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005312 else
5313#endif
Steve Dowercc16be82016-09-08 10:35:16 -07005314#ifdef HAVE_WEXECV
5315 _wexecve(path->wide, argvlist, envlist);
5316#else
Larry Hastings2f936352014-08-05 14:04:04 +10005317 execve(path->narrow, argvlist, envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07005318#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005319 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005320
5321 /* If we get here it's definitely an error */
5322
Alexey Izbyshev83460312018-10-20 03:28:22 +03005323 posix_path_error(path);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005324
Steve Dowercc16be82016-09-08 10:35:16 -07005325 free_string_array(envlist, envc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005326 fail:
Larry Hastings9cf065c2012-06-22 16:30:09 -07005327 if (argvlist)
5328 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005329 return NULL;
5330}
Steve Dowercc16be82016-09-08 10:35:16 -07005331
Larry Hastings9cf065c2012-06-22 16:30:09 -07005332#endif /* HAVE_EXECV */
5333
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005334#ifdef HAVE_POSIX_SPAWN
5335
5336enum posix_spawn_file_actions_identifier {
5337 POSIX_SPAWN_OPEN,
5338 POSIX_SPAWN_CLOSE,
5339 POSIX_SPAWN_DUP2
5340};
5341
William Orr81574b82018-10-01 22:19:56 -07005342#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005343static int
Pablo Galindo254a4662018-09-07 16:44:24 +01005344convert_sched_param(PyObject *param, struct sched_param *res);
William Orr81574b82018-10-01 22:19:56 -07005345#endif
Pablo Galindo254a4662018-09-07 16:44:24 +01005346
5347static int
Victor Stinner325e4ba2019-02-01 15:47:24 +01005348parse_posix_spawn_flags(const char *func_name, PyObject *setpgroup,
5349 int resetids, int setsid, PyObject *setsigmask,
Pablo Galindo254a4662018-09-07 16:44:24 +01005350 PyObject *setsigdef, PyObject *scheduler,
5351 posix_spawnattr_t *attrp)
5352{
5353 long all_flags = 0;
5354
5355 errno = posix_spawnattr_init(attrp);
5356 if (errno) {
5357 posix_error();
5358 return -1;
5359 }
5360
5361 if (setpgroup) {
5362 pid_t pgid = PyLong_AsPid(setpgroup);
5363 if (pgid == (pid_t)-1 && PyErr_Occurred()) {
5364 goto fail;
5365 }
5366 errno = posix_spawnattr_setpgroup(attrp, pgid);
5367 if (errno) {
5368 posix_error();
5369 goto fail;
5370 }
5371 all_flags |= POSIX_SPAWN_SETPGROUP;
5372 }
5373
5374 if (resetids) {
5375 all_flags |= POSIX_SPAWN_RESETIDS;
5376 }
5377
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005378 if (setsid) {
5379#ifdef POSIX_SPAWN_SETSID
5380 all_flags |= POSIX_SPAWN_SETSID;
5381#elif defined(POSIX_SPAWN_SETSID_NP)
5382 all_flags |= POSIX_SPAWN_SETSID_NP;
5383#else
5384 argument_unavailable_error(func_name, "setsid");
5385 return -1;
5386#endif
5387 }
5388
Pablo Galindo254a4662018-09-07 16:44:24 +01005389 if (setsigmask) {
5390 sigset_t set;
5391 if (!_Py_Sigset_Converter(setsigmask, &set)) {
5392 goto fail;
5393 }
5394 errno = posix_spawnattr_setsigmask(attrp, &set);
5395 if (errno) {
5396 posix_error();
5397 goto fail;
5398 }
5399 all_flags |= POSIX_SPAWN_SETSIGMASK;
5400 }
5401
5402 if (setsigdef) {
5403 sigset_t set;
5404 if (!_Py_Sigset_Converter(setsigdef, &set)) {
5405 goto fail;
5406 }
5407 errno = posix_spawnattr_setsigdefault(attrp, &set);
5408 if (errno) {
5409 posix_error();
5410 goto fail;
5411 }
5412 all_flags |= POSIX_SPAWN_SETSIGDEF;
5413 }
5414
5415 if (scheduler) {
5416#ifdef POSIX_SPAWN_SETSCHEDULER
5417 PyObject *py_schedpolicy;
5418 struct sched_param schedparam;
5419
5420 if (!PyArg_ParseTuple(scheduler, "OO&"
5421 ";A scheduler tuple must have two elements",
5422 &py_schedpolicy, convert_sched_param, &schedparam)) {
5423 goto fail;
5424 }
5425 if (py_schedpolicy != Py_None) {
5426 int schedpolicy = _PyLong_AsInt(py_schedpolicy);
5427
5428 if (schedpolicy == -1 && PyErr_Occurred()) {
5429 goto fail;
5430 }
5431 errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
5432 if (errno) {
5433 posix_error();
5434 goto fail;
5435 }
5436 all_flags |= POSIX_SPAWN_SETSCHEDULER;
5437 }
5438 errno = posix_spawnattr_setschedparam(attrp, &schedparam);
5439 if (errno) {
5440 posix_error();
5441 goto fail;
5442 }
5443 all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
5444#else
5445 PyErr_SetString(PyExc_NotImplementedError,
5446 "The scheduler option is not supported in this system.");
5447 goto fail;
5448#endif
5449 }
5450
5451 errno = posix_spawnattr_setflags(attrp, all_flags);
5452 if (errno) {
5453 posix_error();
5454 goto fail;
5455 }
5456
5457 return 0;
5458
5459fail:
5460 (void)posix_spawnattr_destroy(attrp);
5461 return -1;
5462}
5463
5464static int
Serhiy Storchakaef347532018-05-01 16:45:04 +03005465parse_file_actions(PyObject *file_actions,
Pablo Galindocb970732018-06-19 09:19:50 +01005466 posix_spawn_file_actions_t *file_actionsp,
5467 PyObject *temp_buffer)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005468{
5469 PyObject *seq;
5470 PyObject *file_action = NULL;
5471 PyObject *tag_obj;
5472
5473 seq = PySequence_Fast(file_actions,
5474 "file_actions must be a sequence or None");
5475 if (seq == NULL) {
5476 return -1;
5477 }
5478
5479 errno = posix_spawn_file_actions_init(file_actionsp);
5480 if (errno) {
5481 posix_error();
5482 Py_DECREF(seq);
5483 return -1;
5484 }
5485
Zackery Spytzd52a83a2019-06-26 14:54:20 -06005486 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
Serhiy Storchakaef347532018-05-01 16:45:04 +03005487 file_action = PySequence_Fast_GET_ITEM(seq, i);
5488 Py_INCREF(file_action);
5489 if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
5490 PyErr_SetString(PyExc_TypeError,
5491 "Each file_actions element must be a non-empty tuple");
5492 goto fail;
5493 }
5494 long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
5495 if (tag == -1 && PyErr_Occurred()) {
5496 goto fail;
5497 }
5498
5499 /* Populate the file_actions object */
5500 switch (tag) {
5501 case POSIX_SPAWN_OPEN: {
5502 int fd, oflag;
5503 PyObject *path;
5504 unsigned long mode;
5505 if (!PyArg_ParseTuple(file_action, "OiO&ik"
5506 ";A open file_action tuple must have 5 elements",
5507 &tag_obj, &fd, PyUnicode_FSConverter, &path,
5508 &oflag, &mode))
5509 {
5510 goto fail;
5511 }
Pablo Galindocb970732018-06-19 09:19:50 +01005512 if (PyList_Append(temp_buffer, path)) {
5513 Py_DECREF(path);
5514 goto fail;
5515 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005516 errno = posix_spawn_file_actions_addopen(file_actionsp,
5517 fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
Pablo Galindocb970732018-06-19 09:19:50 +01005518 Py_DECREF(path);
Serhiy Storchakaef347532018-05-01 16:45:04 +03005519 if (errno) {
5520 posix_error();
5521 goto fail;
5522 }
5523 break;
5524 }
5525 case POSIX_SPAWN_CLOSE: {
5526 int fd;
5527 if (!PyArg_ParseTuple(file_action, "Oi"
5528 ";A close file_action tuple must have 2 elements",
5529 &tag_obj, &fd))
5530 {
5531 goto fail;
5532 }
5533 errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
5534 if (errno) {
5535 posix_error();
5536 goto fail;
5537 }
5538 break;
5539 }
5540 case POSIX_SPAWN_DUP2: {
5541 int fd1, fd2;
5542 if (!PyArg_ParseTuple(file_action, "Oii"
5543 ";A dup2 file_action tuple must have 3 elements",
5544 &tag_obj, &fd1, &fd2))
5545 {
5546 goto fail;
5547 }
5548 errno = posix_spawn_file_actions_adddup2(file_actionsp,
5549 fd1, fd2);
5550 if (errno) {
5551 posix_error();
5552 goto fail;
5553 }
5554 break;
5555 }
5556 default: {
5557 PyErr_SetString(PyExc_TypeError,
5558 "Unknown file_actions identifier");
5559 goto fail;
5560 }
5561 }
5562 Py_DECREF(file_action);
5563 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005564
Serhiy Storchakaef347532018-05-01 16:45:04 +03005565 Py_DECREF(seq);
5566 return 0;
5567
5568fail:
5569 Py_DECREF(seq);
5570 Py_DECREF(file_action);
5571 (void)posix_spawn_file_actions_destroy(file_actionsp);
5572 return -1;
5573}
5574
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005575
5576static PyObject *
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005577py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
5578 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005579 PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005580 PyObject *setsigdef, PyObject *scheduler)
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005581{
Victor Stinner325e4ba2019-02-01 15:47:24 +01005582 const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005583 EXECV_CHAR **argvlist = NULL;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005584 EXECV_CHAR **envlist = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005585 posix_spawn_file_actions_t file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005586 posix_spawn_file_actions_t *file_actionsp = NULL;
Pablo Galindo254a4662018-09-07 16:44:24 +01005587 posix_spawnattr_t attr;
5588 posix_spawnattr_t *attrp = NULL;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005589 Py_ssize_t argc, envc;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005590 PyObject *result = NULL;
Pablo Galindocb970732018-06-19 09:19:50 +01005591 PyObject *temp_buffer = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005592 pid_t pid;
5593 int err_code;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005594
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005595 /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
Serhiy Storchakaef347532018-05-01 16:45:04 +03005596 argv is a list or tuple of strings and env is a dictionary
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005597 like posix.environ. */
5598
Serhiy Storchakaef347532018-05-01 16:45:04 +03005599 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005600 PyErr_Format(PyExc_TypeError,
5601 "%s: argv must be a tuple or list", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005602 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005603 }
5604 argc = PySequence_Size(argv);
5605 if (argc < 1) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005606 PyErr_Format(PyExc_ValueError,
5607 "%s: argv must not be empty", func_name);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005608 return NULL;
5609 }
5610
5611 if (!PyMapping_Check(env)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005612 PyErr_Format(PyExc_TypeError,
5613 "%s: environment must be a mapping object", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005614 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005615 }
5616
5617 argvlist = parse_arglist(argv, &argc);
5618 if (argvlist == NULL) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005619 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005620 }
5621 if (!argvlist[0][0]) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005622 PyErr_Format(PyExc_ValueError,
5623 "%s: argv first element cannot be empty", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005624 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005625 }
5626
5627 envlist = parse_envlist(env, &envc);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005628 if (envlist == NULL) {
5629 goto exit;
5630 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005631
Anthony Shaw948ed8c2019-05-10 12:00:06 +10005632 if (file_actions != NULL && file_actions != Py_None) {
Pablo Galindocb970732018-06-19 09:19:50 +01005633 /* There is a bug in old versions of glibc that makes some of the
5634 * helper functions for manipulating file actions not copy the provided
5635 * buffers. The problem is that posix_spawn_file_actions_addopen does not
5636 * copy the value of path for some old versions of glibc (<2.20).
5637 * The use of temp_buffer here is a workaround that keeps the
5638 * python objects that own the buffers alive until posix_spawn gets called.
5639 * Check https://bugs.python.org/issue33630 and
5640 * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
5641 temp_buffer = PyList_New(0);
5642 if (!temp_buffer) {
5643 goto exit;
5644 }
5645 if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005646 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005647 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005648 file_actionsp = &file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005649 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005650
Victor Stinner325e4ba2019-02-01 15:47:24 +01005651 if (parse_posix_spawn_flags(func_name, setpgroup, resetids, setsid,
5652 setsigmask, setsigdef, scheduler, &attr)) {
Pablo Galindo254a4662018-09-07 16:44:24 +01005653 goto exit;
5654 }
5655 attrp = &attr;
5656
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005657 _Py_BEGIN_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005658#ifdef HAVE_POSIX_SPAWNP
5659 if (use_posix_spawnp) {
5660 err_code = posix_spawnp(&pid, path->narrow,
5661 file_actionsp, attrp, argvlist, envlist);
5662 }
5663 else
5664#endif /* HAVE_POSIX_SPAWNP */
5665 {
5666 err_code = posix_spawn(&pid, path->narrow,
5667 file_actionsp, attrp, argvlist, envlist);
5668 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005669 _Py_END_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005670
Serhiy Storchakaef347532018-05-01 16:45:04 +03005671 if (err_code) {
5672 errno = err_code;
5673 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005674 goto exit;
5675 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08005676#ifdef _Py_MEMORY_SANITIZER
5677 __msan_unpoison(&pid, sizeof(pid));
5678#endif
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005679 result = PyLong_FromPid(pid);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005680
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005681exit:
Serhiy Storchakaef347532018-05-01 16:45:04 +03005682 if (file_actionsp) {
5683 (void)posix_spawn_file_actions_destroy(file_actionsp);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005684 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005685 if (attrp) {
5686 (void)posix_spawnattr_destroy(attrp);
5687 }
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005688 if (envlist) {
5689 free_string_array(envlist, envc);
5690 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005691 if (argvlist) {
5692 free_string_array(argvlist, argc);
5693 }
Pablo Galindocb970732018-06-19 09:19:50 +01005694 Py_XDECREF(temp_buffer);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005695 return result;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005696}
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005697
5698
5699/*[clinic input]
5700
5701os.posix_spawn
5702 path: path_t
5703 Path of executable file.
5704 argv: object
5705 Tuple or list of strings.
5706 env: object
5707 Dictionary of strings mapping to strings.
5708 /
5709 *
5710 file_actions: object(c_default='NULL') = ()
5711 A sequence of file action tuples.
5712 setpgroup: object = NULL
5713 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5714 resetids: bool(accept={int}) = False
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005715 If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
5716 setsid: bool(accept={int}) = False
5717 If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005718 setsigmask: object(c_default='NULL') = ()
5719 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5720 setsigdef: object(c_default='NULL') = ()
5721 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5722 scheduler: object = NULL
5723 A tuple with the scheduler policy (optional) and parameters.
5724
5725Execute the program specified by path in a new process.
5726[clinic start generated code]*/
5727
5728static PyObject *
5729os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
5730 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005731 PyObject *setpgroup, int resetids, int setsid,
5732 PyObject *setsigmask, PyObject *setsigdef,
5733 PyObject *scheduler)
5734/*[clinic end generated code: output=14a1098c566bc675 input=8c6305619a00ad04]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005735{
5736 return py_posix_spawn(0, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005737 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005738 scheduler);
5739}
5740 #endif /* HAVE_POSIX_SPAWN */
5741
5742
5743
5744#ifdef HAVE_POSIX_SPAWNP
5745/*[clinic input]
5746
5747os.posix_spawnp
5748 path: path_t
5749 Path of executable file.
5750 argv: object
5751 Tuple or list of strings.
5752 env: object
5753 Dictionary of strings mapping to strings.
5754 /
5755 *
5756 file_actions: object(c_default='NULL') = ()
5757 A sequence of file action tuples.
5758 setpgroup: object = NULL
5759 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5760 resetids: bool(accept={int}) = False
5761 If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005762 setsid: bool(accept={int}) = False
5763 If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005764 setsigmask: object(c_default='NULL') = ()
5765 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5766 setsigdef: object(c_default='NULL') = ()
5767 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5768 scheduler: object = NULL
5769 A tuple with the scheduler policy (optional) and parameters.
5770
5771Execute the program specified by path in a new process.
5772[clinic start generated code]*/
5773
5774static PyObject *
5775os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
5776 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005777 PyObject *setpgroup, int resetids, int setsid,
5778 PyObject *setsigmask, PyObject *setsigdef,
5779 PyObject *scheduler)
5780/*[clinic end generated code: output=7b9aaefe3031238d input=c1911043a22028da]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005781{
5782 return py_posix_spawn(1, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005783 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005784 scheduler);
5785}
5786#endif /* HAVE_POSIX_SPAWNP */
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005787
pxinwrf2d7ac72019-05-21 18:46:37 +08005788#ifdef HAVE_RTPSPAWN
5789static intptr_t
5790_rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
5791 const char *envp[])
5792{
5793 RTP_ID rtpid;
5794 int status;
5795 pid_t res;
5796 int async_err = 0;
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005797
pxinwrf2d7ac72019-05-21 18:46:37 +08005798 /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
5799 uStackSize=0 cannot be used, the default stack size is too small for
5800 Python. */
5801 if (envp) {
5802 rtpid = rtpSpawn(rtpFileName, argv, envp,
5803 100, 0x1000000, 0, VX_FP_TASK);
5804 }
5805 else {
5806 rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
5807 100, 0x1000000, 0, VX_FP_TASK);
5808 }
5809 if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
5810 do {
5811 res = waitpid((pid_t)rtpid, &status, 0);
5812 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
5813
5814 if (res < 0)
5815 return RTP_ID_ERROR;
5816 return ((intptr_t)status);
5817 }
5818 return ((intptr_t)rtpid);
5819}
5820#endif
5821
5822#if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
Larry Hastings2f936352014-08-05 14:04:04 +10005823/*[clinic input]
5824os.spawnv
5825
5826 mode: int
5827 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005828 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005829 Path of executable file.
5830 argv: object
5831 Tuple or list of strings.
5832 /
5833
5834Execute the program specified by path in a new process.
5835[clinic start generated code]*/
5836
Larry Hastings2f936352014-08-05 14:04:04 +10005837static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005838os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
5839/*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005840{
Steve Dowercc16be82016-09-08 10:35:16 -07005841 EXECV_CHAR **argvlist;
Larry Hastings2f936352014-08-05 14:04:04 +10005842 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00005843 Py_ssize_t argc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005844 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005845 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Guido van Rossuma1065681999-01-25 23:20:23 +00005846
Victor Stinner8c62be82010-05-06 00:08:46 +00005847 /* spawnv has three arguments: (mode, path, argv), where
5848 argv is a list or tuple of strings. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005849
Victor Stinner8c62be82010-05-06 00:08:46 +00005850 if (PyList_Check(argv)) {
5851 argc = PyList_Size(argv);
5852 getitem = PyList_GetItem;
5853 }
5854 else if (PyTuple_Check(argv)) {
5855 argc = PyTuple_Size(argv);
5856 getitem = PyTuple_GetItem;
5857 }
5858 else {
5859 PyErr_SetString(PyExc_TypeError,
5860 "spawnv() arg 2 must be a tuple or list");
Victor Stinner8c62be82010-05-06 00:08:46 +00005861 return NULL;
5862 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005863 if (argc == 0) {
5864 PyErr_SetString(PyExc_ValueError,
5865 "spawnv() arg 2 cannot be empty");
5866 return NULL;
5867 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005868
Steve Dowercc16be82016-09-08 10:35:16 -07005869 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005870 if (argvlist == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005871 return PyErr_NoMemory();
5872 }
5873 for (i = 0; i < argc; i++) {
5874 if (!fsconvert_strdup((*getitem)(argv, i),
5875 &argvlist[i])) {
5876 free_string_array(argvlist, i);
5877 PyErr_SetString(
5878 PyExc_TypeError,
5879 "spawnv() arg 2 must contain only strings");
Victor Stinner8c62be82010-05-06 00:08:46 +00005880 return NULL;
5881 }
Steve Dower93ff8722016-11-19 19:03:54 -08005882 if (i == 0 && !argvlist[0][0]) {
Victor Stinner8acb4cf2017-06-15 15:30:40 +02005883 free_string_array(argvlist, i + 1);
Steve Dower93ff8722016-11-19 19:03:54 -08005884 PyErr_SetString(
5885 PyExc_ValueError,
5886 "spawnv() arg 2 first element cannot be empty");
5887 return NULL;
5888 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005889 }
5890 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005891
pxinwrf2d7ac72019-05-21 18:46:37 +08005892#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00005893 if (mode == _OLD_P_OVERLAY)
5894 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08005895#endif
Tim Peters5aa91602002-01-30 05:46:57 +00005896
Victor Stinner8c62be82010-05-06 00:08:46 +00005897 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07005898 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005899#ifdef HAVE_WSPAWNV
5900 spawnval = _wspawnv(mode, path->wide, argvlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08005901#elif defined(HAVE_RTPSPAWN)
5902 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
Steve Dowercc16be82016-09-08 10:35:16 -07005903#else
5904 spawnval = _spawnv(mode, path->narrow, argvlist);
5905#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07005906 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00005907 Py_END_ALLOW_THREADS
Tim Peters5aa91602002-01-30 05:46:57 +00005908
Victor Stinner8c62be82010-05-06 00:08:46 +00005909 free_string_array(argvlist, argc);
Guido van Rossuma1065681999-01-25 23:20:23 +00005910
Victor Stinner8c62be82010-05-06 00:08:46 +00005911 if (spawnval == -1)
5912 return posix_error();
5913 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01005914 return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00005915}
5916
Larry Hastings2f936352014-08-05 14:04:04 +10005917/*[clinic input]
5918os.spawnve
5919
5920 mode: int
5921 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005922 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005923 Path of executable file.
5924 argv: object
5925 Tuple or list of strings.
5926 env: object
5927 Dictionary of strings mapping to strings.
5928 /
5929
5930Execute the program specified by path in a new process.
5931[clinic start generated code]*/
5932
Larry Hastings2f936352014-08-05 14:04:04 +10005933static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005934os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005935 PyObject *env)
Steve Dowercc16be82016-09-08 10:35:16 -07005936/*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005937{
Steve Dowercc16be82016-09-08 10:35:16 -07005938 EXECV_CHAR **argvlist;
5939 EXECV_CHAR **envlist;
Victor Stinner8c62be82010-05-06 00:08:46 +00005940 PyObject *res = NULL;
Antoine Pitrou22e41552010-08-15 18:07:50 +00005941 Py_ssize_t argc, i, envc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005942 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005943 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005944 Py_ssize_t lastarg = 0;
Guido van Rossuma1065681999-01-25 23:20:23 +00005945
Victor Stinner8c62be82010-05-06 00:08:46 +00005946 /* spawnve has four arguments: (mode, path, argv, env), where
5947 argv is a list or tuple of strings and env is a dictionary
5948 like posix.environ. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005949
Victor Stinner8c62be82010-05-06 00:08:46 +00005950 if (PyList_Check(argv)) {
5951 argc = PyList_Size(argv);
5952 getitem = PyList_GetItem;
5953 }
5954 else if (PyTuple_Check(argv)) {
5955 argc = PyTuple_Size(argv);
5956 getitem = PyTuple_GetItem;
5957 }
5958 else {
5959 PyErr_SetString(PyExc_TypeError,
5960 "spawnve() arg 2 must be a tuple or list");
5961 goto fail_0;
5962 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005963 if (argc == 0) {
5964 PyErr_SetString(PyExc_ValueError,
5965 "spawnve() arg 2 cannot be empty");
5966 goto fail_0;
5967 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005968 if (!PyMapping_Check(env)) {
5969 PyErr_SetString(PyExc_TypeError,
5970 "spawnve() arg 3 must be a mapping object");
5971 goto fail_0;
5972 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005973
Steve Dowercc16be82016-09-08 10:35:16 -07005974 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005975 if (argvlist == NULL) {
5976 PyErr_NoMemory();
5977 goto fail_0;
5978 }
5979 for (i = 0; i < argc; i++) {
5980 if (!fsconvert_strdup((*getitem)(argv, i),
5981 &argvlist[i]))
5982 {
5983 lastarg = i;
5984 goto fail_1;
5985 }
Steve Dowerbce26262016-11-19 19:17:26 -08005986 if (i == 0 && !argvlist[0][0]) {
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005987 lastarg = i + 1;
Steve Dowerbce26262016-11-19 19:17:26 -08005988 PyErr_SetString(
5989 PyExc_ValueError,
5990 "spawnv() arg 2 first element cannot be empty");
5991 goto fail_1;
5992 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005993 }
5994 lastarg = argc;
5995 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005996
Victor Stinner8c62be82010-05-06 00:08:46 +00005997 envlist = parse_envlist(env, &envc);
5998 if (envlist == NULL)
5999 goto fail_1;
Guido van Rossuma1065681999-01-25 23:20:23 +00006000
pxinwrf2d7ac72019-05-21 18:46:37 +08006001#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00006002 if (mode == _OLD_P_OVERLAY)
6003 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08006004#endif
Tim Peters25059d32001-12-07 20:35:43 +00006005
Victor Stinner8c62be82010-05-06 00:08:46 +00006006 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07006007 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07006008#ifdef HAVE_WSPAWNV
6009 spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08006010#elif defined(HAVE_RTPSPAWN)
6011 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
6012 (const char **)envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07006013#else
6014 spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
6015#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07006016 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00006017 Py_END_ALLOW_THREADS
Tim Peters25059d32001-12-07 20:35:43 +00006018
Victor Stinner8c62be82010-05-06 00:08:46 +00006019 if (spawnval == -1)
6020 (void) posix_error();
6021 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01006022 res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00006023
Victor Stinner8c62be82010-05-06 00:08:46 +00006024 while (--envc >= 0)
6025 PyMem_DEL(envlist[envc]);
6026 PyMem_DEL(envlist);
Guido van Rossum0847c5c2002-12-13 18:36:22 +00006027 fail_1:
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006028 free_string_array(argvlist, lastarg);
Martin v. Löwis114619e2002-10-07 06:44:21 +00006029 fail_0:
Victor Stinner8c62be82010-05-06 00:08:46 +00006030 return res;
Guido van Rossuma1065681999-01-25 23:20:23 +00006031}
Andrew MacIntyre69e18c92004-04-04 07:11:43 +00006032
Guido van Rossuma1065681999-01-25 23:20:23 +00006033#endif /* HAVE_SPAWNV */
6034
6035
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006036#ifdef HAVE_FORK
Gregory P. Smith163468a2017-05-29 10:03:41 -07006037
6038/* Helper function to validate arguments.
6039 Returns 0 on success. non-zero on failure with a TypeError raised.
6040 If obj is non-NULL it must be callable. */
6041static int
6042check_null_or_callable(PyObject *obj, const char* obj_name)
6043{
6044 if (obj && !PyCallable_Check(obj)) {
6045 PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
Eddie Elizondob3966632019-11-05 07:16:14 -08006046 obj_name, _PyType_Name(Py_TYPE(obj)));
Gregory P. Smith163468a2017-05-29 10:03:41 -07006047 return -1;
6048 }
6049 return 0;
6050}
6051
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006052/*[clinic input]
6053os.register_at_fork
6054
Gregory P. Smith163468a2017-05-29 10:03:41 -07006055 *
6056 before: object=NULL
6057 A callable to be called in the parent before the fork() syscall.
6058 after_in_child: object=NULL
6059 A callable to be called in the child after fork().
6060 after_in_parent: object=NULL
6061 A callable to be called in the parent after fork().
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006062
Gregory P. Smith163468a2017-05-29 10:03:41 -07006063Register callables to be called when forking a new process.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006064
Gregory P. Smith163468a2017-05-29 10:03:41 -07006065'before' callbacks are called in reverse order.
6066'after_in_child' and 'after_in_parent' callbacks are called in order.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006067
6068[clinic start generated code]*/
6069
6070static PyObject *
Gregory P. Smith163468a2017-05-29 10:03:41 -07006071os_register_at_fork_impl(PyObject *module, PyObject *before,
6072 PyObject *after_in_child, PyObject *after_in_parent)
6073/*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006074{
6075 PyInterpreterState *interp;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006076
Gregory P. Smith163468a2017-05-29 10:03:41 -07006077 if (!before && !after_in_child && !after_in_parent) {
6078 PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
6079 return NULL;
6080 }
6081 if (check_null_or_callable(before, "before") ||
6082 check_null_or_callable(after_in_child, "after_in_child") ||
6083 check_null_or_callable(after_in_parent, "after_in_parent")) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006084 return NULL;
6085 }
Victor Stinnercaba55b2018-08-03 15:33:52 +02006086 interp = _PyInterpreterState_Get();
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006087
Gregory P. Smith163468a2017-05-29 10:03:41 -07006088 if (register_at_forker(&interp->before_forkers, before)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006089 return NULL;
6090 }
Gregory P. Smith163468a2017-05-29 10:03:41 -07006091 if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006092 return NULL;
Gregory P. Smith163468a2017-05-29 10:03:41 -07006093 }
6094 if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
6095 return NULL;
6096 }
6097 Py_RETURN_NONE;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006098}
6099#endif /* HAVE_FORK */
6100
6101
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006102#ifdef HAVE_FORK1
Larry Hastings2f936352014-08-05 14:04:04 +10006103/*[clinic input]
6104os.fork1
6105
6106Fork a child process with a single multiplexed (i.e., not bound) thread.
6107
6108Return 0 to child process and PID of child to parent process.
6109[clinic start generated code]*/
6110
Larry Hastings2f936352014-08-05 14:04:04 +10006111static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006112os_fork1_impl(PyObject *module)
6113/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006114{
Victor Stinner8c62be82010-05-06 00:08:46 +00006115 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006116
Eric Snow59032962018-09-14 14:17:20 -07006117 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6118 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6119 return NULL;
6120 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006121 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006122 pid = fork1();
6123 if (pid == 0) {
6124 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006125 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006126 } else {
6127 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006128 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006129 }
6130 if (pid == -1)
6131 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006132 return PyLong_FromPid(pid);
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006133}
Larry Hastings2f936352014-08-05 14:04:04 +10006134#endif /* HAVE_FORK1 */
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006135
6136
Guido van Rossumad0ee831995-03-01 10:34:45 +00006137#ifdef HAVE_FORK
Larry Hastings2f936352014-08-05 14:04:04 +10006138/*[clinic input]
6139os.fork
6140
6141Fork a child process.
6142
6143Return 0 to child process and PID of child to parent process.
6144[clinic start generated code]*/
6145
Larry Hastings2f936352014-08-05 14:04:04 +10006146static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006147os_fork_impl(PyObject *module)
6148/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006149{
Victor Stinner8c62be82010-05-06 00:08:46 +00006150 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006151
Eric Snow59032962018-09-14 14:17:20 -07006152 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6153 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6154 return NULL;
6155 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006156 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006157 pid = fork();
6158 if (pid == 0) {
6159 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006160 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006161 } else {
6162 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006163 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006164 }
6165 if (pid == -1)
6166 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006167 return PyLong_FromPid(pid);
Guido van Rossum85e3b011991-06-03 12:42:10 +00006168}
Larry Hastings2f936352014-08-05 14:04:04 +10006169#endif /* HAVE_FORK */
6170
Guido van Rossum85e3b011991-06-03 12:42:10 +00006171
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006172#ifdef HAVE_SCHED_H
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006173#ifdef HAVE_SCHED_GET_PRIORITY_MAX
Larry Hastings2f936352014-08-05 14:04:04 +10006174/*[clinic input]
6175os.sched_get_priority_max
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006176
Larry Hastings2f936352014-08-05 14:04:04 +10006177 policy: int
6178
6179Get the maximum scheduling priority for policy.
6180[clinic start generated code]*/
6181
Larry Hastings2f936352014-08-05 14:04:04 +10006182static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006183os_sched_get_priority_max_impl(PyObject *module, int policy)
6184/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006185{
6186 int max;
6187
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006188 max = sched_get_priority_max(policy);
6189 if (max < 0)
6190 return posix_error();
6191 return PyLong_FromLong(max);
6192}
6193
Larry Hastings2f936352014-08-05 14:04:04 +10006194
6195/*[clinic input]
6196os.sched_get_priority_min
6197
6198 policy: int
6199
6200Get the minimum scheduling priority for policy.
6201[clinic start generated code]*/
6202
Larry Hastings2f936352014-08-05 14:04:04 +10006203static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006204os_sched_get_priority_min_impl(PyObject *module, int policy)
6205/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006206{
6207 int min = sched_get_priority_min(policy);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006208 if (min < 0)
6209 return posix_error();
6210 return PyLong_FromLong(min);
6211}
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006212#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
6213
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006214
Larry Hastings2f936352014-08-05 14:04:04 +10006215#ifdef HAVE_SCHED_SETSCHEDULER
6216/*[clinic input]
6217os.sched_getscheduler
6218 pid: pid_t
6219 /
6220
Min ho Kimc4cacc82019-07-31 08:16:13 +10006221Get the scheduling policy for the process identified by pid.
Larry Hastings2f936352014-08-05 14:04:04 +10006222
6223Passing 0 for pid returns the scheduling policy for the calling process.
6224[clinic start generated code]*/
6225
Larry Hastings2f936352014-08-05 14:04:04 +10006226static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006227os_sched_getscheduler_impl(PyObject *module, pid_t pid)
Min ho Kimc4cacc82019-07-31 08:16:13 +10006228/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=8d99dac505485ac8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006229{
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006230 int policy;
6231
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006232 policy = sched_getscheduler(pid);
6233 if (policy < 0)
6234 return posix_error();
6235 return PyLong_FromLong(policy);
6236}
Larry Hastings2f936352014-08-05 14:04:04 +10006237#endif /* HAVE_SCHED_SETSCHEDULER */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006238
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006239
William Orr81574b82018-10-01 22:19:56 -07006240#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Larry Hastings2f936352014-08-05 14:04:04 +10006241/*[clinic input]
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006242class os.sched_param "PyObject *" "SchedParamType"
Larry Hastings2f936352014-08-05 14:04:04 +10006243
6244@classmethod
6245os.sched_param.__new__
6246
6247 sched_priority: object
6248 A scheduling parameter.
6249
Eddie Elizondob3966632019-11-05 07:16:14 -08006250Currently has only one field: sched_priority
Larry Hastings2f936352014-08-05 14:04:04 +10006251[clinic start generated code]*/
6252
Larry Hastings2f936352014-08-05 14:04:04 +10006253static PyObject *
6254os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
Eddie Elizondob3966632019-11-05 07:16:14 -08006255/*[clinic end generated code: output=48f4067d60f48c13 input=eb42909a2c0e3e6c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006256{
6257 PyObject *res;
6258
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006259 res = PyStructSequence_New(type);
6260 if (!res)
6261 return NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10006262 Py_INCREF(sched_priority);
6263 PyStructSequence_SET_ITEM(res, 0, sched_priority);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006264 return res;
6265}
6266
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03006267PyDoc_VAR(os_sched_param__doc__);
6268
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006269static PyStructSequence_Field sched_param_fields[] = {
6270 {"sched_priority", "the scheduling priority"},
6271 {0}
6272};
6273
6274static PyStructSequence_Desc sched_param_desc = {
6275 "sched_param", /* name */
Larry Hastings2f936352014-08-05 14:04:04 +10006276 os_sched_param__doc__, /* doc */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006277 sched_param_fields,
6278 1
6279};
6280
6281static int
6282convert_sched_param(PyObject *param, struct sched_param *res)
6283{
6284 long priority;
6285
Eddie Elizondob3966632019-11-05 07:16:14 -08006286 PyObject *SchedParamType = _posixstate_global->SchedParamType;
6287 if (Py_TYPE(param) != (PyTypeObject *)SchedParamType) {
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006288 PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
6289 return 0;
6290 }
6291 priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
6292 if (priority == -1 && PyErr_Occurred())
6293 return 0;
6294 if (priority > INT_MAX || priority < INT_MIN) {
6295 PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
6296 return 0;
6297 }
6298 res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
6299 return 1;
6300}
William Orr81574b82018-10-01 22:19:56 -07006301#endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006302
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006303
6304#ifdef HAVE_SCHED_SETSCHEDULER
Larry Hastings2f936352014-08-05 14:04:04 +10006305/*[clinic input]
6306os.sched_setscheduler
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006307
Larry Hastings2f936352014-08-05 14:04:04 +10006308 pid: pid_t
6309 policy: int
6310 param: sched_param
6311 /
6312
6313Set the scheduling policy for the process identified by pid.
6314
6315If pid is 0, the calling process is changed.
6316param is an instance of sched_param.
6317[clinic start generated code]*/
6318
Larry Hastings2f936352014-08-05 14:04:04 +10006319static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006320os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
Larry Hastings89964c42015-04-14 18:07:59 -04006321 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006322/*[clinic end generated code: output=b0ac0a70d3b1d705 input=c581f9469a5327dd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006323{
Jesus Cea9c822272011-09-10 01:40:52 +02006324 /*
Jesus Cea54b01492011-09-10 01:53:19 +02006325 ** sched_setscheduler() returns 0 in Linux, but the previous
6326 ** scheduling policy under Solaris/Illumos, and others.
6327 ** On error, -1 is returned in all Operating Systems.
Jesus Cea9c822272011-09-10 01:40:52 +02006328 */
Larry Hastings2f936352014-08-05 14:04:04 +10006329 if (sched_setscheduler(pid, policy, param) == -1)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006330 return posix_error();
6331 Py_RETURN_NONE;
6332}
Larry Hastings2f936352014-08-05 14:04:04 +10006333#endif /* HAVE_SCHED_SETSCHEDULER*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006334
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006335
6336#ifdef HAVE_SCHED_SETPARAM
Larry Hastings2f936352014-08-05 14:04:04 +10006337/*[clinic input]
6338os.sched_getparam
6339 pid: pid_t
6340 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006341
Larry Hastings2f936352014-08-05 14:04:04 +10006342Returns scheduling parameters for the process identified by pid.
6343
6344If pid is 0, returns parameters for the calling process.
6345Return value is an instance of sched_param.
6346[clinic start generated code]*/
6347
Larry Hastings2f936352014-08-05 14:04:04 +10006348static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006349os_sched_getparam_impl(PyObject *module, pid_t pid)
6350/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006351{
6352 struct sched_param param;
6353 PyObject *result;
6354 PyObject *priority;
6355
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006356 if (sched_getparam(pid, &param))
6357 return posix_error();
Eddie Elizondob3966632019-11-05 07:16:14 -08006358 PyObject *SchedParamType = _posixstate_global->SchedParamType;
6359 result = PyStructSequence_New((PyTypeObject *)SchedParamType);
Larry Hastings2f936352014-08-05 14:04:04 +10006360 if (!result)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006361 return NULL;
6362 priority = PyLong_FromLong(param.sched_priority);
6363 if (!priority) {
Larry Hastings2f936352014-08-05 14:04:04 +10006364 Py_DECREF(result);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006365 return NULL;
6366 }
Larry Hastings2f936352014-08-05 14:04:04 +10006367 PyStructSequence_SET_ITEM(result, 0, priority);
6368 return result;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006369}
6370
Larry Hastings2f936352014-08-05 14:04:04 +10006371
6372/*[clinic input]
6373os.sched_setparam
6374 pid: pid_t
6375 param: sched_param
6376 /
6377
6378Set scheduling parameters for the process identified by pid.
6379
6380If pid is 0, sets parameters for the calling process.
6381param should be an instance of sched_param.
6382[clinic start generated code]*/
6383
Larry Hastings2f936352014-08-05 14:04:04 +10006384static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006385os_sched_setparam_impl(PyObject *module, pid_t pid,
Larry Hastings89964c42015-04-14 18:07:59 -04006386 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006387/*[clinic end generated code: output=8af013f78a32b591 input=6b8d6dfcecdc21bd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006388{
6389 if (sched_setparam(pid, param))
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006390 return posix_error();
6391 Py_RETURN_NONE;
6392}
Larry Hastings2f936352014-08-05 14:04:04 +10006393#endif /* HAVE_SCHED_SETPARAM */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006394
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006395
6396#ifdef HAVE_SCHED_RR_GET_INTERVAL
Larry Hastings2f936352014-08-05 14:04:04 +10006397/*[clinic input]
6398os.sched_rr_get_interval -> double
6399 pid: pid_t
6400 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006401
Larry Hastings2f936352014-08-05 14:04:04 +10006402Return the round-robin quantum for the process identified by pid, in seconds.
6403
6404Value returned is a float.
6405[clinic start generated code]*/
6406
Larry Hastings2f936352014-08-05 14:04:04 +10006407static double
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006408os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
6409/*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006410{
6411 struct timespec interval;
6412 if (sched_rr_get_interval(pid, &interval)) {
6413 posix_error();
6414 return -1.0;
6415 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006416#ifdef _Py_MEMORY_SANITIZER
6417 __msan_unpoison(&interval, sizeof(interval));
6418#endif
Larry Hastings2f936352014-08-05 14:04:04 +10006419 return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
6420}
6421#endif /* HAVE_SCHED_RR_GET_INTERVAL */
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006422
Larry Hastings2f936352014-08-05 14:04:04 +10006423
6424/*[clinic input]
6425os.sched_yield
6426
6427Voluntarily relinquish the CPU.
6428[clinic start generated code]*/
6429
Larry Hastings2f936352014-08-05 14:04:04 +10006430static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006431os_sched_yield_impl(PyObject *module)
6432/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006433{
6434 if (sched_yield())
6435 return posix_error();
6436 Py_RETURN_NONE;
6437}
6438
Benjamin Peterson2740af82011-08-02 17:41:34 -05006439#ifdef HAVE_SCHED_SETAFFINITY
Antoine Pitrou84869872012-08-04 16:16:35 +02006440/* The minimum number of CPUs allocated in a cpu_set_t */
6441static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006442
Larry Hastings2f936352014-08-05 14:04:04 +10006443/*[clinic input]
6444os.sched_setaffinity
6445 pid: pid_t
6446 mask : object
6447 /
6448
6449Set the CPU affinity of the process identified by pid to mask.
6450
6451mask should be an iterable of integers identifying CPUs.
6452[clinic start generated code]*/
6453
Larry Hastings2f936352014-08-05 14:04:04 +10006454static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006455os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
6456/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006457{
Antoine Pitrou84869872012-08-04 16:16:35 +02006458 int ncpus;
6459 size_t setsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006460 cpu_set_t *cpu_set = NULL;
6461 PyObject *iterator = NULL, *item;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006462
Larry Hastings2f936352014-08-05 14:04:04 +10006463 iterator = PyObject_GetIter(mask);
Antoine Pitrou84869872012-08-04 16:16:35 +02006464 if (iterator == NULL)
6465 return NULL;
6466
6467 ncpus = NCPUS_START;
6468 setsize = CPU_ALLOC_SIZE(ncpus);
Larry Hastings2f936352014-08-05 14:04:04 +10006469 cpu_set = CPU_ALLOC(ncpus);
6470 if (cpu_set == NULL) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006471 PyErr_NoMemory();
6472 goto error;
6473 }
Larry Hastings2f936352014-08-05 14:04:04 +10006474 CPU_ZERO_S(setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006475
6476 while ((item = PyIter_Next(iterator))) {
6477 long cpu;
6478 if (!PyLong_Check(item)) {
6479 PyErr_Format(PyExc_TypeError,
6480 "expected an iterator of ints, "
6481 "but iterator yielded %R",
6482 Py_TYPE(item));
6483 Py_DECREF(item);
6484 goto error;
6485 }
6486 cpu = PyLong_AsLong(item);
6487 Py_DECREF(item);
6488 if (cpu < 0) {
6489 if (!PyErr_Occurred())
6490 PyErr_SetString(PyExc_ValueError, "negative CPU number");
6491 goto error;
6492 }
6493 if (cpu > INT_MAX - 1) {
6494 PyErr_SetString(PyExc_OverflowError, "CPU number too large");
6495 goto error;
6496 }
6497 if (cpu >= ncpus) {
6498 /* Grow CPU mask to fit the CPU number */
6499 int newncpus = ncpus;
6500 cpu_set_t *newmask;
6501 size_t newsetsize;
6502 while (newncpus <= cpu) {
6503 if (newncpus > INT_MAX / 2)
6504 newncpus = cpu + 1;
6505 else
6506 newncpus = newncpus * 2;
6507 }
6508 newmask = CPU_ALLOC(newncpus);
6509 if (newmask == NULL) {
6510 PyErr_NoMemory();
6511 goto error;
6512 }
6513 newsetsize = CPU_ALLOC_SIZE(newncpus);
6514 CPU_ZERO_S(newsetsize, newmask);
Larry Hastings2f936352014-08-05 14:04:04 +10006515 memcpy(newmask, cpu_set, setsize);
6516 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006517 setsize = newsetsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006518 cpu_set = newmask;
Antoine Pitrou84869872012-08-04 16:16:35 +02006519 ncpus = newncpus;
6520 }
Larry Hastings2f936352014-08-05 14:04:04 +10006521 CPU_SET_S(cpu, setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006522 }
Brandt Bucher45a30af2019-06-27 09:10:57 -07006523 if (PyErr_Occurred()) {
6524 goto error;
6525 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006526 Py_CLEAR(iterator);
6527
Larry Hastings2f936352014-08-05 14:04:04 +10006528 if (sched_setaffinity(pid, setsize, cpu_set)) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006529 posix_error();
6530 goto error;
6531 }
Larry Hastings2f936352014-08-05 14:04:04 +10006532 CPU_FREE(cpu_set);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006533 Py_RETURN_NONE;
Antoine Pitrou84869872012-08-04 16:16:35 +02006534
6535error:
Larry Hastings2f936352014-08-05 14:04:04 +10006536 if (cpu_set)
6537 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006538 Py_XDECREF(iterator);
6539 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006540}
6541
Larry Hastings2f936352014-08-05 14:04:04 +10006542
6543/*[clinic input]
6544os.sched_getaffinity
6545 pid: pid_t
6546 /
6547
Charles-François Natalidc87e4b2015-07-13 21:01:39 +01006548Return the affinity of the process identified by pid (or the current process if zero).
Larry Hastings2f936352014-08-05 14:04:04 +10006549
6550The affinity is returned as a set of CPU identifiers.
6551[clinic start generated code]*/
6552
Larry Hastings2f936352014-08-05 14:04:04 +10006553static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006554os_sched_getaffinity_impl(PyObject *module, pid_t pid)
Serhiy Storchaka2954f832016-07-07 18:20:03 +03006555/*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006556{
Antoine Pitrou84869872012-08-04 16:16:35 +02006557 int cpu, ncpus, count;
6558 size_t setsize;
6559 cpu_set_t *mask = NULL;
6560 PyObject *res = NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006561
Antoine Pitrou84869872012-08-04 16:16:35 +02006562 ncpus = NCPUS_START;
6563 while (1) {
6564 setsize = CPU_ALLOC_SIZE(ncpus);
6565 mask = CPU_ALLOC(ncpus);
6566 if (mask == NULL)
6567 return PyErr_NoMemory();
6568 if (sched_getaffinity(pid, setsize, mask) == 0)
6569 break;
6570 CPU_FREE(mask);
6571 if (errno != EINVAL)
6572 return posix_error();
6573 if (ncpus > INT_MAX / 2) {
6574 PyErr_SetString(PyExc_OverflowError, "could not allocate "
6575 "a large enough CPU set");
6576 return NULL;
6577 }
6578 ncpus = ncpus * 2;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006579 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006580
6581 res = PySet_New(NULL);
6582 if (res == NULL)
6583 goto error;
6584 for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
6585 if (CPU_ISSET_S(cpu, setsize, mask)) {
6586 PyObject *cpu_num = PyLong_FromLong(cpu);
6587 --count;
6588 if (cpu_num == NULL)
6589 goto error;
6590 if (PySet_Add(res, cpu_num)) {
6591 Py_DECREF(cpu_num);
6592 goto error;
6593 }
6594 Py_DECREF(cpu_num);
6595 }
6596 }
6597 CPU_FREE(mask);
6598 return res;
6599
6600error:
6601 if (mask)
6602 CPU_FREE(mask);
6603 Py_XDECREF(res);
6604 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006605}
6606
Benjamin Peterson2740af82011-08-02 17:41:34 -05006607#endif /* HAVE_SCHED_SETAFFINITY */
6608
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006609#endif /* HAVE_SCHED_H */
6610
Larry Hastings2f936352014-08-05 14:04:04 +10006611
Neal Norwitzb59798b2003-03-21 01:43:31 +00006612/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
Neal Norwitz2deaddb2003-03-21 03:08:31 +00006613/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
6614#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
Neal Norwitzb59798b2003-03-21 01:43:31 +00006615#define DEV_PTY_FILE "/dev/ptc"
6616#define HAVE_DEV_PTMX
6617#else
6618#define DEV_PTY_FILE "/dev/ptmx"
6619#endif
6620
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006621#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
Fred Drake8cef4cf2000-06-28 16:40:38 +00006622#ifdef HAVE_PTY_H
6623#include <pty.h>
6624#else
6625#ifdef HAVE_LIBUTIL_H
6626#include <libutil.h>
Ronald Oussoren755740f2010-02-07 19:56:39 +00006627#else
6628#ifdef HAVE_UTIL_H
6629#include <util.h>
6630#endif /* HAVE_UTIL_H */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006631#endif /* HAVE_LIBUTIL_H */
6632#endif /* HAVE_PTY_H */
Martin v. Löwis14e73b12003-01-01 09:51:12 +00006633#ifdef HAVE_STROPTS_H
6634#include <stropts.h>
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006635#endif
ngie-eign7745ec42018-02-14 11:54:28 -08006636#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006637
Larry Hastings2f936352014-08-05 14:04:04 +10006638
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006639#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
Larry Hastings2f936352014-08-05 14:04:04 +10006640/*[clinic input]
6641os.openpty
6642
6643Open a pseudo-terminal.
6644
6645Return a tuple of (master_fd, slave_fd) containing open file descriptors
6646for both the master and slave ends.
6647[clinic start generated code]*/
6648
Larry Hastings2f936352014-08-05 14:04:04 +10006649static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006650os_openpty_impl(PyObject *module)
6651/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006652{
Victor Stinnerdaf45552013-08-28 00:53:59 +02006653 int master_fd = -1, slave_fd = -1;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006654#ifndef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006655 char * slave_name;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006656#endif
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006657#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006658 PyOS_sighandler_t sig_saved;
Jakub Kulík6f9bc722018-12-31 03:16:40 +01006659#if defined(__sun) && defined(__SVR4)
Victor Stinner8c62be82010-05-06 00:08:46 +00006660 extern char *ptsname(int fildes);
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006661#endif
6662#endif
Thomas Wouters70c21a12000-07-14 14:28:33 +00006663
Thomas Wouters70c21a12000-07-14 14:28:33 +00006664#ifdef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006665 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006666 goto posix_error;
6667
6668 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6669 goto error;
6670 if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
6671 goto error;
6672
Neal Norwitzb59798b2003-03-21 01:43:31 +00006673#elif defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006674 slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
6675 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006676 goto posix_error;
6677 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6678 goto error;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006679
Victor Stinnerdaf45552013-08-28 00:53:59 +02006680 slave_fd = _Py_open(slave_name, O_RDWR);
Victor Stinner8c62be82010-05-06 00:08:46 +00006681 if (slave_fd < 0)
Victor Stinnera555cfc2015-03-18 00:22:14 +01006682 goto error;
Victor Stinnerdaf45552013-08-28 00:53:59 +02006683
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006684#else
Victor Stinner000de532013-11-25 23:19:58 +01006685 master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
Victor Stinner8c62be82010-05-06 00:08:46 +00006686 if (master_fd < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006687 goto posix_error;
6688
Victor Stinner8c62be82010-05-06 00:08:46 +00006689 sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006690
Victor Stinner8c62be82010-05-06 00:08:46 +00006691 /* change permission of slave */
6692 if (grantpt(master_fd) < 0) {
6693 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006694 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006695 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006696
Victor Stinner8c62be82010-05-06 00:08:46 +00006697 /* unlock slave */
6698 if (unlockpt(master_fd) < 0) {
6699 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006700 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006701 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006702
Victor Stinner8c62be82010-05-06 00:08:46 +00006703 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006704
Victor Stinner8c62be82010-05-06 00:08:46 +00006705 slave_name = ptsname(master_fd); /* get name of slave */
6706 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006707 goto posix_error;
6708
6709 slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
Victor Stinnera555cfc2015-03-18 00:22:14 +01006710 if (slave_fd == -1)
6711 goto error;
Victor Stinner000de532013-11-25 23:19:58 +01006712
6713 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6714 goto posix_error;
6715
Stefan Krahfb7c8ae2016-04-26 17:04:18 +02006716#if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
Victor Stinner8c62be82010-05-06 00:08:46 +00006717 ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
6718 ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
Neal Norwitz6700e472002-12-31 16:16:07 +00006719#ifndef __hpux
Victor Stinner8c62be82010-05-06 00:08:46 +00006720 ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
Neal Norwitz6700e472002-12-31 16:16:07 +00006721#endif /* __hpux */
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006722#endif /* HAVE_CYGWIN */
Thomas Wouters1e0c2f42000-07-24 16:06:23 +00006723#endif /* HAVE_OPENPTY */
Thomas Wouters70c21a12000-07-14 14:28:33 +00006724
Victor Stinner8c62be82010-05-06 00:08:46 +00006725 return Py_BuildValue("(ii)", master_fd, slave_fd);
Thomas Wouters70c21a12000-07-14 14:28:33 +00006726
Victor Stinnerdaf45552013-08-28 00:53:59 +02006727posix_error:
6728 posix_error();
6729error:
6730 if (master_fd != -1)
6731 close(master_fd);
6732 if (slave_fd != -1)
6733 close(slave_fd);
6734 return NULL;
Fred Drake8cef4cf2000-06-28 16:40:38 +00006735}
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006736#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006737
Larry Hastings2f936352014-08-05 14:04:04 +10006738
Fred Drake8cef4cf2000-06-28 16:40:38 +00006739#ifdef HAVE_FORKPTY
Larry Hastings2f936352014-08-05 14:04:04 +10006740/*[clinic input]
6741os.forkpty
6742
6743Fork a new process with a new pseudo-terminal as controlling tty.
6744
6745Returns a tuple of (pid, master_fd).
6746Like fork(), return pid of 0 to the child process,
6747and pid of child to the parent process.
6748To both, return fd of newly opened pseudo-terminal.
6749[clinic start generated code]*/
6750
Larry Hastings2f936352014-08-05 14:04:04 +10006751static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006752os_forkpty_impl(PyObject *module)
6753/*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006754{
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006755 int master_fd = -1;
Victor Stinner8c62be82010-05-06 00:08:46 +00006756 pid_t pid;
Tim Peters5aa91602002-01-30 05:46:57 +00006757
Eric Snow59032962018-09-14 14:17:20 -07006758 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6759 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6760 return NULL;
6761 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006762 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006763 pid = forkpty(&master_fd, NULL, NULL, NULL);
6764 if (pid == 0) {
6765 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006766 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006767 } else {
6768 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006769 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006770 }
6771 if (pid == -1)
6772 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006773 return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
Fred Drake8cef4cf2000-06-28 16:40:38 +00006774}
Larry Hastings2f936352014-08-05 14:04:04 +10006775#endif /* HAVE_FORKPTY */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006776
Ross Lagerwall7807c352011-03-17 20:20:30 +02006777
Guido van Rossumad0ee831995-03-01 10:34:45 +00006778#ifdef HAVE_GETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10006779/*[clinic input]
6780os.getegid
6781
6782Return the current process's effective group id.
6783[clinic start generated code]*/
6784
Larry Hastings2f936352014-08-05 14:04:04 +10006785static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006786os_getegid_impl(PyObject *module)
6787/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006788{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006789 return _PyLong_FromGid(getegid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006790}
Larry Hastings2f936352014-08-05 14:04:04 +10006791#endif /* HAVE_GETEGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006792
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006793
Guido van Rossumad0ee831995-03-01 10:34:45 +00006794#ifdef HAVE_GETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10006795/*[clinic input]
6796os.geteuid
6797
6798Return the current process's effective user id.
6799[clinic start generated code]*/
6800
Larry Hastings2f936352014-08-05 14:04:04 +10006801static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006802os_geteuid_impl(PyObject *module)
6803/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006804{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006805 return _PyLong_FromUid(geteuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006806}
Larry Hastings2f936352014-08-05 14:04:04 +10006807#endif /* HAVE_GETEUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006808
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006809
Guido van Rossumad0ee831995-03-01 10:34:45 +00006810#ifdef HAVE_GETGID
Larry Hastings2f936352014-08-05 14:04:04 +10006811/*[clinic input]
6812os.getgid
6813
6814Return the current process's group id.
6815[clinic start generated code]*/
6816
Larry Hastings2f936352014-08-05 14:04:04 +10006817static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006818os_getgid_impl(PyObject *module)
6819/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006820{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006821 return _PyLong_FromGid(getgid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006822}
Larry Hastings2f936352014-08-05 14:04:04 +10006823#endif /* HAVE_GETGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006824
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006825
Berker Peksag39404992016-09-15 20:45:16 +03006826#ifdef HAVE_GETPID
Larry Hastings2f936352014-08-05 14:04:04 +10006827/*[clinic input]
6828os.getpid
6829
6830Return the current process id.
6831[clinic start generated code]*/
6832
Larry Hastings2f936352014-08-05 14:04:04 +10006833static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006834os_getpid_impl(PyObject *module)
6835/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006836{
Victor Stinner8c62be82010-05-06 00:08:46 +00006837 return PyLong_FromPid(getpid());
Guido van Rossum85e3b011991-06-03 12:42:10 +00006838}
Berker Peksag39404992016-09-15 20:45:16 +03006839#endif /* HAVE_GETPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00006840
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07006841#ifdef NGROUPS_MAX
6842#define MAX_GROUPS NGROUPS_MAX
6843#else
6844 /* defined to be 16 on Solaris7, so this should be a small number */
6845#define MAX_GROUPS 64
6846#endif
6847
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006848#ifdef HAVE_GETGROUPLIST
Larry Hastings2f936352014-08-05 14:04:04 +10006849
6850/* AC 3.5: funny apple logic below */
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006851PyDoc_STRVAR(posix_getgrouplist__doc__,
6852"getgrouplist(user, group) -> list of groups to which a user belongs\n\n\
6853Returns a list of groups to which a user belongs.\n\n\
6854 user: username to lookup\n\
6855 group: base group id of the user");
6856
6857static PyObject *
6858posix_getgrouplist(PyObject *self, PyObject *args)
6859{
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006860 const char *user;
6861 int i, ngroups;
6862 PyObject *list;
6863#ifdef __APPLE__
6864 int *groups, basegid;
6865#else
6866 gid_t *groups, basegid;
6867#endif
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07006868
6869 /*
6870 * NGROUPS_MAX is defined by POSIX.1 as the maximum
6871 * number of supplimental groups a users can belong to.
6872 * We have to increment it by one because
6873 * getgrouplist() returns both the supplemental groups
6874 * and the primary group, i.e. all of the groups the
6875 * user belongs to.
6876 */
6877 ngroups = 1 + MAX_GROUPS;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006878
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006879#ifdef __APPLE__
6880 if (!PyArg_ParseTuple(args, "si:getgrouplist", &user, &basegid))
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006881 return NULL;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006882#else
6883 if (!PyArg_ParseTuple(args, "sO&:getgrouplist", &user,
6884 _Py_Gid_Converter, &basegid))
6885 return NULL;
6886#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006887
6888#ifdef __APPLE__
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006889 groups = PyMem_New(int, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006890#else
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006891 groups = PyMem_New(gid_t, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006892#endif
6893 if (groups == NULL)
6894 return PyErr_NoMemory();
6895
6896 if (getgrouplist(user, basegid, groups, &ngroups) == -1) {
6897 PyMem_Del(groups);
6898 return posix_error();
6899 }
6900
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006901#ifdef _Py_MEMORY_SANITIZER
6902 /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
6903 __msan_unpoison(&ngroups, sizeof(ngroups));
6904 __msan_unpoison(groups, ngroups*sizeof(*groups));
6905#endif
6906
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006907 list = PyList_New(ngroups);
6908 if (list == NULL) {
6909 PyMem_Del(groups);
6910 return NULL;
6911 }
6912
6913 for (i = 0; i < ngroups; i++) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006914#ifdef __APPLE__
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006915 PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006916#else
6917 PyObject *o = _PyLong_FromGid(groups[i]);
6918#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006919 if (o == NULL) {
6920 Py_DECREF(list);
6921 PyMem_Del(groups);
6922 return NULL;
6923 }
6924 PyList_SET_ITEM(list, i, o);
6925 }
6926
6927 PyMem_Del(groups);
6928
6929 return list;
6930}
Larry Hastings2f936352014-08-05 14:04:04 +10006931#endif /* HAVE_GETGROUPLIST */
6932
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006933
Fred Drakec9680921999-12-13 16:37:25 +00006934#ifdef HAVE_GETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10006935/*[clinic input]
6936os.getgroups
6937
6938Return list of supplemental group IDs for the process.
6939[clinic start generated code]*/
6940
Larry Hastings2f936352014-08-05 14:04:04 +10006941static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006942os_getgroups_impl(PyObject *module)
6943/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
Fred Drakec9680921999-12-13 16:37:25 +00006944{
6945 PyObject *result = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00006946 gid_t grouplist[MAX_GROUPS];
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006947
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00006948 /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006949 * This is a helper variable to store the intermediate result when
6950 * that happens.
6951 *
6952 * To keep the code readable the OSX behaviour is unconditional,
6953 * according to the POSIX spec this should be safe on all unix-y
6954 * systems.
6955 */
6956 gid_t* alt_grouplist = grouplist;
Victor Stinner8c62be82010-05-06 00:08:46 +00006957 int n;
Fred Drakec9680921999-12-13 16:37:25 +00006958
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006959#ifdef __APPLE__
6960 /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
6961 * there are more groups than can fit in grouplist. Therefore, on OS X
6962 * always first call getgroups with length 0 to get the actual number
6963 * of groups.
6964 */
6965 n = getgroups(0, NULL);
6966 if (n < 0) {
6967 return posix_error();
6968 } else if (n <= MAX_GROUPS) {
6969 /* groups will fit in existing array */
6970 alt_grouplist = grouplist;
6971 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006972 alt_grouplist = PyMem_New(gid_t, n);
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006973 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07006974 return PyErr_NoMemory();
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006975 }
6976 }
6977
6978 n = getgroups(n, alt_grouplist);
6979 if (n == -1) {
6980 if (alt_grouplist != grouplist) {
6981 PyMem_Free(alt_grouplist);
6982 }
6983 return posix_error();
6984 }
6985#else
Victor Stinner8c62be82010-05-06 00:08:46 +00006986 n = getgroups(MAX_GROUPS, grouplist);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006987 if (n < 0) {
6988 if (errno == EINVAL) {
6989 n = getgroups(0, NULL);
6990 if (n == -1) {
6991 return posix_error();
6992 }
6993 if (n == 0) {
6994 /* Avoid malloc(0) */
6995 alt_grouplist = grouplist;
6996 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006997 alt_grouplist = PyMem_New(gid_t, n);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006998 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07006999 return PyErr_NoMemory();
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007000 }
7001 n = getgroups(n, alt_grouplist);
7002 if (n == -1) {
7003 PyMem_Free(alt_grouplist);
7004 return posix_error();
7005 }
7006 }
7007 } else {
7008 return posix_error();
7009 }
7010 }
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007011#endif
7012
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007013 result = PyList_New(n);
7014 if (result != NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007015 int i;
7016 for (i = 0; i < n; ++i) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007017 PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
Victor Stinner8c62be82010-05-06 00:08:46 +00007018 if (o == NULL) {
Stefan Krah0e803b32010-11-26 16:16:47 +00007019 Py_DECREF(result);
7020 result = NULL;
7021 break;
Fred Drakec9680921999-12-13 16:37:25 +00007022 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007023 PyList_SET_ITEM(result, i, o);
Fred Drakec9680921999-12-13 16:37:25 +00007024 }
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007025 }
7026
7027 if (alt_grouplist != grouplist) {
7028 PyMem_Free(alt_grouplist);
Victor Stinner8c62be82010-05-06 00:08:46 +00007029 }
Neal Norwitze241ce82003-02-17 18:17:05 +00007030
Fred Drakec9680921999-12-13 16:37:25 +00007031 return result;
7032}
Larry Hastings2f936352014-08-05 14:04:04 +10007033#endif /* HAVE_GETGROUPS */
Fred Drakec9680921999-12-13 16:37:25 +00007034
Antoine Pitroub7572f02009-12-02 20:46:48 +00007035#ifdef HAVE_INITGROUPS
7036PyDoc_STRVAR(posix_initgroups__doc__,
7037"initgroups(username, gid) -> None\n\n\
7038Call the system initgroups() to initialize the group access list with all of\n\
7039the groups of which the specified username is a member, plus the specified\n\
7040group id.");
7041
Larry Hastings2f936352014-08-05 14:04:04 +10007042/* AC 3.5: funny apple logic */
Antoine Pitroub7572f02009-12-02 20:46:48 +00007043static PyObject *
7044posix_initgroups(PyObject *self, PyObject *args)
7045{
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007046 PyObject *oname;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03007047 const char *username;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007048 int res;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007049#ifdef __APPLE__
7050 int gid;
7051#else
7052 gid_t gid;
7053#endif
Antoine Pitroub7572f02009-12-02 20:46:48 +00007054
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007055#ifdef __APPLE__
7056 if (!PyArg_ParseTuple(args, "O&i:initgroups",
7057 PyUnicode_FSConverter, &oname,
7058 &gid))
7059#else
7060 if (!PyArg_ParseTuple(args, "O&O&:initgroups",
7061 PyUnicode_FSConverter, &oname,
7062 _Py_Gid_Converter, &gid))
7063#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00007064 return NULL;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007065 username = PyBytes_AS_STRING(oname);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007066
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007067 res = initgroups(username, gid);
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007068 Py_DECREF(oname);
7069 if (res == -1)
Victor Stinner8c62be82010-05-06 00:08:46 +00007070 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007071
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007072 Py_RETURN_NONE;
Antoine Pitroub7572f02009-12-02 20:46:48 +00007073}
Larry Hastings2f936352014-08-05 14:04:04 +10007074#endif /* HAVE_INITGROUPS */
7075
Antoine Pitroub7572f02009-12-02 20:46:48 +00007076
Martin v. Löwis606edc12002-06-13 21:09:11 +00007077#ifdef HAVE_GETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10007078/*[clinic input]
7079os.getpgid
7080
7081 pid: pid_t
7082
7083Call the system call getpgid(), and return the result.
7084[clinic start generated code]*/
7085
Larry Hastings2f936352014-08-05 14:04:04 +10007086static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007087os_getpgid_impl(PyObject *module, pid_t pid)
7088/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007089{
7090 pid_t pgid = getpgid(pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007091 if (pgid < 0)
7092 return posix_error();
7093 return PyLong_FromPid(pgid);
Martin v. Löwis606edc12002-06-13 21:09:11 +00007094}
7095#endif /* HAVE_GETPGID */
7096
7097
Guido van Rossumb6775db1994-08-01 11:34:53 +00007098#ifdef HAVE_GETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007099/*[clinic input]
7100os.getpgrp
7101
7102Return the current process group id.
7103[clinic start generated code]*/
7104
Larry Hastings2f936352014-08-05 14:04:04 +10007105static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007106os_getpgrp_impl(PyObject *module)
7107/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
Guido van Rossum04814471991-06-04 20:23:49 +00007108{
Guido van Rossumb6775db1994-08-01 11:34:53 +00007109#ifdef GETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007110 return PyLong_FromPid(getpgrp(0));
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007111#else /* GETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007112 return PyLong_FromPid(getpgrp());
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007113#endif /* GETPGRP_HAVE_ARG */
Guido van Rossum04814471991-06-04 20:23:49 +00007114}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007115#endif /* HAVE_GETPGRP */
Guido van Rossum04814471991-06-04 20:23:49 +00007116
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007117
Guido van Rossumb6775db1994-08-01 11:34:53 +00007118#ifdef HAVE_SETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007119/*[clinic input]
7120os.setpgrp
7121
7122Make the current process the leader of its process group.
7123[clinic start generated code]*/
7124
Larry Hastings2f936352014-08-05 14:04:04 +10007125static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007126os_setpgrp_impl(PyObject *module)
7127/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00007128{
Guido van Rossum64933891994-10-20 21:56:42 +00007129#ifdef SETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007130 if (setpgrp(0, 0) < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007131#else /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007132 if (setpgrp() < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007133#endif /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007134 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007135 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00007136}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007137#endif /* HAVE_SETPGRP */
7138
Guido van Rossumad0ee831995-03-01 10:34:45 +00007139#ifdef HAVE_GETPPID
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007140
7141#ifdef MS_WINDOWS
7142#include <tlhelp32.h>
7143
7144static PyObject*
7145win32_getppid()
7146{
7147 HANDLE snapshot;
7148 pid_t mypid;
7149 PyObject* result = NULL;
7150 BOOL have_record;
7151 PROCESSENTRY32 pe;
7152
7153 mypid = getpid(); /* This function never fails */
7154
7155 snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
7156 if (snapshot == INVALID_HANDLE_VALUE)
7157 return PyErr_SetFromWindowsErr(GetLastError());
7158
7159 pe.dwSize = sizeof(pe);
7160 have_record = Process32First(snapshot, &pe);
7161 while (have_record) {
7162 if (mypid == (pid_t)pe.th32ProcessID) {
7163 /* We could cache the ulong value in a static variable. */
7164 result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
7165 break;
7166 }
7167
7168 have_record = Process32Next(snapshot, &pe);
7169 }
7170
7171 /* If our loop exits and our pid was not found (result will be NULL)
7172 * then GetLastError will return ERROR_NO_MORE_FILES. This is an
7173 * error anyway, so let's raise it. */
7174 if (!result)
7175 result = PyErr_SetFromWindowsErr(GetLastError());
7176
7177 CloseHandle(snapshot);
7178
7179 return result;
7180}
7181#endif /*MS_WINDOWS*/
7182
Larry Hastings2f936352014-08-05 14:04:04 +10007183
7184/*[clinic input]
7185os.getppid
7186
7187Return the parent's process id.
7188
7189If the parent process has already exited, Windows machines will still
7190return its id; others systems will return the id of the 'init' process (1).
7191[clinic start generated code]*/
7192
Larry Hastings2f936352014-08-05 14:04:04 +10007193static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007194os_getppid_impl(PyObject *module)
7195/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00007196{
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007197#ifdef MS_WINDOWS
7198 return win32_getppid();
7199#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007200 return PyLong_FromPid(getppid());
Guido van Rossumad0ee831995-03-01 10:34:45 +00007201#endif
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007202}
7203#endif /* HAVE_GETPPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007204
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007205
Fred Drake12c6e2d1999-12-14 21:25:03 +00007206#ifdef HAVE_GETLOGIN
Larry Hastings2f936352014-08-05 14:04:04 +10007207/*[clinic input]
7208os.getlogin
7209
7210Return the actual login name.
7211[clinic start generated code]*/
7212
Larry Hastings2f936352014-08-05 14:04:04 +10007213static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007214os_getlogin_impl(PyObject *module)
7215/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
Fred Drake12c6e2d1999-12-14 21:25:03 +00007216{
Victor Stinner8c62be82010-05-06 00:08:46 +00007217 PyObject *result = NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007218#ifdef MS_WINDOWS
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007219 wchar_t user_name[UNLEN + 1];
Victor Stinner63941882011-09-29 00:42:28 +02007220 DWORD num_chars = Py_ARRAY_LENGTH(user_name);
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007221
7222 if (GetUserNameW(user_name, &num_chars)) {
7223 /* num_chars is the number of unicode chars plus null terminator */
7224 result = PyUnicode_FromWideChar(user_name, num_chars - 1);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007225 }
7226 else
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007227 result = PyErr_SetFromWindowsErr(GetLastError());
7228#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007229 char *name;
7230 int old_errno = errno;
Fred Drake12c6e2d1999-12-14 21:25:03 +00007231
Victor Stinner8c62be82010-05-06 00:08:46 +00007232 errno = 0;
7233 name = getlogin();
7234 if (name == NULL) {
7235 if (errno)
Victor Stinnere039ffe2010-08-15 09:33:08 +00007236 posix_error();
Fred Drake12c6e2d1999-12-14 21:25:03 +00007237 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007238 PyErr_SetString(PyExc_OSError, "unable to determine login name");
Victor Stinner8c62be82010-05-06 00:08:46 +00007239 }
7240 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007241 result = PyUnicode_DecodeFSDefault(name);
Victor Stinner8c62be82010-05-06 00:08:46 +00007242 errno = old_errno;
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007243#endif
Fred Drake12c6e2d1999-12-14 21:25:03 +00007244 return result;
7245}
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007246#endif /* HAVE_GETLOGIN */
Fred Drake12c6e2d1999-12-14 21:25:03 +00007247
Larry Hastings2f936352014-08-05 14:04:04 +10007248
Guido van Rossumad0ee831995-03-01 10:34:45 +00007249#ifdef HAVE_GETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007250/*[clinic input]
7251os.getuid
7252
7253Return the current process's user id.
7254[clinic start generated code]*/
7255
Larry Hastings2f936352014-08-05 14:04:04 +10007256static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007257os_getuid_impl(PyObject *module)
7258/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00007259{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007260 return _PyLong_FromUid(getuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00007261}
Larry Hastings2f936352014-08-05 14:04:04 +10007262#endif /* HAVE_GETUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00007263
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007264
Brian Curtineb24d742010-04-12 17:16:38 +00007265#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007266#define HAVE_KILL
7267#endif /* MS_WINDOWS */
7268
7269#ifdef HAVE_KILL
7270/*[clinic input]
7271os.kill
7272
7273 pid: pid_t
7274 signal: Py_ssize_t
7275 /
7276
7277Kill a process with a signal.
7278[clinic start generated code]*/
7279
Larry Hastings2f936352014-08-05 14:04:04 +10007280static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007281os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
7282/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007283#ifndef MS_WINDOWS
7284{
7285 if (kill(pid, (int)signal) == -1)
7286 return posix_error();
7287 Py_RETURN_NONE;
7288}
7289#else /* !MS_WINDOWS */
Brian Curtineb24d742010-04-12 17:16:38 +00007290{
Amaury Forgeot d'Arc0a589c92010-05-15 20:35:12 +00007291 PyObject *result;
Larry Hastings2f936352014-08-05 14:04:04 +10007292 DWORD sig = (DWORD)signal;
7293 DWORD err;
Victor Stinner8c62be82010-05-06 00:08:46 +00007294 HANDLE handle;
Brian Curtineb24d742010-04-12 17:16:38 +00007295
Victor Stinner8c62be82010-05-06 00:08:46 +00007296 /* Console processes which share a common console can be sent CTRL+C or
7297 CTRL+BREAK events, provided they handle said events. */
7298 if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007299 if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007300 err = GetLastError();
7301 PyErr_SetFromWindowsErr(err);
7302 }
7303 else
7304 Py_RETURN_NONE;
7305 }
Brian Curtineb24d742010-04-12 17:16:38 +00007306
Victor Stinner8c62be82010-05-06 00:08:46 +00007307 /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
7308 attempt to open and terminate the process. */
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007309 handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007310 if (handle == NULL) {
7311 err = GetLastError();
7312 return PyErr_SetFromWindowsErr(err);
7313 }
Brian Curtineb24d742010-04-12 17:16:38 +00007314
Victor Stinner8c62be82010-05-06 00:08:46 +00007315 if (TerminateProcess(handle, sig) == 0) {
7316 err = GetLastError();
7317 result = PyErr_SetFromWindowsErr(err);
7318 } else {
7319 Py_INCREF(Py_None);
7320 result = Py_None;
7321 }
Brian Curtineb24d742010-04-12 17:16:38 +00007322
Victor Stinner8c62be82010-05-06 00:08:46 +00007323 CloseHandle(handle);
7324 return result;
Brian Curtineb24d742010-04-12 17:16:38 +00007325}
Larry Hastings2f936352014-08-05 14:04:04 +10007326#endif /* !MS_WINDOWS */
7327#endif /* HAVE_KILL */
7328
7329
7330#ifdef HAVE_KILLPG
7331/*[clinic input]
7332os.killpg
7333
7334 pgid: pid_t
7335 signal: int
7336 /
7337
7338Kill a process group with a signal.
7339[clinic start generated code]*/
7340
Larry Hastings2f936352014-08-05 14:04:04 +10007341static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007342os_killpg_impl(PyObject *module, pid_t pgid, int signal)
7343/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007344{
7345 /* XXX some man pages make the `pgid` parameter an int, others
7346 a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
7347 take the same type. Moreover, pid_t is always at least as wide as
7348 int (else compilation of this module fails), which is safe. */
7349 if (killpg(pgid, signal) == -1)
7350 return posix_error();
7351 Py_RETURN_NONE;
7352}
7353#endif /* HAVE_KILLPG */
7354
Brian Curtineb24d742010-04-12 17:16:38 +00007355
Guido van Rossumc0125471996-06-28 18:55:32 +00007356#ifdef HAVE_PLOCK
Guido van Rossumc0125471996-06-28 18:55:32 +00007357#ifdef HAVE_SYS_LOCK_H
7358#include <sys/lock.h>
7359#endif
7360
Larry Hastings2f936352014-08-05 14:04:04 +10007361/*[clinic input]
7362os.plock
7363 op: int
7364 /
7365
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007366Lock program segments into memory.");
Larry Hastings2f936352014-08-05 14:04:04 +10007367[clinic start generated code]*/
7368
Larry Hastings2f936352014-08-05 14:04:04 +10007369static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007370os_plock_impl(PyObject *module, int op)
7371/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007372{
Victor Stinner8c62be82010-05-06 00:08:46 +00007373 if (plock(op) == -1)
7374 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007375 Py_RETURN_NONE;
Guido van Rossumc0125471996-06-28 18:55:32 +00007376}
Larry Hastings2f936352014-08-05 14:04:04 +10007377#endif /* HAVE_PLOCK */
7378
Guido van Rossumc0125471996-06-28 18:55:32 +00007379
Guido van Rossumb6775db1994-08-01 11:34:53 +00007380#ifdef HAVE_SETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007381/*[clinic input]
7382os.setuid
7383
7384 uid: uid_t
7385 /
7386
7387Set the current process's user id.
7388[clinic start generated code]*/
7389
Larry Hastings2f936352014-08-05 14:04:04 +10007390static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007391os_setuid_impl(PyObject *module, uid_t uid)
7392/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007393{
Victor Stinner8c62be82010-05-06 00:08:46 +00007394 if (setuid(uid) < 0)
7395 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007396 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007397}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007398#endif /* HAVE_SETUID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007399
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007400
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007401#ifdef HAVE_SETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10007402/*[clinic input]
7403os.seteuid
7404
7405 euid: uid_t
7406 /
7407
7408Set the current process's effective user id.
7409[clinic start generated code]*/
7410
Larry Hastings2f936352014-08-05 14:04:04 +10007411static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007412os_seteuid_impl(PyObject *module, uid_t euid)
7413/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007414{
7415 if (seteuid(euid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007416 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007417 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007418}
7419#endif /* HAVE_SETEUID */
7420
Larry Hastings2f936352014-08-05 14:04:04 +10007421
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007422#ifdef HAVE_SETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10007423/*[clinic input]
7424os.setegid
7425
7426 egid: gid_t
7427 /
7428
7429Set the current process's effective group id.
7430[clinic start generated code]*/
7431
Larry Hastings2f936352014-08-05 14:04:04 +10007432static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007433os_setegid_impl(PyObject *module, gid_t egid)
7434/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007435{
7436 if (setegid(egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007437 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007438 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007439}
7440#endif /* HAVE_SETEGID */
7441
Larry Hastings2f936352014-08-05 14:04:04 +10007442
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007443#ifdef HAVE_SETREUID
Larry Hastings2f936352014-08-05 14:04:04 +10007444/*[clinic input]
7445os.setreuid
7446
7447 ruid: uid_t
7448 euid: uid_t
7449 /
7450
7451Set the current process's real and effective user ids.
7452[clinic start generated code]*/
7453
Larry Hastings2f936352014-08-05 14:04:04 +10007454static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007455os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
7456/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007457{
Victor Stinner8c62be82010-05-06 00:08:46 +00007458 if (setreuid(ruid, euid) < 0) {
7459 return posix_error();
7460 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007461 Py_RETURN_NONE;
Victor Stinner8c62be82010-05-06 00:08:46 +00007462 }
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007463}
7464#endif /* HAVE_SETREUID */
7465
Larry Hastings2f936352014-08-05 14:04:04 +10007466
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007467#ifdef HAVE_SETREGID
Larry Hastings2f936352014-08-05 14:04:04 +10007468/*[clinic input]
7469os.setregid
7470
7471 rgid: gid_t
7472 egid: gid_t
7473 /
7474
7475Set the current process's real and effective group ids.
7476[clinic start generated code]*/
7477
Larry Hastings2f936352014-08-05 14:04:04 +10007478static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007479os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
7480/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007481{
7482 if (setregid(rgid, egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007483 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007484 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007485}
7486#endif /* HAVE_SETREGID */
7487
Larry Hastings2f936352014-08-05 14:04:04 +10007488
Guido van Rossumb6775db1994-08-01 11:34:53 +00007489#ifdef HAVE_SETGID
Larry Hastings2f936352014-08-05 14:04:04 +10007490/*[clinic input]
7491os.setgid
7492 gid: gid_t
7493 /
7494
7495Set the current process's group id.
7496[clinic start generated code]*/
7497
Larry Hastings2f936352014-08-05 14:04:04 +10007498static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007499os_setgid_impl(PyObject *module, gid_t gid)
7500/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007501{
Victor Stinner8c62be82010-05-06 00:08:46 +00007502 if (setgid(gid) < 0)
7503 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007504 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007505}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007506#endif /* HAVE_SETGID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007507
Larry Hastings2f936352014-08-05 14:04:04 +10007508
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007509#ifdef HAVE_SETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007510/*[clinic input]
7511os.setgroups
7512
7513 groups: object
7514 /
7515
7516Set the groups of the current process to list.
7517[clinic start generated code]*/
7518
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007519static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007520os_setgroups(PyObject *module, PyObject *groups)
7521/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007522{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007523 Py_ssize_t i, len;
Victor Stinner8c62be82010-05-06 00:08:46 +00007524 gid_t grouplist[MAX_GROUPS];
Tim Peters5aa91602002-01-30 05:46:57 +00007525
Victor Stinner8c62be82010-05-06 00:08:46 +00007526 if (!PySequence_Check(groups)) {
7527 PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
7528 return NULL;
7529 }
7530 len = PySequence_Size(groups);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007531 if (len < 0) {
7532 return NULL;
7533 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007534 if (len > MAX_GROUPS) {
7535 PyErr_SetString(PyExc_ValueError, "too many groups");
7536 return NULL;
7537 }
7538 for(i = 0; i < len; i++) {
7539 PyObject *elem;
7540 elem = PySequence_GetItem(groups, i);
7541 if (!elem)
7542 return NULL;
7543 if (!PyLong_Check(elem)) {
7544 PyErr_SetString(PyExc_TypeError,
7545 "groups must be integers");
7546 Py_DECREF(elem);
7547 return NULL;
7548 } else {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007549 if (!_Py_Gid_Converter(elem, &grouplist[i])) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007550 Py_DECREF(elem);
7551 return NULL;
7552 }
7553 }
7554 Py_DECREF(elem);
7555 }
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007556
Victor Stinner8c62be82010-05-06 00:08:46 +00007557 if (setgroups(len, grouplist) < 0)
7558 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007559 Py_RETURN_NONE;
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007560}
7561#endif /* HAVE_SETGROUPS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007562
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007563#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
7564static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +01007565wait_helper(pid_t pid, int status, struct rusage *ru)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007566{
Victor Stinner8c62be82010-05-06 00:08:46 +00007567 PyObject *result;
Eddie Elizondob3966632019-11-05 07:16:14 -08007568 PyObject *struct_rusage;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007569
Victor Stinner8c62be82010-05-06 00:08:46 +00007570 if (pid == -1)
7571 return posix_error();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007572
Zackery Spytz682107c2019-09-09 09:48:32 -06007573 // If wait succeeded but no child was ready to report status, ru will not
7574 // have been populated.
7575 if (pid == 0) {
7576 memset(ru, 0, sizeof(*ru));
7577 }
7578
Eddie Elizondob3966632019-11-05 07:16:14 -08007579 PyObject *m = PyImport_ImportModuleNoBlock("resource");
7580 if (m == NULL)
7581 return NULL;
7582 struct_rusage = PyObject_GetAttr(m, _posixstate_global->struct_rusage);
7583 Py_DECREF(m);
7584 if (struct_rusage == NULL)
7585 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007586
Victor Stinner8c62be82010-05-06 00:08:46 +00007587 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
7588 result = PyStructSequence_New((PyTypeObject*) struct_rusage);
Eddie Elizondoe4db1f02019-11-25 19:07:37 -08007589 Py_DECREF(struct_rusage);
Victor Stinner8c62be82010-05-06 00:08:46 +00007590 if (!result)
7591 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007592
7593#ifndef doubletime
7594#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
7595#endif
7596
Victor Stinner8c62be82010-05-06 00:08:46 +00007597 PyStructSequence_SET_ITEM(result, 0,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007598 PyFloat_FromDouble(doubletime(ru->ru_utime)));
Victor Stinner8c62be82010-05-06 00:08:46 +00007599 PyStructSequence_SET_ITEM(result, 1,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007600 PyFloat_FromDouble(doubletime(ru->ru_stime)));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007601#define SET_INT(result, index, value)\
Victor Stinner8c62be82010-05-06 00:08:46 +00007602 PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
7603 SET_INT(result, 2, ru->ru_maxrss);
7604 SET_INT(result, 3, ru->ru_ixrss);
7605 SET_INT(result, 4, ru->ru_idrss);
7606 SET_INT(result, 5, ru->ru_isrss);
7607 SET_INT(result, 6, ru->ru_minflt);
7608 SET_INT(result, 7, ru->ru_majflt);
7609 SET_INT(result, 8, ru->ru_nswap);
7610 SET_INT(result, 9, ru->ru_inblock);
7611 SET_INT(result, 10, ru->ru_oublock);
7612 SET_INT(result, 11, ru->ru_msgsnd);
7613 SET_INT(result, 12, ru->ru_msgrcv);
7614 SET_INT(result, 13, ru->ru_nsignals);
7615 SET_INT(result, 14, ru->ru_nvcsw);
7616 SET_INT(result, 15, ru->ru_nivcsw);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007617#undef SET_INT
7618
Victor Stinner8c62be82010-05-06 00:08:46 +00007619 if (PyErr_Occurred()) {
7620 Py_DECREF(result);
7621 return NULL;
7622 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007623
Victor Stinner8c62be82010-05-06 00:08:46 +00007624 return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007625}
7626#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
7627
Larry Hastings2f936352014-08-05 14:04:04 +10007628
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007629#ifdef HAVE_WAIT3
Larry Hastings2f936352014-08-05 14:04:04 +10007630/*[clinic input]
7631os.wait3
7632
7633 options: int
7634Wait for completion of a child process.
7635
7636Returns a tuple of information about the child process:
7637 (pid, status, rusage)
7638[clinic start generated code]*/
7639
Larry Hastings2f936352014-08-05 14:04:04 +10007640static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007641os_wait3_impl(PyObject *module, int options)
7642/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007643{
Victor Stinner8c62be82010-05-06 00:08:46 +00007644 pid_t pid;
Victor Stinner8c62be82010-05-06 00:08:46 +00007645 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007646 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007647 WAIT_TYPE status;
7648 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007649
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007650 do {
7651 Py_BEGIN_ALLOW_THREADS
7652 pid = wait3(&status, options, &ru);
7653 Py_END_ALLOW_THREADS
7654 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7655 if (pid < 0)
7656 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007657
Victor Stinner4195b5c2012-02-08 23:03:19 +01007658 return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007659}
7660#endif /* HAVE_WAIT3 */
7661
Larry Hastings2f936352014-08-05 14:04:04 +10007662
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007663#ifdef HAVE_WAIT4
Larry Hastings2f936352014-08-05 14:04:04 +10007664/*[clinic input]
7665
7666os.wait4
7667
7668 pid: pid_t
7669 options: int
7670
7671Wait for completion of a specific child process.
7672
7673Returns a tuple of information about the child process:
7674 (pid, status, rusage)
7675[clinic start generated code]*/
7676
Larry Hastings2f936352014-08-05 14:04:04 +10007677static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007678os_wait4_impl(PyObject *module, pid_t pid, int options)
7679/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007680{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007681 pid_t res;
Victor Stinner8c62be82010-05-06 00:08:46 +00007682 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007683 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007684 WAIT_TYPE status;
7685 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007686
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007687 do {
7688 Py_BEGIN_ALLOW_THREADS
7689 res = wait4(pid, &status, options, &ru);
7690 Py_END_ALLOW_THREADS
7691 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7692 if (res < 0)
7693 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007694
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007695 return wait_helper(res, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007696}
7697#endif /* HAVE_WAIT4 */
7698
Larry Hastings2f936352014-08-05 14:04:04 +10007699
Ross Lagerwall7807c352011-03-17 20:20:30 +02007700#if defined(HAVE_WAITID) && !defined(__APPLE__)
Larry Hastings2f936352014-08-05 14:04:04 +10007701/*[clinic input]
7702os.waitid
7703
7704 idtype: idtype_t
7705 Must be one of be P_PID, P_PGID or P_ALL.
7706 id: id_t
7707 The id to wait on.
7708 options: int
7709 Constructed from the ORing of one or more of WEXITED, WSTOPPED
7710 or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
7711 /
7712
7713Returns the result of waiting for a process or processes.
7714
7715Returns either waitid_result or None if WNOHANG is specified and there are
7716no children in a waitable state.
7717[clinic start generated code]*/
7718
Larry Hastings2f936352014-08-05 14:04:04 +10007719static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007720os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
7721/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007722{
7723 PyObject *result;
7724 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007725 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007726 siginfo_t si;
7727 si.si_pid = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007728
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007729 do {
7730 Py_BEGIN_ALLOW_THREADS
7731 res = waitid(idtype, id, &si, options);
7732 Py_END_ALLOW_THREADS
7733 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7734 if (res < 0)
7735 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007736
7737 if (si.si_pid == 0)
7738 Py_RETURN_NONE;
7739
Eddie Elizondob3966632019-11-05 07:16:14 -08007740 PyObject *WaitidResultType = _posixstate(module)->WaitidResultType;
7741 result = PyStructSequence_New((PyTypeObject *)WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +02007742 if (!result)
7743 return NULL;
7744
7745 PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007746 PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
Ross Lagerwall7807c352011-03-17 20:20:30 +02007747 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
7748 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
7749 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
7750 if (PyErr_Occurred()) {
7751 Py_DECREF(result);
7752 return NULL;
7753 }
7754
7755 return result;
7756}
Larry Hastings2f936352014-08-05 14:04:04 +10007757#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
Ross Lagerwall7807c352011-03-17 20:20:30 +02007758
Larry Hastings2f936352014-08-05 14:04:04 +10007759
7760#if defined(HAVE_WAITPID)
7761/*[clinic input]
7762os.waitpid
7763 pid: pid_t
7764 options: int
7765 /
7766
7767Wait for completion of a given child process.
7768
7769Returns a tuple of information regarding the child process:
7770 (pid, status)
7771
7772The options argument is ignored on Windows.
7773[clinic start generated code]*/
7774
Larry Hastings2f936352014-08-05 14:04:04 +10007775static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007776os_waitpid_impl(PyObject *module, pid_t pid, int options)
7777/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007778{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007779 pid_t res;
7780 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007781 WAIT_TYPE status;
7782 WAIT_STATUS_INT(status) = 0;
Guido van Rossum54ecc3d1999-01-27 17:53:11 +00007783
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007784 do {
7785 Py_BEGIN_ALLOW_THREADS
7786 res = waitpid(pid, &status, options);
7787 Py_END_ALLOW_THREADS
7788 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7789 if (res < 0)
7790 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007791
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007792 return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
Guido van Rossum21803b81992-08-09 12:55:27 +00007793}
Tim Petersab034fa2002-02-01 11:27:43 +00007794#elif defined(HAVE_CWAIT)
Tim Petersab034fa2002-02-01 11:27:43 +00007795/* MS C has a variant of waitpid() that's usable for most purposes. */
Larry Hastings2f936352014-08-05 14:04:04 +10007796/*[clinic input]
7797os.waitpid
Benjamin Petersonca470632016-09-06 13:47:26 -07007798 pid: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +10007799 options: int
7800 /
7801
7802Wait for completion of a given process.
7803
7804Returns a tuple of information regarding the process:
7805 (pid, status << 8)
7806
7807The options argument is ignored on Windows.
7808[clinic start generated code]*/
7809
Larry Hastings2f936352014-08-05 14:04:04 +10007810static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -07007811os_waitpid_impl(PyObject *module, intptr_t pid, int options)
Victor Stinner581139c2016-09-06 15:54:20 -07007812/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007813{
7814 int status;
Benjamin Petersonca470632016-09-06 13:47:26 -07007815 intptr_t res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007816 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007817
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007818 do {
7819 Py_BEGIN_ALLOW_THREADS
Steve Dower11f43262016-11-19 18:33:39 -08007820 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007821 res = _cwait(&status, pid, options);
Steve Dower11f43262016-11-19 18:33:39 -08007822 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007823 Py_END_ALLOW_THREADS
7824 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinnerd3ffd322015-09-15 10:11:03 +02007825 if (res < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007826 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007827
Victor Stinner8c62be82010-05-06 00:08:46 +00007828 /* shift the status left a byte so this is more like the POSIX waitpid */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007829 return Py_BuildValue(_Py_PARSE_INTPTR "i", res, status << 8);
Tim Petersab034fa2002-02-01 11:27:43 +00007830}
Larry Hastings2f936352014-08-05 14:04:04 +10007831#endif
7832
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007833
Guido van Rossumad0ee831995-03-01 10:34:45 +00007834#ifdef HAVE_WAIT
Larry Hastings2f936352014-08-05 14:04:04 +10007835/*[clinic input]
7836os.wait
7837
7838Wait for completion of a child process.
7839
7840Returns a tuple of information about the child process:
7841 (pid, status)
7842[clinic start generated code]*/
7843
Larry Hastings2f936352014-08-05 14:04:04 +10007844static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007845os_wait_impl(PyObject *module)
7846/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
Guido van Rossum21803b81992-08-09 12:55:27 +00007847{
Victor Stinner8c62be82010-05-06 00:08:46 +00007848 pid_t pid;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007849 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007850 WAIT_TYPE status;
7851 WAIT_STATUS_INT(status) = 0;
Neal Norwitze241ce82003-02-17 18:17:05 +00007852
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007853 do {
7854 Py_BEGIN_ALLOW_THREADS
7855 pid = wait(&status);
7856 Py_END_ALLOW_THREADS
7857 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7858 if (pid < 0)
7859 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007860
Victor Stinner8c62be82010-05-06 00:08:46 +00007861 return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
Guido van Rossum85e3b011991-06-03 12:42:10 +00007862}
Larry Hastings2f936352014-08-05 14:04:04 +10007863#endif /* HAVE_WAIT */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007864
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -08007865#if defined(__linux__) && defined(__NR_pidfd_open)
7866/*[clinic input]
7867os.pidfd_open
7868 pid: pid_t
7869 flags: unsigned_int = 0
7870
7871Return a file descriptor referring to the process *pid*.
7872
7873The descriptor can be used to perform process management without races and
7874signals.
7875[clinic start generated code]*/
7876
7877static PyObject *
7878os_pidfd_open_impl(PyObject *module, pid_t pid, unsigned int flags)
7879/*[clinic end generated code: output=5c7252698947dc41 input=c3fd99ce947ccfef]*/
7880{
7881 int fd = syscall(__NR_pidfd_open, pid, flags);
7882 if (fd < 0) {
7883 return posix_error();
7884 }
7885 return PyLong_FromLong(fd);
7886}
7887#endif
7888
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007889
Larry Hastings9cf065c2012-06-22 16:30:09 -07007890#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007891/*[clinic input]
7892os.readlink
7893
7894 path: path_t
7895 *
7896 dir_fd: dir_fd(requires='readlinkat') = None
7897
7898Return a string representing the path to which the symbolic link points.
7899
7900If dir_fd is not None, it should be a file descriptor open to a directory,
7901and path should be relative; path will then be relative to that directory.
7902
7903dir_fd may not be implemented on your platform. If it is unavailable,
7904using it will raise a NotImplementedError.
7905[clinic start generated code]*/
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007906
Barry Warsaw53699e91996-12-10 23:23:01 +00007907static PyObject *
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007908os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
7909/*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00007910{
Berker Peksage0b5b202018-08-15 13:03:41 +03007911#if defined(HAVE_READLINK)
Christian Heimes3cb091e2016-09-23 20:24:28 +02007912 char buffer[MAXPATHLEN+1];
Larry Hastings9cf065c2012-06-22 16:30:09 -07007913 ssize_t length;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007914
7915 Py_BEGIN_ALLOW_THREADS
7916#ifdef HAVE_READLINKAT
7917 if (dir_fd != DEFAULT_DIR_FD)
7918 length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
7919 else
7920#endif
7921 length = readlink(path->narrow, buffer, MAXPATHLEN);
7922 Py_END_ALLOW_THREADS
7923
7924 if (length < 0) {
7925 return path_error(path);
7926 }
7927 buffer[length] = '\0';
7928
7929 if (PyUnicode_Check(path->object))
7930 return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
7931 else
7932 return PyBytes_FromStringAndSize(buffer, length);
Berker Peksage0b5b202018-08-15 13:03:41 +03007933#elif defined(MS_WINDOWS)
7934 DWORD n_bytes_returned;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007935 DWORD io_result = 0;
Berker Peksage0b5b202018-08-15 13:03:41 +03007936 HANDLE reparse_point_handle;
Berker Peksage0b5b202018-08-15 13:03:41 +03007937 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
7938 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Steve Dower993ac922019-09-03 12:50:51 -07007939 PyObject *result = NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00007940
Larry Hastings2f936352014-08-05 14:04:04 +10007941 /* First get a handle to the reparse point */
7942 Py_BEGIN_ALLOW_THREADS
7943 reparse_point_handle = CreateFileW(
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007944 path->wide,
Larry Hastings2f936352014-08-05 14:04:04 +10007945 0,
7946 0,
7947 0,
7948 OPEN_EXISTING,
7949 FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
7950 0);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007951 if (reparse_point_handle != INVALID_HANDLE_VALUE) {
7952 /* New call DeviceIoControl to read the reparse point */
7953 io_result = DeviceIoControl(
7954 reparse_point_handle,
7955 FSCTL_GET_REPARSE_POINT,
7956 0, 0, /* in buffer */
7957 target_buffer, sizeof(target_buffer),
7958 &n_bytes_returned,
7959 0 /* we're not using OVERLAPPED_IO */
7960 );
7961 CloseHandle(reparse_point_handle);
Berker Peksage0b5b202018-08-15 13:03:41 +03007962 }
Larry Hastings2f936352014-08-05 14:04:04 +10007963 Py_END_ALLOW_THREADS
7964
Berker Peksage0b5b202018-08-15 13:03:41 +03007965 if (io_result == 0) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007966 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03007967 }
Larry Hastings2f936352014-08-05 14:04:04 +10007968
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007969 wchar_t *name = NULL;
7970 Py_ssize_t nameLen = 0;
7971 if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
Larry Hastings2f936352014-08-05 14:04:04 +10007972 {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007973 name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
7974 rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
7975 nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
Larry Hastings2f936352014-08-05 14:04:04 +10007976 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007977 else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
7978 {
7979 name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
7980 rdb->MountPointReparseBuffer.SubstituteNameOffset);
7981 nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
7982 }
7983 else
7984 {
7985 PyErr_SetString(PyExc_ValueError, "not a symbolic link");
7986 }
7987 if (name) {
7988 if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
7989 /* Our buffer is mutable, so this is okay */
7990 name[1] = L'\\';
7991 }
7992 result = PyUnicode_FromWideChar(name, nameLen);
Steve Dower993ac922019-09-03 12:50:51 -07007993 if (result && path->narrow) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007994 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
7995 }
Berker Peksage0b5b202018-08-15 13:03:41 +03007996 }
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007997 return result;
Berker Peksage0b5b202018-08-15 13:03:41 +03007998#endif
Larry Hastings2f936352014-08-05 14:04:04 +10007999}
Berker Peksage0b5b202018-08-15 13:03:41 +03008000#endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008001
Larry Hastings9cf065c2012-06-22 16:30:09 -07008002#ifdef HAVE_SYMLINK
Larry Hastings9cf065c2012-06-22 16:30:09 -07008003
8004#if defined(MS_WINDOWS)
8005
Steve Dower6921e732018-03-05 14:26:08 -08008006/* Remove the last portion of the path - return 0 on success */
8007static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008008_dirnameW(WCHAR *path)
8009{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008010 WCHAR *ptr;
Steve Dower6921e732018-03-05 14:26:08 -08008011 size_t length = wcsnlen_s(path, MAX_PATH);
8012 if (length == MAX_PATH) {
8013 return -1;
8014 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008015
8016 /* walk the path from the end until a backslash is encountered */
Steve Dower6921e732018-03-05 14:26:08 -08008017 for(ptr = path + length; ptr != path; ptr--) {
8018 if (*ptr == L'\\' || *ptr == L'/') {
Jason R. Coombs3a092862013-05-27 23:21:28 -04008019 break;
Steve Dower6921e732018-03-05 14:26:08 -08008020 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008021 }
8022 *ptr = 0;
Steve Dower6921e732018-03-05 14:26:08 -08008023 return 0;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008024}
8025
Victor Stinner31b3b922013-06-05 01:49:17 +02008026/* Is this path absolute? */
8027static int
8028_is_absW(const WCHAR *path)
8029{
Steve Dower6921e732018-03-05 14:26:08 -08008030 return path[0] == L'\\' || path[0] == L'/' ||
8031 (path[0] && path[1] == L':');
Jason R. Coombs3a092862013-05-27 23:21:28 -04008032}
8033
Steve Dower6921e732018-03-05 14:26:08 -08008034/* join root and rest with a backslash - return 0 on success */
8035static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008036_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
8037{
Victor Stinner31b3b922013-06-05 01:49:17 +02008038 if (_is_absW(rest)) {
Steve Dower6921e732018-03-05 14:26:08 -08008039 return wcscpy_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008040 }
8041
Steve Dower6921e732018-03-05 14:26:08 -08008042 if (wcscpy_s(dest_path, MAX_PATH, root)) {
8043 return -1;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008044 }
Steve Dower6921e732018-03-05 14:26:08 -08008045
8046 if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
8047 return -1;
8048 }
8049
8050 return wcscat_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008051}
8052
Victor Stinner31b3b922013-06-05 01:49:17 +02008053/* Return True if the path at src relative to dest is a directory */
8054static int
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03008055_check_dirW(LPCWSTR src, LPCWSTR dest)
Jason R. Coombs3a092862013-05-27 23:21:28 -04008056{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008057 WIN32_FILE_ATTRIBUTE_DATA src_info;
8058 WCHAR dest_parent[MAX_PATH];
8059 WCHAR src_resolved[MAX_PATH] = L"";
8060
8061 /* dest_parent = os.path.dirname(dest) */
Steve Dower6921e732018-03-05 14:26:08 -08008062 if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
8063 _dirnameW(dest_parent)) {
8064 return 0;
8065 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008066 /* src_resolved = os.path.join(dest_parent, src) */
Steve Dower6921e732018-03-05 14:26:08 -08008067 if (_joinW(src_resolved, dest_parent, src)) {
8068 return 0;
8069 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008070 return (
8071 GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
8072 && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
8073 );
8074}
Larry Hastings9cf065c2012-06-22 16:30:09 -07008075#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008076
Larry Hastings2f936352014-08-05 14:04:04 +10008077
8078/*[clinic input]
8079os.symlink
8080 src: path_t
8081 dst: path_t
8082 target_is_directory: bool = False
8083 *
8084 dir_fd: dir_fd(requires='symlinkat')=None
8085
8086# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
8087
8088Create a symbolic link pointing to src named dst.
8089
8090target_is_directory is required on Windows if the target is to be
8091 interpreted as a directory. (On Windows, symlink requires
8092 Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
8093 target_is_directory is ignored on non-Windows platforms.
8094
8095If dir_fd is not None, it should be a file descriptor open to a directory,
8096 and path should be relative; path will then be relative to that directory.
8097dir_fd may not be implemented on your platform.
8098 If it is unavailable, using it will raise a NotImplementedError.
8099
8100[clinic start generated code]*/
8101
Larry Hastings2f936352014-08-05 14:04:04 +10008102static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008103os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
Larry Hastings89964c42015-04-14 18:07:59 -04008104 int target_is_directory, int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008105/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008106{
Larry Hastings9cf065c2012-06-22 16:30:09 -07008107#ifdef MS_WINDOWS
8108 DWORD result;
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008109 DWORD flags = 0;
8110
8111 /* Assumed true, set to false if detected to not be available. */
8112 static int windows_has_symlink_unprivileged_flag = TRUE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008113#else
8114 int result;
8115#endif
8116
Larry Hastings9cf065c2012-06-22 16:30:09 -07008117#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008118
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008119 if (windows_has_symlink_unprivileged_flag) {
8120 /* Allow non-admin symlinks if system allows it. */
8121 flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
8122 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008123
Larry Hastings9cf065c2012-06-22 16:30:09 -07008124 Py_BEGIN_ALLOW_THREADS
Steve Dower6921e732018-03-05 14:26:08 -08008125 _Py_BEGIN_SUPPRESS_IPH
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008126 /* if src is a directory, ensure flags==1 (target_is_directory bit) */
8127 if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
8128 flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
8129 }
8130
8131 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
Steve Dower6921e732018-03-05 14:26:08 -08008132 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07008133 Py_END_ALLOW_THREADS
8134
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008135 if (windows_has_symlink_unprivileged_flag && !result &&
8136 ERROR_INVALID_PARAMETER == GetLastError()) {
8137
8138 Py_BEGIN_ALLOW_THREADS
8139 _Py_BEGIN_SUPPRESS_IPH
8140 /* This error might be caused by
8141 SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
8142 Try again, and update windows_has_symlink_unprivileged_flag if we
8143 are successful this time.
8144
8145 NOTE: There is a risk of a race condition here if there are other
8146 conditions than the flag causing ERROR_INVALID_PARAMETER, and
8147 another process (or thread) changes that condition in between our
8148 calls to CreateSymbolicLink.
8149 */
8150 flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
8151 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
8152 _Py_END_SUPPRESS_IPH
8153 Py_END_ALLOW_THREADS
8154
8155 if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
8156 windows_has_symlink_unprivileged_flag = FALSE;
8157 }
8158 }
8159
Larry Hastings2f936352014-08-05 14:04:04 +10008160 if (!result)
8161 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008162
8163#else
8164
Steve Dower6921e732018-03-05 14:26:08 -08008165 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
8166 PyErr_SetString(PyExc_ValueError,
8167 "symlink: src and dst must be the same type");
8168 return NULL;
8169 }
8170
Larry Hastings9cf065c2012-06-22 16:30:09 -07008171 Py_BEGIN_ALLOW_THREADS
8172#if HAVE_SYMLINKAT
8173 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10008174 result = symlinkat(src->narrow, dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008175 else
8176#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008177 result = symlink(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008178 Py_END_ALLOW_THREADS
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#endif
8183
Larry Hastings2f936352014-08-05 14:04:04 +10008184 Py_RETURN_NONE;
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008185}
8186#endif /* HAVE_SYMLINK */
8187
Larry Hastings9cf065c2012-06-22 16:30:09 -07008188
Brian Curtind40e6f72010-07-08 21:39:08 +00008189
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008190
Larry Hastings605a62d2012-06-24 04:33:36 -07008191static PyStructSequence_Field times_result_fields[] = {
8192 {"user", "user time"},
8193 {"system", "system time"},
8194 {"children_user", "user time of children"},
8195 {"children_system", "system time of children"},
8196 {"elapsed", "elapsed time since an arbitrary point in the past"},
8197 {NULL}
8198};
8199
8200PyDoc_STRVAR(times_result__doc__,
8201"times_result: Result from os.times().\n\n\
8202This object may be accessed either as a tuple of\n\
8203 (user, system, children_user, children_system, elapsed),\n\
8204or via the attributes user, system, children_user, children_system,\n\
8205and elapsed.\n\
8206\n\
8207See os.times for more information.");
8208
8209static PyStructSequence_Desc times_result_desc = {
8210 "times_result", /* name */
8211 times_result__doc__, /* doc */
8212 times_result_fields,
8213 5
8214};
8215
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008216#ifdef MS_WINDOWS
8217#define HAVE_TIMES /* mandatory, for the method table */
8218#endif
Larry Hastings605a62d2012-06-24 04:33:36 -07008219
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008220#ifdef HAVE_TIMES
Larry Hastings605a62d2012-06-24 04:33:36 -07008221
8222static PyObject *
8223build_times_result(double user, double system,
8224 double children_user, double children_system,
8225 double elapsed)
8226{
Eddie Elizondob3966632019-11-05 07:16:14 -08008227 PyObject *TimesResultType = _posixstate_global->TimesResultType;
8228 PyObject *value = PyStructSequence_New((PyTypeObject *)TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07008229 if (value == NULL)
8230 return NULL;
8231
8232#define SET(i, field) \
8233 { \
8234 PyObject *o = PyFloat_FromDouble(field); \
8235 if (!o) { \
8236 Py_DECREF(value); \
8237 return NULL; \
8238 } \
8239 PyStructSequence_SET_ITEM(value, i, o); \
8240 } \
8241
8242 SET(0, user);
8243 SET(1, system);
8244 SET(2, children_user);
8245 SET(3, children_system);
8246 SET(4, elapsed);
8247
8248#undef SET
8249
8250 return value;
8251}
8252
Larry Hastings605a62d2012-06-24 04:33:36 -07008253
Larry Hastings2f936352014-08-05 14:04:04 +10008254#ifndef MS_WINDOWS
8255#define NEED_TICKS_PER_SECOND
8256static long ticks_per_second = -1;
8257#endif /* MS_WINDOWS */
8258
8259/*[clinic input]
8260os.times
8261
8262Return a collection containing process timing information.
8263
8264The object returned behaves like a named tuple with these fields:
8265 (utime, stime, cutime, cstime, elapsed_time)
8266All fields are floating point numbers.
8267[clinic start generated code]*/
8268
Larry Hastings2f936352014-08-05 14:04:04 +10008269static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008270os_times_impl(PyObject *module)
8271/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008272#ifdef MS_WINDOWS
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008273{
Victor Stinner8c62be82010-05-06 00:08:46 +00008274 FILETIME create, exit, kernel, user;
8275 HANDLE hProc;
8276 hProc = GetCurrentProcess();
8277 GetProcessTimes(hProc, &create, &exit, &kernel, &user);
8278 /* The fields of a FILETIME structure are the hi and lo part
8279 of a 64-bit value expressed in 100 nanosecond units.
8280 1e7 is one second in such units; 1e-7 the inverse.
8281 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
8282 */
Larry Hastings605a62d2012-06-24 04:33:36 -07008283 return build_times_result(
Victor Stinner8c62be82010-05-06 00:08:46 +00008284 (double)(user.dwHighDateTime*429.4967296 +
8285 user.dwLowDateTime*1e-7),
8286 (double)(kernel.dwHighDateTime*429.4967296 +
8287 kernel.dwLowDateTime*1e-7),
8288 (double)0,
8289 (double)0,
8290 (double)0);
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008291}
Larry Hastings2f936352014-08-05 14:04:04 +10008292#else /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008293{
Larry Hastings2f936352014-08-05 14:04:04 +10008294
8295
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008296 struct tms t;
8297 clock_t c;
8298 errno = 0;
8299 c = times(&t);
8300 if (c == (clock_t) -1)
8301 return posix_error();
8302 return build_times_result(
8303 (double)t.tms_utime / ticks_per_second,
8304 (double)t.tms_stime / ticks_per_second,
8305 (double)t.tms_cutime / ticks_per_second,
8306 (double)t.tms_cstime / ticks_per_second,
8307 (double)c / ticks_per_second);
8308}
Larry Hastings2f936352014-08-05 14:04:04 +10008309#endif /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008310#endif /* HAVE_TIMES */
8311
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008312
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008313#ifdef HAVE_GETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008314/*[clinic input]
8315os.getsid
8316
8317 pid: pid_t
8318 /
8319
8320Call the system call getsid(pid) and return the result.
8321[clinic start generated code]*/
8322
Larry Hastings2f936352014-08-05 14:04:04 +10008323static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008324os_getsid_impl(PyObject *module, pid_t pid)
8325/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008326{
Victor Stinner8c62be82010-05-06 00:08:46 +00008327 int sid;
Victor Stinner8c62be82010-05-06 00:08:46 +00008328 sid = getsid(pid);
8329 if (sid < 0)
8330 return posix_error();
8331 return PyLong_FromLong((long)sid);
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008332}
8333#endif /* HAVE_GETSID */
8334
8335
Guido van Rossumb6775db1994-08-01 11:34:53 +00008336#ifdef HAVE_SETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008337/*[clinic input]
8338os.setsid
8339
8340Call the system call setsid().
8341[clinic start generated code]*/
8342
Larry Hastings2f936352014-08-05 14:04:04 +10008343static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008344os_setsid_impl(PyObject *module)
8345/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00008346{
Victor Stinner8c62be82010-05-06 00:08:46 +00008347 if (setsid() < 0)
8348 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008349 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008350}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008351#endif /* HAVE_SETSID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008352
Larry Hastings2f936352014-08-05 14:04:04 +10008353
Guido van Rossumb6775db1994-08-01 11:34:53 +00008354#ifdef HAVE_SETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10008355/*[clinic input]
8356os.setpgid
8357
8358 pid: pid_t
8359 pgrp: pid_t
8360 /
8361
8362Call the system call setpgid(pid, pgrp).
8363[clinic start generated code]*/
8364
Larry Hastings2f936352014-08-05 14:04:04 +10008365static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008366os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
8367/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008368{
Victor Stinner8c62be82010-05-06 00:08:46 +00008369 if (setpgid(pid, pgrp) < 0)
8370 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008371 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008372}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008373#endif /* HAVE_SETPGID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008374
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008375
Guido van Rossumb6775db1994-08-01 11:34:53 +00008376#ifdef HAVE_TCGETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008377/*[clinic input]
8378os.tcgetpgrp
8379
8380 fd: int
8381 /
8382
8383Return the process group associated with the terminal specified by fd.
8384[clinic start generated code]*/
8385
Larry Hastings2f936352014-08-05 14:04:04 +10008386static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008387os_tcgetpgrp_impl(PyObject *module, int fd)
8388/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008389{
8390 pid_t pgid = tcgetpgrp(fd);
Victor Stinner8c62be82010-05-06 00:08:46 +00008391 if (pgid < 0)
8392 return posix_error();
8393 return PyLong_FromPid(pgid);
Guido van Rossum7066dd71992-09-17 17:54:56 +00008394}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008395#endif /* HAVE_TCGETPGRP */
Guido van Rossum7066dd71992-09-17 17:54:56 +00008396
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008397
Guido van Rossumb6775db1994-08-01 11:34:53 +00008398#ifdef HAVE_TCSETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008399/*[clinic input]
8400os.tcsetpgrp
8401
8402 fd: int
8403 pgid: pid_t
8404 /
8405
8406Set the process group associated with the terminal specified by fd.
8407[clinic start generated code]*/
8408
Larry Hastings2f936352014-08-05 14:04:04 +10008409static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008410os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
8411/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008412{
Victor Stinner8c62be82010-05-06 00:08:46 +00008413 if (tcsetpgrp(fd, pgid) < 0)
8414 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008415 Py_RETURN_NONE;
Guido van Rossum7066dd71992-09-17 17:54:56 +00008416}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008417#endif /* HAVE_TCSETPGRP */
Guido van Rossum22db57e1992-04-05 14:25:30 +00008418
Guido van Rossum687dd131993-05-17 08:34:16 +00008419/* Functions acting on file descriptors */
8420
Victor Stinnerdaf45552013-08-28 00:53:59 +02008421#ifdef O_CLOEXEC
8422extern int _Py_open_cloexec_works;
8423#endif
8424
Larry Hastings2f936352014-08-05 14:04:04 +10008425
8426/*[clinic input]
8427os.open -> int
8428 path: path_t
8429 flags: int
8430 mode: int = 0o777
8431 *
8432 dir_fd: dir_fd(requires='openat') = None
8433
8434# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
8435
8436Open a file for low level IO. Returns a file descriptor (integer).
8437
8438If dir_fd is not None, it should be a file descriptor open to a directory,
8439 and path should be relative; path will then be relative to that directory.
8440dir_fd may not be implemented on your platform.
8441 If it is unavailable, using it will raise a NotImplementedError.
8442[clinic start generated code]*/
8443
Larry Hastings2f936352014-08-05 14:04:04 +10008444static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008445os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
8446/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008447{
8448 int fd;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008449 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008450
Victor Stinnerdaf45552013-08-28 00:53:59 +02008451#ifdef O_CLOEXEC
8452 int *atomic_flag_works = &_Py_open_cloexec_works;
8453#elif !defined(MS_WINDOWS)
8454 int *atomic_flag_works = NULL;
8455#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +00008456
Victor Stinnerdaf45552013-08-28 00:53:59 +02008457#ifdef MS_WINDOWS
8458 flags |= O_NOINHERIT;
8459#elif defined(O_CLOEXEC)
8460 flags |= O_CLOEXEC;
8461#endif
8462
Steve Dowerb82e17e2019-05-23 08:45:22 -07008463 if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
8464 return -1;
8465 }
8466
Steve Dower8fc89802015-04-12 00:26:27 -04008467 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008468 do {
8469 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008470#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07008471 fd = _wopen(path->wide, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008472#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07008473#ifdef HAVE_OPENAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008474 if (dir_fd != DEFAULT_DIR_FD)
8475 fd = openat(dir_fd, path->narrow, flags, mode);
8476 else
Steve Dower6230aaf2016-09-09 09:03:15 -07008477#endif /* HAVE_OPENAT */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008478 fd = open(path->narrow, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008479#endif /* !MS_WINDOWS */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008480 Py_END_ALLOW_THREADS
8481 } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04008482 _Py_END_SUPPRESS_IPH
Guido van Rossum687dd131993-05-17 08:34:16 +00008483
Victor Stinnerd3ffd322015-09-15 10:11:03 +02008484 if (fd < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008485 if (!async_err)
8486 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Larry Hastings2f936352014-08-05 14:04:04 +10008487 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008488 }
8489
Victor Stinnerdaf45552013-08-28 00:53:59 +02008490#ifndef MS_WINDOWS
8491 if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
8492 close(fd);
Larry Hastings2f936352014-08-05 14:04:04 +10008493 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008494 }
8495#endif
8496
Larry Hastings2f936352014-08-05 14:04:04 +10008497 return fd;
8498}
8499
8500
8501/*[clinic input]
8502os.close
8503
8504 fd: int
8505
8506Close a file descriptor.
8507[clinic start generated code]*/
8508
Barry Warsaw53699e91996-12-10 23:23:01 +00008509static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008510os_close_impl(PyObject *module, int fd)
8511/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00008512{
Larry Hastings2f936352014-08-05 14:04:04 +10008513 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008514 /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
8515 * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
8516 * for more details.
8517 */
Victor Stinner8c62be82010-05-06 00:08:46 +00008518 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008519 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008520 res = close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04008521 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008522 Py_END_ALLOW_THREADS
8523 if (res < 0)
8524 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008525 Py_RETURN_NONE;
Guido van Rossum687dd131993-05-17 08:34:16 +00008526}
8527
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008528
Jakub Kulíke20134f2019-09-11 17:11:57 +02008529#ifdef HAVE_FDWALK
8530static int
8531_fdwalk_close_func(void *lohi, int fd)
8532{
8533 int lo = ((int *)lohi)[0];
8534 int hi = ((int *)lohi)[1];
8535
8536 if (fd >= hi)
8537 return 1;
8538 else if (fd >= lo)
8539 close(fd);
8540 return 0;
8541}
8542#endif /* HAVE_FDWALK */
8543
Larry Hastings2f936352014-08-05 14:04:04 +10008544/*[clinic input]
8545os.closerange
8546
8547 fd_low: int
8548 fd_high: int
8549 /
8550
8551Closes all file descriptors in [fd_low, fd_high), ignoring errors.
8552[clinic start generated code]*/
8553
Larry Hastings2f936352014-08-05 14:04:04 +10008554static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008555os_closerange_impl(PyObject *module, int fd_low, int fd_high)
8556/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008557{
Jakub Kulíke20134f2019-09-11 17:11:57 +02008558#ifdef HAVE_FDWALK
8559 int lohi[2];
8560#else
Larry Hastings2f936352014-08-05 14:04:04 +10008561 int i;
Jakub Kulíke20134f2019-09-11 17:11:57 +02008562#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00008563 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008564 _Py_BEGIN_SUPPRESS_IPH
Jakub Kulíke20134f2019-09-11 17:11:57 +02008565#ifdef HAVE_FDWALK
8566 lohi[0] = Py_MAX(fd_low, 0);
8567 lohi[1] = fd_high;
8568 fdwalk(_fdwalk_close_func, lohi);
8569#else
Benjamin Peterson207116b2016-09-08 11:28:06 -07008570 for (i = Py_MAX(fd_low, 0); i < fd_high; i++)
Steve Dower940f33a2016-09-08 11:21:54 -07008571 close(i);
Jakub Kulíke20134f2019-09-11 17:11:57 +02008572#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008573 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008574 Py_END_ALLOW_THREADS
8575 Py_RETURN_NONE;
Christian Heimesfdab48e2008-01-20 09:06:41 +00008576}
8577
8578
Larry Hastings2f936352014-08-05 14:04:04 +10008579/*[clinic input]
8580os.dup -> int
8581
8582 fd: int
8583 /
8584
8585Return a duplicate of a file descriptor.
8586[clinic start generated code]*/
8587
Larry Hastings2f936352014-08-05 14:04:04 +10008588static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008589os_dup_impl(PyObject *module, int fd)
8590/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008591{
8592 return _Py_dup(fd);
Guido van Rossum687dd131993-05-17 08:34:16 +00008593}
8594
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008595
Larry Hastings2f936352014-08-05 14:04:04 +10008596/*[clinic input]
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008597os.dup2 -> int
Larry Hastings2f936352014-08-05 14:04:04 +10008598 fd: int
8599 fd2: int
8600 inheritable: bool=True
8601
8602Duplicate file descriptor.
8603[clinic start generated code]*/
8604
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008605static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008606os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008607/*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008608{
Stéphane Wirtel3d86e482018-01-30 07:04:36 +01008609 int res = 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008610#if defined(HAVE_DUP3) && \
8611 !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
8612 /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
Alexey Izbyshevb3caf382018-02-20 10:25:46 +03008613 static int dup3_works = -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008614#endif
8615
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008616 if (fd < 0 || fd2 < 0) {
8617 posix_error();
8618 return -1;
8619 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008620
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008621 /* dup2() can fail with EINTR if the target FD is already open, because it
8622 * then has to be closed. See os_close_impl() for why we don't handle EINTR
8623 * upon close(), and therefore below.
8624 */
Victor Stinnerdaf45552013-08-28 00:53:59 +02008625#ifdef MS_WINDOWS
8626 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008627 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008628 res = dup2(fd, fd2);
Steve Dower8fc89802015-04-12 00:26:27 -04008629 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02008630 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008631 if (res < 0) {
8632 posix_error();
8633 return -1;
8634 }
8635 res = fd2; // msvcrt dup2 returns 0 on success.
Victor Stinnerdaf45552013-08-28 00:53:59 +02008636
8637 /* Character files like console cannot be make non-inheritable */
8638 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8639 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008640 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008641 }
8642
8643#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
8644 Py_BEGIN_ALLOW_THREADS
8645 if (!inheritable)
8646 res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
8647 else
8648 res = dup2(fd, fd2);
8649 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008650 if (res < 0) {
8651 posix_error();
8652 return -1;
8653 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008654
8655#else
8656
8657#ifdef HAVE_DUP3
8658 if (!inheritable && dup3_works != 0) {
8659 Py_BEGIN_ALLOW_THREADS
8660 res = dup3(fd, fd2, O_CLOEXEC);
8661 Py_END_ALLOW_THREADS
8662 if (res < 0) {
8663 if (dup3_works == -1)
8664 dup3_works = (errno != ENOSYS);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008665 if (dup3_works) {
8666 posix_error();
8667 return -1;
8668 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008669 }
8670 }
8671
8672 if (inheritable || dup3_works == 0)
8673 {
8674#endif
8675 Py_BEGIN_ALLOW_THREADS
8676 res = dup2(fd, fd2);
8677 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008678 if (res < 0) {
8679 posix_error();
8680 return -1;
8681 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008682
8683 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8684 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008685 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008686 }
8687#ifdef HAVE_DUP3
8688 }
8689#endif
8690
8691#endif
8692
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008693 return res;
Guido van Rossum687dd131993-05-17 08:34:16 +00008694}
8695
Larry Hastings2f936352014-08-05 14:04:04 +10008696
Ross Lagerwall7807c352011-03-17 20:20:30 +02008697#ifdef HAVE_LOCKF
Larry Hastings2f936352014-08-05 14:04:04 +10008698/*[clinic input]
8699os.lockf
8700
8701 fd: int
8702 An open file descriptor.
8703 command: int
8704 One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
8705 length: Py_off_t
8706 The number of bytes to lock, starting at the current position.
8707 /
8708
8709Apply, test or remove a POSIX lock on an open file descriptor.
8710
8711[clinic start generated code]*/
8712
Larry Hastings2f936352014-08-05 14:04:04 +10008713static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008714os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
8715/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008716{
8717 int res;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008718
8719 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008720 res = lockf(fd, command, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008721 Py_END_ALLOW_THREADS
8722
8723 if (res < 0)
8724 return posix_error();
8725
8726 Py_RETURN_NONE;
8727}
Larry Hastings2f936352014-08-05 14:04:04 +10008728#endif /* HAVE_LOCKF */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008729
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008730
Larry Hastings2f936352014-08-05 14:04:04 +10008731/*[clinic input]
8732os.lseek -> Py_off_t
8733
8734 fd: int
8735 position: Py_off_t
8736 how: int
8737 /
8738
8739Set the position of a file descriptor. Return the new position.
8740
8741Return the new cursor position in number of bytes
8742relative to the beginning of the file.
8743[clinic start generated code]*/
8744
Larry Hastings2f936352014-08-05 14:04:04 +10008745static Py_off_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008746os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
8747/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008748{
8749 Py_off_t result;
8750
Guido van Rossum687dd131993-05-17 08:34:16 +00008751#ifdef SEEK_SET
Victor Stinner8c62be82010-05-06 00:08:46 +00008752 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
8753 switch (how) {
Larry Hastings2f936352014-08-05 14:04:04 +10008754 case 0: how = SEEK_SET; break;
8755 case 1: how = SEEK_CUR; break;
8756 case 2: how = SEEK_END; break;
Victor Stinner8c62be82010-05-06 00:08:46 +00008757 }
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00008758#endif /* SEEK_END */
Guido van Rossum94f6f721999-01-06 18:42:14 +00008759
Victor Stinner8c62be82010-05-06 00:08:46 +00008760 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008761 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner14b9b112013-06-25 00:37:25 +02008762#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10008763 result = _lseeki64(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008764#else
Larry Hastings2f936352014-08-05 14:04:04 +10008765 result = lseek(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008766#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008767 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008768 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008769 if (result < 0)
8770 posix_error();
Guido van Rossum94f6f721999-01-06 18:42:14 +00008771
Larry Hastings2f936352014-08-05 14:04:04 +10008772 return result;
Guido van Rossum687dd131993-05-17 08:34:16 +00008773}
8774
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008775
Larry Hastings2f936352014-08-05 14:04:04 +10008776/*[clinic input]
8777os.read
8778 fd: int
8779 length: Py_ssize_t
8780 /
8781
8782Read from a file descriptor. Returns a bytes object.
8783[clinic start generated code]*/
8784
Larry Hastings2f936352014-08-05 14:04:04 +10008785static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008786os_read_impl(PyObject *module, int fd, Py_ssize_t length)
8787/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008788{
Victor Stinner8c62be82010-05-06 00:08:46 +00008789 Py_ssize_t n;
8790 PyObject *buffer;
Larry Hastings2f936352014-08-05 14:04:04 +10008791
8792 if (length < 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008793 errno = EINVAL;
8794 return posix_error();
8795 }
Larry Hastings2f936352014-08-05 14:04:04 +10008796
Victor Stinner9a0d7a72018-11-22 15:03:40 +01008797 length = Py_MIN(length, _PY_READ_MAX);
Larry Hastings2f936352014-08-05 14:04:04 +10008798
8799 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Victor Stinner8c62be82010-05-06 00:08:46 +00008800 if (buffer == NULL)
8801 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008802
Victor Stinner66aab0c2015-03-19 22:53:20 +01008803 n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
8804 if (n == -1) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008805 Py_DECREF(buffer);
Victor Stinner66aab0c2015-03-19 22:53:20 +01008806 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00008807 }
Larry Hastings2f936352014-08-05 14:04:04 +10008808
8809 if (n != length)
Victor Stinner8c62be82010-05-06 00:08:46 +00008810 _PyBytes_Resize(&buffer, n);
Larry Hastings2f936352014-08-05 14:04:04 +10008811
Victor Stinner8c62be82010-05-06 00:08:46 +00008812 return buffer;
Guido van Rossum687dd131993-05-17 08:34:16 +00008813}
8814
Ross Lagerwall7807c352011-03-17 20:20:30 +02008815#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008816 || defined(__APPLE__))) \
8817 || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
8818 || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
8819static int
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008820iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008821{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008822 Py_ssize_t i, j;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008823
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008824 *iov = PyMem_New(struct iovec, cnt);
8825 if (*iov == NULL) {
8826 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008827 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008828 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008829
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008830 *buf = PyMem_New(Py_buffer, cnt);
8831 if (*buf == NULL) {
8832 PyMem_Del(*iov);
8833 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008834 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008835 }
8836
8837 for (i = 0; i < cnt; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008838 PyObject *item = PySequence_GetItem(seq, i);
8839 if (item == NULL)
8840 goto fail;
8841 if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
8842 Py_DECREF(item);
8843 goto fail;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008844 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008845 Py_DECREF(item);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008846 (*iov)[i].iov_base = (*buf)[i].buf;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008847 (*iov)[i].iov_len = (*buf)[i].len;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008848 }
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008849 return 0;
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008850
8851fail:
8852 PyMem_Del(*iov);
8853 for (j = 0; j < i; j++) {
8854 PyBuffer_Release(&(*buf)[j]);
8855 }
8856 PyMem_Del(*buf);
Victor Stinner57ddf782014-01-08 15:21:28 +01008857 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008858}
8859
8860static void
8861iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
8862{
8863 int i;
8864 PyMem_Del(iov);
8865 for (i = 0; i < cnt; i++) {
8866 PyBuffer_Release(&buf[i]);
8867 }
8868 PyMem_Del(buf);
8869}
8870#endif
8871
Larry Hastings2f936352014-08-05 14:04:04 +10008872
Ross Lagerwall7807c352011-03-17 20:20:30 +02008873#ifdef HAVE_READV
Larry Hastings2f936352014-08-05 14:04:04 +10008874/*[clinic input]
8875os.readv -> Py_ssize_t
8876
8877 fd: int
8878 buffers: object
8879 /
8880
8881Read from a file descriptor fd into an iterable of buffers.
8882
8883The buffers should be mutable buffers accepting bytes.
8884readv will transfer data into each buffer until it is full
8885and then move on to the next buffer in the sequence to hold
8886the rest of the data.
8887
8888readv returns the total number of bytes read,
8889which may be less than the total capacity of all the buffers.
8890[clinic start generated code]*/
8891
Larry Hastings2f936352014-08-05 14:04:04 +10008892static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008893os_readv_impl(PyObject *module, int fd, PyObject *buffers)
8894/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008895{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008896 Py_ssize_t cnt, n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008897 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008898 struct iovec *iov;
8899 Py_buffer *buf;
8900
Larry Hastings2f936352014-08-05 14:04:04 +10008901 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008902 PyErr_SetString(PyExc_TypeError,
8903 "readv() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10008904 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008905 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02008906
Larry Hastings2f936352014-08-05 14:04:04 +10008907 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008908 if (cnt < 0)
8909 return -1;
Larry Hastings2f936352014-08-05 14:04:04 +10008910
8911 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
8912 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008913
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008914 do {
8915 Py_BEGIN_ALLOW_THREADS
8916 n = readv(fd, iov, cnt);
8917 Py_END_ALLOW_THREADS
8918 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02008919
8920 iov_cleanup(iov, buf, cnt);
Larry Hastings2f936352014-08-05 14:04:04 +10008921 if (n < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008922 if (!async_err)
8923 posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008924 return -1;
8925 }
Victor Stinner57ddf782014-01-08 15:21:28 +01008926
Larry Hastings2f936352014-08-05 14:04:04 +10008927 return n;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008928}
Larry Hastings2f936352014-08-05 14:04:04 +10008929#endif /* HAVE_READV */
8930
Ross Lagerwall7807c352011-03-17 20:20:30 +02008931
8932#ifdef HAVE_PREAD
Larry Hastings2f936352014-08-05 14:04:04 +10008933/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10008934os.pread
8935
8936 fd: int
Dong-hee Naad7736f2019-09-25 14:47:04 +09008937 length: Py_ssize_t
Larry Hastings2f936352014-08-05 14:04:04 +10008938 offset: Py_off_t
8939 /
8940
8941Read a number of bytes from a file descriptor starting at a particular offset.
8942
8943Read length bytes from file descriptor fd, starting at offset bytes from
8944the beginning of the file. The file offset remains unchanged.
8945[clinic start generated code]*/
8946
Larry Hastings2f936352014-08-05 14:04:04 +10008947static PyObject *
Dong-hee Naad7736f2019-09-25 14:47:04 +09008948os_pread_impl(PyObject *module, int fd, Py_ssize_t length, Py_off_t offset)
8949/*[clinic end generated code: output=3f875c1eef82e32f input=85cb4a5589627144]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008950{
Ross Lagerwall7807c352011-03-17 20:20:30 +02008951 Py_ssize_t n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008952 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008953 PyObject *buffer;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008954
Larry Hastings2f936352014-08-05 14:04:04 +10008955 if (length < 0) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008956 errno = EINVAL;
8957 return posix_error();
8958 }
Larry Hastings2f936352014-08-05 14:04:04 +10008959 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008960 if (buffer == NULL)
8961 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008962
8963 do {
8964 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008965 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008966 n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04008967 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008968 Py_END_ALLOW_THREADS
8969 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8970
Ross Lagerwall7807c352011-03-17 20:20:30 +02008971 if (n < 0) {
8972 Py_DECREF(buffer);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008973 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008974 }
Larry Hastings2f936352014-08-05 14:04:04 +10008975 if (n != length)
Ross Lagerwall7807c352011-03-17 20:20:30 +02008976 _PyBytes_Resize(&buffer, n);
8977 return buffer;
8978}
Larry Hastings2f936352014-08-05 14:04:04 +10008979#endif /* HAVE_PREAD */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008980
Pablo Galindo4defba32018-01-27 16:16:37 +00008981#if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
8982/*[clinic input]
8983os.preadv -> Py_ssize_t
8984
8985 fd: int
8986 buffers: object
8987 offset: Py_off_t
8988 flags: int = 0
8989 /
8990
8991Reads from a file descriptor into a number of mutable bytes-like objects.
8992
8993Combines the functionality of readv() and pread(). As readv(), it will
8994transfer data into each buffer until it is full and then move on to the next
8995buffer in the sequence to hold the rest of the data. Its fourth argument,
8996specifies the file offset at which the input operation is to be performed. It
8997will return the total number of bytes read (which can be less than the total
8998capacity of all the objects).
8999
9000The flags argument contains a bitwise OR of zero or more of the following flags:
9001
9002- RWF_HIPRI
9003- RWF_NOWAIT
9004
9005Using non-zero flags requires Linux 4.6 or newer.
9006[clinic start generated code]*/
9007
9008static Py_ssize_t
9009os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9010 int flags)
9011/*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
9012{
9013 Py_ssize_t cnt, n;
9014 int async_err = 0;
9015 struct iovec *iov;
9016 Py_buffer *buf;
9017
9018 if (!PySequence_Check(buffers)) {
9019 PyErr_SetString(PyExc_TypeError,
9020 "preadv2() arg 2 must be a sequence");
9021 return -1;
9022 }
9023
9024 cnt = PySequence_Size(buffers);
9025 if (cnt < 0) {
9026 return -1;
9027 }
9028
9029#ifndef HAVE_PREADV2
9030 if(flags != 0) {
9031 argument_unavailable_error("preadv2", "flags");
9032 return -1;
9033 }
9034#endif
9035
9036 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
9037 return -1;
9038 }
9039#ifdef HAVE_PREADV2
9040 do {
9041 Py_BEGIN_ALLOW_THREADS
9042 _Py_BEGIN_SUPPRESS_IPH
9043 n = preadv2(fd, iov, cnt, offset, flags);
9044 _Py_END_SUPPRESS_IPH
9045 Py_END_ALLOW_THREADS
9046 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9047#else
9048 do {
9049 Py_BEGIN_ALLOW_THREADS
9050 _Py_BEGIN_SUPPRESS_IPH
9051 n = preadv(fd, iov, cnt, offset);
9052 _Py_END_SUPPRESS_IPH
9053 Py_END_ALLOW_THREADS
9054 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9055#endif
9056
9057 iov_cleanup(iov, buf, cnt);
9058 if (n < 0) {
9059 if (!async_err) {
9060 posix_error();
9061 }
9062 return -1;
9063 }
9064
9065 return n;
9066}
9067#endif /* HAVE_PREADV */
9068
Larry Hastings2f936352014-08-05 14:04:04 +10009069
9070/*[clinic input]
9071os.write -> Py_ssize_t
9072
9073 fd: int
9074 data: Py_buffer
9075 /
9076
9077Write a bytes object to a file descriptor.
9078[clinic start generated code]*/
9079
Larry Hastings2f936352014-08-05 14:04:04 +10009080static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009081os_write_impl(PyObject *module, int fd, Py_buffer *data)
9082/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009083{
Victor Stinner66aab0c2015-03-19 22:53:20 +01009084 return _Py_write(fd, data->buf, data->len);
Ross Lagerwall7807c352011-03-17 20:20:30 +02009085}
9086
9087#ifdef HAVE_SENDFILE
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009088PyDoc_STRVAR(posix_sendfile__doc__,
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009089"sendfile(out_fd, in_fd, offset, count) -> byteswritten\n\
9090sendfile(out_fd, in_fd, offset, count[, headers][, trailers], flags=0)\n\
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009091 -> byteswritten\n\
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009092Copy count bytes from file descriptor in_fd to file descriptor out_fd.");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009093
Larry Hastings2f936352014-08-05 14:04:04 +10009094/* AC 3.5: don't bother converting, has optional group*/
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009095static PyObject *
9096posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict)
9097{
9098 int in, out;
9099 Py_ssize_t ret;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009100 int async_err = 0;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009101 off_t offset;
9102
9103#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
9104#ifndef __APPLE__
9105 Py_ssize_t len;
9106#endif
9107 PyObject *headers = NULL, *trailers = NULL;
9108 Py_buffer *hbuf, *tbuf;
9109 off_t sbytes;
9110 struct sf_hdtr sf;
9111 int flags = 0;
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009112 static char *keywords[] = {"out_fd", "in_fd",
Benjamin Petersond8a43b42011-02-26 21:35:16 +00009113 "offset", "count",
9114 "headers", "trailers", "flags", NULL};
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009115
Victor Stinner6ce0dbf2013-07-07 16:32:36 +02009116 sf.headers = NULL;
9117 sf.trailers = NULL;
9118
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009119#ifdef __APPLE__
9120 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&O&|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10009121 keywords, &out, &in, Py_off_t_converter, &offset, Py_off_t_converter, &sbytes,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009122#else
9123 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&n|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10009124 keywords, &out, &in, Py_off_t_converter, &offset, &len,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009125#endif
9126 &headers, &trailers, &flags))
9127 return NULL;
9128 if (headers != NULL) {
9129 if (!PySequence_Check(headers)) {
9130 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009131 "sendfile() headers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009132 return NULL;
9133 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009134 Py_ssize_t i = PySequence_Size(headers);
9135 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009136 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009137 if (i > INT_MAX) {
9138 PyErr_SetString(PyExc_OverflowError,
9139 "sendfile() header is too large");
9140 return NULL;
9141 }
9142 if (i > 0) {
9143 sf.hdr_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009144 if (iov_setup(&(sf.headers), &hbuf,
9145 headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009146 return NULL;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009147#ifdef __APPLE__
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009148 for (i = 0; i < sf.hdr_cnt; i++) {
9149 Py_ssize_t blen = sf.headers[i].iov_len;
9150# define OFF_T_MAX 0x7fffffffffffffff
9151 if (sbytes >= OFF_T_MAX - blen) {
9152 PyErr_SetString(PyExc_OverflowError,
9153 "sendfile() header is too large");
9154 return NULL;
9155 }
9156 sbytes += blen;
9157 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009158#endif
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009159 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009160 }
9161 }
9162 if (trailers != NULL) {
9163 if (!PySequence_Check(trailers)) {
9164 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009165 "sendfile() trailers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009166 return NULL;
9167 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009168 Py_ssize_t i = PySequence_Size(trailers);
9169 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009170 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009171 if (i > INT_MAX) {
9172 PyErr_SetString(PyExc_OverflowError,
9173 "sendfile() trailer is too large");
9174 return NULL;
9175 }
9176 if (i > 0) {
9177 sf.trl_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009178 if (iov_setup(&(sf.trailers), &tbuf,
9179 trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009180 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009181 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009182 }
9183 }
9184
Steve Dower8fc89802015-04-12 00:26:27 -04009185 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009186 do {
9187 Py_BEGIN_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009188#ifdef __APPLE__
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009189 ret = sendfile(in, out, offset, &sbytes, &sf, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009190#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009191 ret = sendfile(in, out, offset, len, &sf, &sbytes, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009192#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009193 Py_END_ALLOW_THREADS
9194 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04009195 _Py_END_SUPPRESS_IPH
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009196
9197 if (sf.headers != NULL)
9198 iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
9199 if (sf.trailers != NULL)
9200 iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
9201
9202 if (ret < 0) {
9203 if ((errno == EAGAIN) || (errno == EBUSY)) {
9204 if (sbytes != 0) {
9205 // some data has been sent
9206 goto done;
9207 }
9208 else {
9209 // no data has been sent; upper application is supposed
9210 // to retry on EAGAIN or EBUSY
9211 return posix_error();
9212 }
9213 }
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009214 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009215 }
9216 goto done;
9217
9218done:
9219 #if !defined(HAVE_LARGEFILE_SUPPORT)
9220 return Py_BuildValue("l", sbytes);
9221 #else
9222 return Py_BuildValue("L", sbytes);
9223 #endif
9224
9225#else
9226 Py_ssize_t count;
9227 PyObject *offobj;
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009228 static char *keywords[] = {"out_fd", "in_fd",
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009229 "offset", "count", NULL};
9230 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiOn:sendfile",
9231 keywords, &out, &in, &offobj, &count))
9232 return NULL;
Benjamin Peterson840ef8f2016-09-07 14:45:10 -07009233#ifdef __linux__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009234 if (offobj == Py_None) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009235 do {
9236 Py_BEGIN_ALLOW_THREADS
9237 ret = sendfile(out, in, NULL, count);
9238 Py_END_ALLOW_THREADS
9239 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009240 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009241 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodola'ff1a7352011-04-19 09:47:16 +02009242 return Py_BuildValue("n", ret);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009243 }
9244#endif
Larry Hastings2f936352014-08-05 14:04:04 +10009245 if (!Py_off_t_converter(offobj, &offset))
Antoine Pitroudcc20b82011-02-26 13:38:35 +00009246 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009247
9248 do {
9249 Py_BEGIN_ALLOW_THREADS
9250 ret = sendfile(out, in, &offset, count);
9251 Py_END_ALLOW_THREADS
9252 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009253 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009254 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009255 return Py_BuildValue("n", ret);
9256#endif
9257}
Larry Hastings2f936352014-08-05 14:04:04 +10009258#endif /* HAVE_SENDFILE */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009259
Larry Hastings2f936352014-08-05 14:04:04 +10009260
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009261#if defined(__APPLE__)
9262/*[clinic input]
9263os._fcopyfile
9264
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009265 in_fd: int
9266 out_fd: int
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009267 flags: int
9268 /
9269
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009270Efficiently copy content or metadata of 2 regular file descriptors (macOS).
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009271[clinic start generated code]*/
9272
9273static PyObject *
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009274os__fcopyfile_impl(PyObject *module, int in_fd, int out_fd, int flags)
9275/*[clinic end generated code: output=c9d1a35a992e401b input=1e34638a86948795]*/
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009276{
9277 int ret;
9278
9279 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009280 ret = fcopyfile(in_fd, out_fd, NULL, flags);
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009281 Py_END_ALLOW_THREADS
9282 if (ret < 0)
9283 return posix_error();
9284 Py_RETURN_NONE;
9285}
9286#endif
9287
9288
Larry Hastings2f936352014-08-05 14:04:04 +10009289/*[clinic input]
9290os.fstat
9291
9292 fd : int
9293
9294Perform a stat system call on the given file descriptor.
9295
9296Like stat(), but for an open file descriptor.
9297Equivalent to os.stat(fd).
9298[clinic start generated code]*/
9299
Larry Hastings2f936352014-08-05 14:04:04 +10009300static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009301os_fstat_impl(PyObject *module, int fd)
9302/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009303{
Victor Stinner8c62be82010-05-06 00:08:46 +00009304 STRUCT_STAT st;
9305 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009306 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009307
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009308 do {
9309 Py_BEGIN_ALLOW_THREADS
9310 res = FSTAT(fd, &st);
9311 Py_END_ALLOW_THREADS
9312 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner8c62be82010-05-06 00:08:46 +00009313 if (res != 0) {
Martin v. Löwis14694662006-02-03 12:54:16 +00009314#ifdef MS_WINDOWS
Victor Stinnerb024e842012-10-31 22:24:06 +01009315 return PyErr_SetFromWindowsErr(0);
Martin v. Löwis14694662006-02-03 12:54:16 +00009316#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009317 return (!async_err) ? posix_error() : NULL;
Martin v. Löwis14694662006-02-03 12:54:16 +00009318#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00009319 }
Tim Peters5aa91602002-01-30 05:46:57 +00009320
Victor Stinner4195b5c2012-02-08 23:03:19 +01009321 return _pystat_fromstructstat(&st);
Guido van Rossum687dd131993-05-17 08:34:16 +00009322}
9323
Larry Hastings2f936352014-08-05 14:04:04 +10009324
9325/*[clinic input]
9326os.isatty -> bool
9327 fd: int
9328 /
9329
9330Return True if the fd is connected to a terminal.
9331
9332Return True if the file descriptor is an open file descriptor
9333connected to the slave end of a terminal.
9334[clinic start generated code]*/
9335
Larry Hastings2f936352014-08-05 14:04:04 +10009336static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009337os_isatty_impl(PyObject *module, int fd)
9338/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009339{
Steve Dower8fc89802015-04-12 00:26:27 -04009340 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -04009341 _Py_BEGIN_SUPPRESS_IPH
9342 return_value = isatty(fd);
9343 _Py_END_SUPPRESS_IPH
9344 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +10009345}
9346
9347
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009348#ifdef HAVE_PIPE
Larry Hastings2f936352014-08-05 14:04:04 +10009349/*[clinic input]
9350os.pipe
9351
9352Create a pipe.
9353
9354Returns a tuple of two file descriptors:
9355 (read_fd, write_fd)
9356[clinic start generated code]*/
9357
Larry Hastings2f936352014-08-05 14:04:04 +10009358static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009359os_pipe_impl(PyObject *module)
9360/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00009361{
Victor Stinner8c62be82010-05-06 00:08:46 +00009362 int fds[2];
Victor Stinnerdaf45552013-08-28 00:53:59 +02009363#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00009364 HANDLE read, write;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009365 SECURITY_ATTRIBUTES attr;
Victor Stinner8c62be82010-05-06 00:08:46 +00009366 BOOL ok;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009367#else
9368 int res;
9369#endif
9370
9371#ifdef MS_WINDOWS
9372 attr.nLength = sizeof(attr);
9373 attr.lpSecurityDescriptor = NULL;
9374 attr.bInheritHandle = FALSE;
9375
9376 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08009377 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009378 ok = CreatePipe(&read, &write, &attr, 0);
9379 if (ok) {
Benjamin Petersonca470632016-09-06 13:47:26 -07009380 fds[0] = _open_osfhandle((intptr_t)read, _O_RDONLY);
9381 fds[1] = _open_osfhandle((intptr_t)write, _O_WRONLY);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009382 if (fds[0] == -1 || fds[1] == -1) {
9383 CloseHandle(read);
9384 CloseHandle(write);
9385 ok = 0;
9386 }
9387 }
Steve Dowerc3630612016-11-19 18:41:16 -08009388 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009389 Py_END_ALLOW_THREADS
9390
Victor Stinner8c62be82010-05-06 00:08:46 +00009391 if (!ok)
Victor Stinnerb024e842012-10-31 22:24:06 +01009392 return PyErr_SetFromWindowsErr(0);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009393#else
9394
9395#ifdef HAVE_PIPE2
9396 Py_BEGIN_ALLOW_THREADS
9397 res = pipe2(fds, O_CLOEXEC);
9398 Py_END_ALLOW_THREADS
9399
9400 if (res != 0 && errno == ENOSYS)
9401 {
9402#endif
9403 Py_BEGIN_ALLOW_THREADS
9404 res = pipe(fds);
9405 Py_END_ALLOW_THREADS
9406
9407 if (res == 0) {
9408 if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
9409 close(fds[0]);
9410 close(fds[1]);
9411 return NULL;
9412 }
9413 if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
9414 close(fds[0]);
9415 close(fds[1]);
9416 return NULL;
9417 }
9418 }
9419#ifdef HAVE_PIPE2
9420 }
9421#endif
9422
9423 if (res != 0)
9424 return PyErr_SetFromErrno(PyExc_OSError);
9425#endif /* !MS_WINDOWS */
9426 return Py_BuildValue("(ii)", fds[0], fds[1]);
Guido van Rossum687dd131993-05-17 08:34:16 +00009427}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009428#endif /* HAVE_PIPE */
9429
Larry Hastings2f936352014-08-05 14:04:04 +10009430
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009431#ifdef HAVE_PIPE2
Larry Hastings2f936352014-08-05 14:04:04 +10009432/*[clinic input]
9433os.pipe2
9434
9435 flags: int
9436 /
9437
9438Create a pipe with flags set atomically.
9439
9440Returns a tuple of two file descriptors:
9441 (read_fd, write_fd)
9442
9443flags can be constructed by ORing together one or more of these values:
9444O_NONBLOCK, O_CLOEXEC.
9445[clinic start generated code]*/
9446
Larry Hastings2f936352014-08-05 14:04:04 +10009447static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009448os_pipe2_impl(PyObject *module, int flags)
9449/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009450{
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009451 int fds[2];
9452 int res;
9453
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009454 res = pipe2(fds, flags);
9455 if (res != 0)
9456 return posix_error();
9457 return Py_BuildValue("(ii)", fds[0], fds[1]);
9458}
9459#endif /* HAVE_PIPE2 */
9460
Larry Hastings2f936352014-08-05 14:04:04 +10009461
Ross Lagerwall7807c352011-03-17 20:20:30 +02009462#ifdef HAVE_WRITEV
Larry Hastings2f936352014-08-05 14:04:04 +10009463/*[clinic input]
9464os.writev -> Py_ssize_t
9465 fd: int
9466 buffers: object
9467 /
9468
9469Iterate over buffers, and write the contents of each to a file descriptor.
9470
9471Returns the total number of bytes written.
9472buffers must be a sequence of bytes-like objects.
9473[clinic start generated code]*/
9474
Larry Hastings2f936352014-08-05 14:04:04 +10009475static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009476os_writev_impl(PyObject *module, int fd, PyObject *buffers)
9477/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009478{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009479 Py_ssize_t cnt;
Larry Hastings2f936352014-08-05 14:04:04 +10009480 Py_ssize_t result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009481 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009482 struct iovec *iov;
9483 Py_buffer *buf;
Larry Hastings2f936352014-08-05 14:04:04 +10009484
9485 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009486 PyErr_SetString(PyExc_TypeError,
9487 "writev() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009488 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009489 }
Larry Hastings2f936352014-08-05 14:04:04 +10009490 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009491 if (cnt < 0)
9492 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009493
Larry Hastings2f936352014-08-05 14:04:04 +10009494 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9495 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009496 }
9497
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009498 do {
9499 Py_BEGIN_ALLOW_THREADS
9500 result = writev(fd, iov, cnt);
9501 Py_END_ALLOW_THREADS
9502 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009503
9504 iov_cleanup(iov, buf, cnt);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009505 if (result < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009506 posix_error();
Victor Stinner57ddf782014-01-08 15:21:28 +01009507
Georg Brandl306336b2012-06-24 12:55:33 +02009508 return result;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009509}
Larry Hastings2f936352014-08-05 14:04:04 +10009510#endif /* HAVE_WRITEV */
9511
9512
9513#ifdef HAVE_PWRITE
9514/*[clinic input]
9515os.pwrite -> Py_ssize_t
9516
9517 fd: int
9518 buffer: Py_buffer
9519 offset: Py_off_t
9520 /
9521
9522Write bytes to a file descriptor starting at a particular offset.
9523
9524Write buffer to fd, starting at offset bytes from the beginning of
9525the file. Returns the number of bytes writte. Does not change the
9526current file offset.
9527[clinic start generated code]*/
9528
Larry Hastings2f936352014-08-05 14:04:04 +10009529static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009530os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
9531/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009532{
9533 Py_ssize_t size;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009534 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009535
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009536 do {
9537 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009538 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009539 size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009540 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009541 Py_END_ALLOW_THREADS
9542 } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +10009543
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009544 if (size < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009545 posix_error();
9546 return size;
9547}
9548#endif /* HAVE_PWRITE */
9549
Pablo Galindo4defba32018-01-27 16:16:37 +00009550#if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
9551/*[clinic input]
9552os.pwritev -> Py_ssize_t
9553
9554 fd: int
9555 buffers: object
9556 offset: Py_off_t
9557 flags: int = 0
9558 /
9559
9560Writes the contents of bytes-like objects to a file descriptor at a given offset.
9561
9562Combines the functionality of writev() and pwrite(). All buffers must be a sequence
9563of bytes-like objects. Buffers are processed in array order. Entire contents of first
9564buffer is written before proceeding to second, and so on. The operating system may
9565set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
9566This function writes the contents of each object to the file descriptor and returns
9567the total number of bytes written.
9568
9569The flags argument contains a bitwise OR of zero or more of the following flags:
9570
9571- RWF_DSYNC
9572- RWF_SYNC
9573
9574Using non-zero flags requires Linux 4.7 or newer.
9575[clinic start generated code]*/
9576
9577static Py_ssize_t
9578os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9579 int flags)
9580/*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=803dc5ddbf0cfd3b]*/
9581{
9582 Py_ssize_t cnt;
9583 Py_ssize_t result;
9584 int async_err = 0;
9585 struct iovec *iov;
9586 Py_buffer *buf;
9587
9588 if (!PySequence_Check(buffers)) {
9589 PyErr_SetString(PyExc_TypeError,
9590 "pwritev() arg 2 must be a sequence");
9591 return -1;
9592 }
9593
9594 cnt = PySequence_Size(buffers);
9595 if (cnt < 0) {
9596 return -1;
9597 }
9598
9599#ifndef HAVE_PWRITEV2
9600 if(flags != 0) {
9601 argument_unavailable_error("pwritev2", "flags");
9602 return -1;
9603 }
9604#endif
9605
9606 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9607 return -1;
9608 }
9609#ifdef HAVE_PWRITEV2
9610 do {
9611 Py_BEGIN_ALLOW_THREADS
9612 _Py_BEGIN_SUPPRESS_IPH
9613 result = pwritev2(fd, iov, cnt, offset, flags);
9614 _Py_END_SUPPRESS_IPH
9615 Py_END_ALLOW_THREADS
9616 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9617#else
9618 do {
9619 Py_BEGIN_ALLOW_THREADS
9620 _Py_BEGIN_SUPPRESS_IPH
9621 result = pwritev(fd, iov, cnt, offset);
9622 _Py_END_SUPPRESS_IPH
9623 Py_END_ALLOW_THREADS
9624 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9625#endif
9626
9627 iov_cleanup(iov, buf, cnt);
9628 if (result < 0) {
9629 if (!async_err) {
9630 posix_error();
9631 }
9632 return -1;
9633 }
9634
9635 return result;
9636}
9637#endif /* HAVE_PWRITEV */
9638
Pablo Galindoaac4d032019-05-31 19:39:47 +01009639#ifdef HAVE_COPY_FILE_RANGE
9640/*[clinic input]
9641
9642os.copy_file_range
9643 src: int
9644 Source file descriptor.
9645 dst: int
9646 Destination file descriptor.
9647 count: Py_ssize_t
9648 Number of bytes to copy.
9649 offset_src: object = None
9650 Starting offset in src.
9651 offset_dst: object = None
9652 Starting offset in dst.
9653
9654Copy count bytes from one file descriptor to another.
9655
9656If offset_src is None, then src is read from the current position;
9657respectively for offset_dst.
9658[clinic start generated code]*/
9659
9660static PyObject *
9661os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
9662 PyObject *offset_src, PyObject *offset_dst)
9663/*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
9664{
9665 off_t offset_src_val, offset_dst_val;
9666 off_t *p_offset_src = NULL;
9667 off_t *p_offset_dst = NULL;
9668 Py_ssize_t ret;
9669 int async_err = 0;
9670 /* The flags argument is provided to allow
9671 * for future extensions and currently must be to 0. */
9672 int flags = 0;
Pablo Galindo4defba32018-01-27 16:16:37 +00009673
9674
Pablo Galindoaac4d032019-05-31 19:39:47 +01009675 if (count < 0) {
9676 PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
9677 return NULL;
9678 }
9679
9680 if (offset_src != Py_None) {
9681 if (!Py_off_t_converter(offset_src, &offset_src_val)) {
9682 return NULL;
9683 }
9684 p_offset_src = &offset_src_val;
9685 }
9686
9687 if (offset_dst != Py_None) {
9688 if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
9689 return NULL;
9690 }
9691 p_offset_dst = &offset_dst_val;
9692 }
9693
9694 do {
9695 Py_BEGIN_ALLOW_THREADS
9696 ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
9697 Py_END_ALLOW_THREADS
9698 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9699
9700 if (ret < 0) {
9701 return (!async_err) ? posix_error() : NULL;
9702 }
9703
9704 return PyLong_FromSsize_t(ret);
9705}
9706#endif /* HAVE_COPY_FILE_RANGE*/
Larry Hastings2f936352014-08-05 14:04:04 +10009707
9708#ifdef HAVE_MKFIFO
9709/*[clinic input]
9710os.mkfifo
9711
9712 path: path_t
9713 mode: int=0o666
9714 *
9715 dir_fd: dir_fd(requires='mkfifoat')=None
9716
9717Create a "fifo" (a POSIX named pipe).
9718
9719If dir_fd is not None, it should be a file descriptor open to a directory,
9720 and path should be relative; path will then be relative to that directory.
9721dir_fd may not be implemented on your platform.
9722 If it is unavailable, using it will raise a NotImplementedError.
9723[clinic start generated code]*/
9724
Larry Hastings2f936352014-08-05 14:04:04 +10009725static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009726os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
9727/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009728{
9729 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009730 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009731
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009732 do {
9733 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009734#ifdef HAVE_MKFIFOAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009735 if (dir_fd != DEFAULT_DIR_FD)
9736 result = mkfifoat(dir_fd, path->narrow, mode);
9737 else
Ross Lagerwall7807c352011-03-17 20:20:30 +02009738#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009739 result = mkfifo(path->narrow, mode);
9740 Py_END_ALLOW_THREADS
9741 } while (result != 0 && errno == EINTR &&
9742 !(async_err = PyErr_CheckSignals()));
9743 if (result != 0)
9744 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009745
9746 Py_RETURN_NONE;
9747}
9748#endif /* HAVE_MKFIFO */
9749
9750
9751#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
9752/*[clinic input]
9753os.mknod
9754
9755 path: path_t
9756 mode: int=0o600
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009757 device: dev_t=0
Larry Hastings2f936352014-08-05 14:04:04 +10009758 *
9759 dir_fd: dir_fd(requires='mknodat')=None
9760
9761Create a node in the file system.
9762
9763Create a node in the file system (file, device special file or named pipe)
9764at path. mode specifies both the permissions to use and the
9765type of node to be created, being combined (bitwise OR) with one of
9766S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
9767device defines the newly created device special file (probably using
9768os.makedev()). Otherwise device is ignored.
9769
9770If dir_fd is not None, it should be a file descriptor open to a directory,
9771 and path should be relative; path will then be relative to that directory.
9772dir_fd may not be implemented on your platform.
9773 If it is unavailable, using it will raise a NotImplementedError.
9774[clinic start generated code]*/
9775
Larry Hastings2f936352014-08-05 14:04:04 +10009776static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009777os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
Larry Hastings89964c42015-04-14 18:07:59 -04009778 int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009779/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009780{
9781 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009782 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009783
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009784 do {
9785 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009786#ifdef HAVE_MKNODAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009787 if (dir_fd != DEFAULT_DIR_FD)
9788 result = mknodat(dir_fd, path->narrow, mode, device);
9789 else
Larry Hastings2f936352014-08-05 14:04:04 +10009790#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009791 result = mknod(path->narrow, mode, device);
9792 Py_END_ALLOW_THREADS
9793 } while (result != 0 && errno == EINTR &&
9794 !(async_err = PyErr_CheckSignals()));
9795 if (result != 0)
9796 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009797
9798 Py_RETURN_NONE;
9799}
9800#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
9801
9802
9803#ifdef HAVE_DEVICE_MACROS
9804/*[clinic input]
9805os.major -> unsigned_int
9806
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009807 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009808 /
9809
9810Extracts a device major number from a raw device number.
9811[clinic start generated code]*/
9812
Larry Hastings2f936352014-08-05 14:04:04 +10009813static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009814os_major_impl(PyObject *module, dev_t device)
9815/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009816{
9817 return major(device);
9818}
9819
9820
9821/*[clinic input]
9822os.minor -> unsigned_int
9823
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009824 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009825 /
9826
9827Extracts a device minor number from a raw device number.
9828[clinic start generated code]*/
9829
Larry Hastings2f936352014-08-05 14:04:04 +10009830static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009831os_minor_impl(PyObject *module, dev_t device)
9832/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009833{
9834 return minor(device);
9835}
9836
9837
9838/*[clinic input]
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009839os.makedev -> dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009840
9841 major: int
9842 minor: int
9843 /
9844
9845Composes a raw device number from the major and minor device numbers.
9846[clinic start generated code]*/
9847
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009848static dev_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009849os_makedev_impl(PyObject *module, int major, int minor)
9850/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009851{
9852 return makedev(major, minor);
9853}
9854#endif /* HAVE_DEVICE_MACROS */
9855
9856
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009857#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009858/*[clinic input]
9859os.ftruncate
9860
9861 fd: int
9862 length: Py_off_t
9863 /
9864
9865Truncate a file, specified by file descriptor, to a specific length.
9866[clinic start generated code]*/
9867
Larry Hastings2f936352014-08-05 14:04:04 +10009868static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009869os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
9870/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009871{
9872 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009873 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009874
Steve Dowerb82e17e2019-05-23 08:45:22 -07009875 if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
9876 return NULL;
9877 }
9878
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009879 do {
9880 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009881 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009882#ifdef MS_WINDOWS
9883 result = _chsize_s(fd, length);
9884#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009885 result = ftruncate(fd, length);
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009886#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009887 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009888 Py_END_ALLOW_THREADS
9889 } while (result != 0 && errno == EINTR &&
9890 !(async_err = PyErr_CheckSignals()));
9891 if (result != 0)
9892 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009893 Py_RETURN_NONE;
9894}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009895#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009896
9897
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009898#if defined HAVE_TRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009899/*[clinic input]
9900os.truncate
9901 path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
9902 length: Py_off_t
9903
9904Truncate a file, specified by path, to a specific length.
9905
9906On some platforms, path may also be specified as an open file descriptor.
9907 If this functionality is unavailable, using it raises an exception.
9908[clinic start generated code]*/
9909
Larry Hastings2f936352014-08-05 14:04:04 +10009910static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009911os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
9912/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009913{
9914 int result;
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009915#ifdef MS_WINDOWS
9916 int fd;
9917#endif
9918
9919 if (path->fd != -1)
9920 return os_ftruncate_impl(module, path->fd, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009921
Steve Dowerb82e17e2019-05-23 08:45:22 -07009922 if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
9923 return NULL;
9924 }
9925
Larry Hastings2f936352014-08-05 14:04:04 +10009926 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009927 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009928#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07009929 fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
Victor Stinnercc0bbbc2015-04-25 00:21:52 +02009930 if (fd < 0)
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009931 result = -1;
9932 else {
9933 result = _chsize_s(fd, length);
9934 close(fd);
9935 if (result < 0)
9936 errno = result;
9937 }
9938#else
9939 result = truncate(path->narrow, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009940#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009941 _Py_END_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10009942 Py_END_ALLOW_THREADS
9943 if (result < 0)
Alexey Izbyshev83460312018-10-20 03:28:22 +03009944 return posix_path_error(path);
Larry Hastings2f936352014-08-05 14:04:04 +10009945
9946 Py_RETURN_NONE;
9947}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009948#endif /* HAVE_TRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009949
Ross Lagerwall7807c352011-03-17 20:20:30 +02009950
Victor Stinnerd6b17692014-09-30 12:20:05 +02009951/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
9952 and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
9953 defined, which is the case in Python on AIX. AIX bug report:
9954 http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
9955#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
9956# define POSIX_FADVISE_AIX_BUG
9957#endif
9958
Victor Stinnerec39e262014-09-30 12:35:58 +02009959
Victor Stinnerd6b17692014-09-30 12:20:05 +02009960#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +10009961/*[clinic input]
9962os.posix_fallocate
9963
9964 fd: int
9965 offset: Py_off_t
9966 length: Py_off_t
9967 /
9968
9969Ensure a file has allocated at least a particular number of bytes on disk.
9970
9971Ensure that the file specified by fd encompasses a range of bytes
9972starting at offset bytes from the beginning and continuing for length bytes.
9973[clinic start generated code]*/
9974
Larry Hastings2f936352014-08-05 14:04:04 +10009975static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009976os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -04009977 Py_off_t length)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009978/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009979{
9980 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009981 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009982
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009983 do {
9984 Py_BEGIN_ALLOW_THREADS
9985 result = posix_fallocate(fd, offset, length);
9986 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +05009987 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
9988
9989 if (result == 0)
9990 Py_RETURN_NONE;
9991
9992 if (async_err)
9993 return NULL;
9994
9995 errno = result;
9996 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +02009997}
Victor Stinnerec39e262014-09-30 12:35:58 +02009998#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
Larry Hastings2f936352014-08-05 14:04:04 +10009999
Ross Lagerwall7807c352011-03-17 20:20:30 +020010000
Victor Stinnerd6b17692014-09-30 12:20:05 +020010001#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +100010002/*[clinic input]
10003os.posix_fadvise
10004
10005 fd: int
10006 offset: Py_off_t
10007 length: Py_off_t
10008 advice: int
10009 /
10010
10011Announce an intention to access data in a specific pattern.
10012
10013Announce an intention to access data in a specific pattern, thus allowing
10014the kernel to make optimizations.
10015The advice applies to the region of the file specified by fd starting at
10016offset and continuing for length bytes.
10017advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
10018POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
10019POSIX_FADV_DONTNEED.
10020[clinic start generated code]*/
10021
Larry Hastings2f936352014-08-05 14:04:04 +100010022static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010023os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -040010024 Py_off_t length, int advice)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010025/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010026{
10027 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010028 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010029
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010030 do {
10031 Py_BEGIN_ALLOW_THREADS
10032 result = posix_fadvise(fd, offset, length, advice);
10033 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010034 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10035
10036 if (result == 0)
10037 Py_RETURN_NONE;
10038
10039 if (async_err)
10040 return NULL;
10041
10042 errno = result;
10043 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010044}
Victor Stinnerec39e262014-09-30 12:35:58 +020010045#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
Ross Lagerwall7807c352011-03-17 20:20:30 +020010046
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000010047
Thomas Hellerf78f12a2007-11-08 19:33:05 +000010048#ifdef MS_WINDOWS
Victor Stinner161e7b32020-01-24 11:53:44 +010010049static PyObject*
10050win32_putenv(PyObject *name, PyObject *value)
10051{
10052 /* Search from index 1 because on Windows starting '=' is allowed for
10053 defining hidden environment variables. */
10054 if (PyUnicode_GET_LENGTH(name) == 0 ||
10055 PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
10056 {
10057 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10058 return NULL;
10059 }
10060 PyObject *unicode;
10061 if (value != NULL) {
10062 unicode = PyUnicode_FromFormat("%U=%U", name, value);
10063 }
10064 else {
10065 unicode = PyUnicode_FromFormat("%U=", name);
10066 }
10067 if (unicode == NULL) {
10068 return NULL;
10069 }
10070
10071 Py_ssize_t size;
10072 /* PyUnicode_AsWideCharString() rejects embedded null characters */
10073 wchar_t *env = PyUnicode_AsWideCharString(unicode, &size);
10074 Py_DECREF(unicode);
10075
10076 if (env == NULL) {
10077 return NULL;
10078 }
10079 if (size > _MAX_ENV) {
10080 PyErr_Format(PyExc_ValueError,
10081 "the environment variable is longer than %u characters",
10082 _MAX_ENV);
10083 PyMem_Free(env);
10084 return NULL;
10085 }
10086
10087 /* _wputenv() and SetEnvironmentVariableW() update the environment in the
10088 Process Environment Block (PEB). _wputenv() also updates CRT 'environ'
10089 and '_wenviron' variables, whereas SetEnvironmentVariableW() does not.
10090
10091 Prefer _wputenv() to be compatible with C libraries using CRT
10092 variables and CRT functions using these variables (ex: getenv()). */
10093 int err = _wputenv(env);
10094 PyMem_Free(env);
10095
10096 if (err) {
10097 posix_error();
10098 return NULL;
10099 }
10100
10101 Py_RETURN_NONE;
10102}
10103#endif
10104
10105
10106#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010107/*[clinic input]
10108os.putenv
10109
10110 name: unicode
10111 value: unicode
10112 /
10113
10114Change or add an environment variable.
10115[clinic start generated code]*/
10116
Larry Hastings2f936352014-08-05 14:04:04 +100010117static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010118os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10119/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010120{
Victor Stinner161e7b32020-01-24 11:53:44 +010010121 return win32_putenv(name, value);
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010122}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010123#else
Larry Hastings2f936352014-08-05 14:04:04 +100010124/*[clinic input]
10125os.putenv
Guido van Rossumb6a47161997-09-15 22:54:34 +000010126
Larry Hastings2f936352014-08-05 14:04:04 +100010127 name: FSConverter
10128 value: FSConverter
10129 /
10130
10131Change or add an environment variable.
10132[clinic start generated code]*/
10133
Larry Hastings2f936352014-08-05 14:04:04 +100010134static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010135os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10136/*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010137{
Serhiy Storchaka77703942017-06-25 07:33:01 +030010138 const char *name_string = PyBytes_AS_STRING(name);
10139 const char *value_string = PyBytes_AS_STRING(value);
Larry Hastings2f936352014-08-05 14:04:04 +100010140
Serhiy Storchaka77703942017-06-25 07:33:01 +030010141 if (strchr(name_string, '=') != NULL) {
10142 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10143 return NULL;
10144 }
Victor Stinnerb477d192020-01-22 22:48:16 +010010145
Victor Stinnerb477d192020-01-22 22:48:16 +010010146 if (setenv(name_string, value_string, 1)) {
10147 return posix_error();
10148 }
Larry Hastings2f936352014-08-05 14:04:04 +100010149 Py_RETURN_NONE;
10150}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010151#endif /* !defined(MS_WINDOWS) */
Larry Hastings2f936352014-08-05 14:04:04 +100010152
10153
Victor Stinner161e7b32020-01-24 11:53:44 +010010154#ifdef MS_WINDOWS
10155/*[clinic input]
10156os.unsetenv
10157 name: unicode
10158 /
10159
10160Delete an environment variable.
10161[clinic start generated code]*/
10162
10163static PyObject *
10164os_unsetenv_impl(PyObject *module, PyObject *name)
10165/*[clinic end generated code: output=54c4137ab1834f02 input=4d6a1747cc526d2f]*/
10166{
10167 return win32_putenv(name, NULL);
10168}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010169#else
Larry Hastings2f936352014-08-05 14:04:04 +100010170/*[clinic input]
10171os.unsetenv
10172 name: FSConverter
10173 /
10174
10175Delete an environment variable.
10176[clinic start generated code]*/
10177
Larry Hastings2f936352014-08-05 14:04:04 +100010178static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010179os_unsetenv_impl(PyObject *module, PyObject *name)
10180/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010181{
Victor Stinner984890f2011-11-24 13:53:38 +010010182#ifdef HAVE_BROKEN_UNSETENV
10183 unsetenv(PyBytes_AS_STRING(name));
10184#else
Victor Stinner161e7b32020-01-24 11:53:44 +010010185 int err = unsetenv(PyBytes_AS_STRING(name));
10186 if (err) {
Victor Stinner60b385e2011-11-22 22:01:28 +010010187 return posix_error();
Victor Stinner161e7b32020-01-24 11:53:44 +010010188 }
Victor Stinner984890f2011-11-24 13:53:38 +010010189#endif
Guido van Rossumc524d952001-10-19 01:31:59 +000010190
Victor Stinner84ae1182010-05-06 22:05:07 +000010191 Py_RETURN_NONE;
Guido van Rossumc524d952001-10-19 01:31:59 +000010192}
Victor Stinnerb8d12622020-01-24 14:05:48 +010010193#endif /* !MS_WINDOWS */
Guido van Rossumc524d952001-10-19 01:31:59 +000010194
Larry Hastings2f936352014-08-05 14:04:04 +100010195
10196/*[clinic input]
10197os.strerror
10198
10199 code: int
10200 /
10201
10202Translate an error code to a message string.
10203[clinic start generated code]*/
10204
Larry Hastings2f936352014-08-05 14:04:04 +100010205static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010206os_strerror_impl(PyObject *module, int code)
10207/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010208{
10209 char *message = strerror(code);
Victor Stinner8c62be82010-05-06 00:08:46 +000010210 if (message == NULL) {
10211 PyErr_SetString(PyExc_ValueError,
10212 "strerror() argument out of range");
10213 return NULL;
10214 }
Victor Stinner1b579672011-12-17 05:47:23 +010010215 return PyUnicode_DecodeLocale(message, "surrogateescape");
Guido van Rossumb6a47161997-09-15 22:54:34 +000010216}
Guido van Rossumb6a47161997-09-15 22:54:34 +000010217
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010218
Guido van Rossumc9641791998-08-04 15:26:23 +000010219#ifdef HAVE_SYS_WAIT_H
Fred Drake106c1a02002-04-23 15:58:02 +000010220#ifdef WCOREDUMP
Larry Hastings2f936352014-08-05 14:04:04 +100010221/*[clinic input]
10222os.WCOREDUMP -> bool
10223
10224 status: int
10225 /
10226
10227Return True if the process returning status was dumped to a core file.
10228[clinic start generated code]*/
10229
Larry Hastings2f936352014-08-05 14:04:04 +100010230static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010231os_WCOREDUMP_impl(PyObject *module, int status)
10232/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010233{
10234 WAIT_TYPE wait_status;
10235 WAIT_STATUS_INT(wait_status) = status;
10236 return WCOREDUMP(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010237}
10238#endif /* WCOREDUMP */
10239
Larry Hastings2f936352014-08-05 14:04:04 +100010240
Fred Drake106c1a02002-04-23 15:58:02 +000010241#ifdef WIFCONTINUED
Larry Hastings2f936352014-08-05 14:04:04 +100010242/*[clinic input]
10243os.WIFCONTINUED -> bool
10244
10245 status: int
10246
10247Return True if a particular process was continued from a job control stop.
10248
10249Return True if the process returning status was continued from a
10250job control stop.
10251[clinic start generated code]*/
10252
Larry Hastings2f936352014-08-05 14:04:04 +100010253static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010254os_WIFCONTINUED_impl(PyObject *module, int status)
10255/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010256{
10257 WAIT_TYPE wait_status;
10258 WAIT_STATUS_INT(wait_status) = status;
10259 return WIFCONTINUED(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010260}
10261#endif /* WIFCONTINUED */
10262
Larry Hastings2f936352014-08-05 14:04:04 +100010263
Guido van Rossumc9641791998-08-04 15:26:23 +000010264#ifdef WIFSTOPPED
Larry Hastings2f936352014-08-05 14:04:04 +100010265/*[clinic input]
10266os.WIFSTOPPED -> bool
10267
10268 status: int
10269
10270Return True if the process returning status was stopped.
10271[clinic start generated code]*/
10272
Larry Hastings2f936352014-08-05 14:04:04 +100010273static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010274os_WIFSTOPPED_impl(PyObject *module, int status)
10275/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010276{
10277 WAIT_TYPE wait_status;
10278 WAIT_STATUS_INT(wait_status) = status;
10279 return WIFSTOPPED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010280}
10281#endif /* WIFSTOPPED */
10282
Larry Hastings2f936352014-08-05 14:04:04 +100010283
Guido van Rossumc9641791998-08-04 15:26:23 +000010284#ifdef WIFSIGNALED
Larry Hastings2f936352014-08-05 14:04:04 +100010285/*[clinic input]
10286os.WIFSIGNALED -> bool
10287
10288 status: int
10289
10290Return True if the process returning status was terminated by a signal.
10291[clinic start generated code]*/
10292
Larry Hastings2f936352014-08-05 14:04:04 +100010293static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010294os_WIFSIGNALED_impl(PyObject *module, int status)
10295/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010296{
10297 WAIT_TYPE wait_status;
10298 WAIT_STATUS_INT(wait_status) = status;
10299 return WIFSIGNALED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010300}
10301#endif /* WIFSIGNALED */
10302
Larry Hastings2f936352014-08-05 14:04:04 +100010303
Guido van Rossumc9641791998-08-04 15:26:23 +000010304#ifdef WIFEXITED
Larry Hastings2f936352014-08-05 14:04:04 +100010305/*[clinic input]
10306os.WIFEXITED -> bool
10307
10308 status: int
10309
10310Return True if the process returning status exited via the exit() system call.
10311[clinic start generated code]*/
10312
Larry Hastings2f936352014-08-05 14:04:04 +100010313static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010314os_WIFEXITED_impl(PyObject *module, int status)
10315/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010316{
10317 WAIT_TYPE wait_status;
10318 WAIT_STATUS_INT(wait_status) = status;
10319 return WIFEXITED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010320}
10321#endif /* WIFEXITED */
10322
Larry Hastings2f936352014-08-05 14:04:04 +100010323
Guido van Rossum54ecc3d1999-01-27 17:53:11 +000010324#ifdef WEXITSTATUS
Larry Hastings2f936352014-08-05 14:04:04 +100010325/*[clinic input]
10326os.WEXITSTATUS -> int
10327
10328 status: int
10329
10330Return the process return code from status.
10331[clinic start generated code]*/
10332
Larry Hastings2f936352014-08-05 14:04:04 +100010333static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010334os_WEXITSTATUS_impl(PyObject *module, int status)
10335/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010336{
10337 WAIT_TYPE wait_status;
10338 WAIT_STATUS_INT(wait_status) = status;
10339 return WEXITSTATUS(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010340}
10341#endif /* WEXITSTATUS */
10342
Larry Hastings2f936352014-08-05 14:04:04 +100010343
Guido van Rossumc9641791998-08-04 15:26:23 +000010344#ifdef WTERMSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010345/*[clinic input]
10346os.WTERMSIG -> int
10347
10348 status: int
10349
10350Return the signal that terminated the process that provided the status value.
10351[clinic start generated code]*/
10352
Larry Hastings2f936352014-08-05 14:04:04 +100010353static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010354os_WTERMSIG_impl(PyObject *module, int status)
10355/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010356{
10357 WAIT_TYPE wait_status;
10358 WAIT_STATUS_INT(wait_status) = status;
10359 return WTERMSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010360}
10361#endif /* WTERMSIG */
10362
Larry Hastings2f936352014-08-05 14:04:04 +100010363
Guido van Rossumc9641791998-08-04 15:26:23 +000010364#ifdef WSTOPSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010365/*[clinic input]
10366os.WSTOPSIG -> int
10367
10368 status: int
10369
10370Return the signal that stopped the process that provided the status value.
10371[clinic start generated code]*/
10372
Larry Hastings2f936352014-08-05 14:04:04 +100010373static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010374os_WSTOPSIG_impl(PyObject *module, int status)
10375/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010376{
10377 WAIT_TYPE wait_status;
10378 WAIT_STATUS_INT(wait_status) = status;
10379 return WSTOPSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010380}
10381#endif /* WSTOPSIG */
Guido van Rossumc9641791998-08-04 15:26:23 +000010382#endif /* HAVE_SYS_WAIT_H */
10383
10384
Thomas Wouters477c8d52006-05-27 19:21:47 +000010385#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossumd5753e11999-10-19 13:29:23 +000010386#ifdef _SCO_DS
10387/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
10388 needed definitions in sys/statvfs.h */
10389#define _SVID3
10390#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000010391#include <sys/statvfs.h>
10392
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010393static PyObject*
10394_pystatvfs_fromstructstatvfs(struct statvfs st) {
Eddie Elizondob3966632019-11-05 07:16:14 -080010395 PyObject *StatVFSResultType = _posixstate_global->StatVFSResultType;
10396 PyObject *v = PyStructSequence_New((PyTypeObject *)StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000010397 if (v == NULL)
10398 return NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010399
10400#if !defined(HAVE_LARGEFILE_SUPPORT)
Victor Stinner8c62be82010-05-06 00:08:46 +000010401 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10402 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10403 PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
10404 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
10405 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
10406 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
10407 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
10408 PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
10409 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10410 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010411#else
Victor Stinner8c62be82010-05-06 00:08:46 +000010412 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10413 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10414 PyStructSequence_SET_ITEM(v, 2,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010415 PyLong_FromLongLong((long long) st.f_blocks));
Victor Stinner8c62be82010-05-06 00:08:46 +000010416 PyStructSequence_SET_ITEM(v, 3,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010417 PyLong_FromLongLong((long long) st.f_bfree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010418 PyStructSequence_SET_ITEM(v, 4,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010419 PyLong_FromLongLong((long long) st.f_bavail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010420 PyStructSequence_SET_ITEM(v, 5,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010421 PyLong_FromLongLong((long long) st.f_files));
Victor Stinner8c62be82010-05-06 00:08:46 +000010422 PyStructSequence_SET_ITEM(v, 6,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010423 PyLong_FromLongLong((long long) st.f_ffree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010424 PyStructSequence_SET_ITEM(v, 7,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010425 PyLong_FromLongLong((long long) st.f_favail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010426 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10427 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010428#endif
Michael Felt502d5512018-01-05 13:01:58 +010010429/* The _ALL_SOURCE feature test macro defines f_fsid as a structure
10430 * (issue #32390). */
10431#if defined(_AIX) && defined(_ALL_SOURCE)
10432 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
10433#else
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +010010434 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid));
Michael Felt502d5512018-01-05 13:01:58 +010010435#endif
Victor Stinnerf0a7bac2013-10-30 18:55:24 +010010436 if (PyErr_Occurred()) {
10437 Py_DECREF(v);
10438 return NULL;
10439 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010440
Victor Stinner8c62be82010-05-06 00:08:46 +000010441 return v;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010442}
10443
Larry Hastings2f936352014-08-05 14:04:04 +100010444
10445/*[clinic input]
10446os.fstatvfs
10447 fd: int
10448 /
10449
10450Perform an fstatvfs system call on the given fd.
10451
10452Equivalent to statvfs(fd).
10453[clinic start generated code]*/
10454
Larry Hastings2f936352014-08-05 14:04:04 +100010455static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010456os_fstatvfs_impl(PyObject *module, int fd)
10457/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010458{
10459 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010460 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010461 struct statvfs st;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010462
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010463 do {
10464 Py_BEGIN_ALLOW_THREADS
10465 result = fstatvfs(fd, &st);
10466 Py_END_ALLOW_THREADS
10467 } while (result != 0 && errno == EINTR &&
10468 !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +100010469 if (result != 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010470 return (!async_err) ? posix_error() : NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010471
Victor Stinner8c62be82010-05-06 00:08:46 +000010472 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010473}
Larry Hastings2f936352014-08-05 14:04:04 +100010474#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
Guido van Rossum94f6f721999-01-06 18:42:14 +000010475
10476
Thomas Wouters477c8d52006-05-27 19:21:47 +000010477#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossum94f6f721999-01-06 18:42:14 +000010478#include <sys/statvfs.h>
Larry Hastings2f936352014-08-05 14:04:04 +100010479/*[clinic input]
10480os.statvfs
Guido van Rossum94f6f721999-01-06 18:42:14 +000010481
Larry Hastings2f936352014-08-05 14:04:04 +100010482 path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
10483
10484Perform a statvfs system call on the given path.
10485
10486path may always be specified as a string.
10487On some platforms, path may also be specified as an open file descriptor.
10488 If this functionality is unavailable, using it raises an exception.
10489[clinic start generated code]*/
10490
Larry Hastings2f936352014-08-05 14:04:04 +100010491static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010492os_statvfs_impl(PyObject *module, path_t *path)
10493/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010494{
10495 int result;
10496 struct statvfs st;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010497
10498 Py_BEGIN_ALLOW_THREADS
10499#ifdef HAVE_FSTATVFS
Larry Hastings2f936352014-08-05 14:04:04 +100010500 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -070010501#ifdef __APPLE__
10502 /* handle weak-linking on Mac OS X 10.3 */
10503 if (fstatvfs == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010504 fd_specified("statvfs", path->fd);
10505 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010506 }
10507#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010508 result = fstatvfs(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010509 }
10510 else
10511#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010512 result = statvfs(path->narrow, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010513 Py_END_ALLOW_THREADS
10514
10515 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100010516 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010517 }
10518
Larry Hastings2f936352014-08-05 14:04:04 +100010519 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010520}
Larry Hastings2f936352014-08-05 14:04:04 +100010521#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
10522
Guido van Rossum94f6f721999-01-06 18:42:14 +000010523
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010524#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010525/*[clinic input]
10526os._getdiskusage
10527
Steve Dower23ad6d02018-02-22 10:39:10 -080010528 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +100010529
10530Return disk usage statistics about the given path as a (total, free) tuple.
10531[clinic start generated code]*/
10532
Larry Hastings2f936352014-08-05 14:04:04 +100010533static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -080010534os__getdiskusage_impl(PyObject *module, path_t *path)
10535/*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010536{
10537 BOOL retval;
10538 ULARGE_INTEGER _, total, free;
Joe Pamerc8c02492018-09-25 10:57:36 -040010539 DWORD err = 0;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010540
10541 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -080010542 retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010543 Py_END_ALLOW_THREADS
Joe Pamerc8c02492018-09-25 10:57:36 -040010544 if (retval == 0) {
10545 if (GetLastError() == ERROR_DIRECTORY) {
10546 wchar_t *dir_path = NULL;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010547
Joe Pamerc8c02492018-09-25 10:57:36 -040010548 dir_path = PyMem_New(wchar_t, path->length + 1);
10549 if (dir_path == NULL) {
10550 return PyErr_NoMemory();
10551 }
10552
10553 wcscpy_s(dir_path, path->length + 1, path->wide);
10554
10555 if (_dirnameW(dir_path) != -1) {
10556 Py_BEGIN_ALLOW_THREADS
10557 retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
10558 Py_END_ALLOW_THREADS
10559 }
10560 /* Record the last error in case it's modified by PyMem_Free. */
10561 err = GetLastError();
10562 PyMem_Free(dir_path);
10563 if (retval) {
10564 goto success;
10565 }
10566 }
10567 return PyErr_SetFromWindowsErr(err);
10568 }
10569
10570success:
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010571 return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
10572}
Larry Hastings2f936352014-08-05 14:04:04 +100010573#endif /* MS_WINDOWS */
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010574
10575
Fred Drakec9680921999-12-13 16:37:25 +000010576/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
10577 * It maps strings representing configuration variable names to
10578 * integer values, allowing those functions to be called with the
Thomas Wouters7e474022000-07-16 12:04:32 +000010579 * magic names instead of polluting the module's namespace with tons of
Fred Drake12c6e2d1999-12-14 21:25:03 +000010580 * rarely-used constants. There are three separate tables that use
10581 * these definitions.
Fred Drakebec628d1999-12-15 18:31:10 +000010582 *
10583 * This code is always included, even if none of the interfaces that
10584 * need it are included. The #if hackery needed to avoid it would be
10585 * sufficiently pervasive that it's not worth the loss of readability.
Fred Drakec9680921999-12-13 16:37:25 +000010586 */
10587struct constdef {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020010588 const char *name;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010589 int value;
Fred Drakec9680921999-12-13 16:37:25 +000010590};
10591
Fred Drake12c6e2d1999-12-14 21:25:03 +000010592static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010593conv_confname(PyObject *arg, int *valuep, struct constdef *table,
Guido van Rossum7d5baac2007-08-27 23:24:46 +000010594 size_t tablesize)
Fred Drake12c6e2d1999-12-14 21:25:03 +000010595{
Christian Heimes217cfd12007-12-02 14:31:20 +000010596 if (PyLong_Check(arg)) {
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010597 int value = _PyLong_AsInt(arg);
10598 if (value == -1 && PyErr_Occurred())
10599 return 0;
10600 *valuep = value;
Stefan Krah0e803b32010-11-26 16:16:47 +000010601 return 1;
Fred Drake12c6e2d1999-12-14 21:25:03 +000010602 }
Guido van Rossumbce56a62007-05-10 18:04:33 +000010603 else {
Stefan Krah0e803b32010-11-26 16:16:47 +000010604 /* look up the value in the table using a binary search */
10605 size_t lo = 0;
10606 size_t mid;
10607 size_t hi = tablesize;
10608 int cmp;
10609 const char *confname;
10610 if (!PyUnicode_Check(arg)) {
10611 PyErr_SetString(PyExc_TypeError,
10612 "configuration names must be strings or integers");
10613 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010614 }
Serhiy Storchaka06515832016-11-20 09:13:07 +020010615 confname = PyUnicode_AsUTF8(arg);
Stefan Krah0e803b32010-11-26 16:16:47 +000010616 if (confname == NULL)
10617 return 0;
10618 while (lo < hi) {
10619 mid = (lo + hi) / 2;
10620 cmp = strcmp(confname, table[mid].name);
10621 if (cmp < 0)
10622 hi = mid;
10623 else if (cmp > 0)
10624 lo = mid + 1;
10625 else {
10626 *valuep = table[mid].value;
10627 return 1;
10628 }
10629 }
10630 PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
10631 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010632 }
Fred Drake12c6e2d1999-12-14 21:25:03 +000010633}
10634
10635
10636#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
10637static struct constdef posix_constants_pathconf[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010638#ifdef _PC_ABI_AIO_XFER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010639 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000010640#endif
10641#ifdef _PC_ABI_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010642 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010643#endif
Fred Drakec9680921999-12-13 16:37:25 +000010644#ifdef _PC_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010645 {"PC_ASYNC_IO", _PC_ASYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010646#endif
10647#ifdef _PC_CHOWN_RESTRICTED
Victor Stinner8c62be82010-05-06 00:08:46 +000010648 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
Fred Drakec9680921999-12-13 16:37:25 +000010649#endif
10650#ifdef _PC_FILESIZEBITS
Victor Stinner8c62be82010-05-06 00:08:46 +000010651 {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
Fred Drakec9680921999-12-13 16:37:25 +000010652#endif
10653#ifdef _PC_LAST
Victor Stinner8c62be82010-05-06 00:08:46 +000010654 {"PC_LAST", _PC_LAST},
Fred Drakec9680921999-12-13 16:37:25 +000010655#endif
10656#ifdef _PC_LINK_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010657 {"PC_LINK_MAX", _PC_LINK_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010658#endif
10659#ifdef _PC_MAX_CANON
Victor Stinner8c62be82010-05-06 00:08:46 +000010660 {"PC_MAX_CANON", _PC_MAX_CANON},
Fred Drakec9680921999-12-13 16:37:25 +000010661#endif
10662#ifdef _PC_MAX_INPUT
Victor Stinner8c62be82010-05-06 00:08:46 +000010663 {"PC_MAX_INPUT", _PC_MAX_INPUT},
Fred Drakec9680921999-12-13 16:37:25 +000010664#endif
10665#ifdef _PC_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010666 {"PC_NAME_MAX", _PC_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010667#endif
10668#ifdef _PC_NO_TRUNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010669 {"PC_NO_TRUNC", _PC_NO_TRUNC},
Fred Drakec9680921999-12-13 16:37:25 +000010670#endif
10671#ifdef _PC_PATH_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010672 {"PC_PATH_MAX", _PC_PATH_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010673#endif
10674#ifdef _PC_PIPE_BUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010675 {"PC_PIPE_BUF", _PC_PIPE_BUF},
Fred Drakec9680921999-12-13 16:37:25 +000010676#endif
10677#ifdef _PC_PRIO_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010678 {"PC_PRIO_IO", _PC_PRIO_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010679#endif
10680#ifdef _PC_SOCK_MAXBUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010681 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
Fred Drakec9680921999-12-13 16:37:25 +000010682#endif
10683#ifdef _PC_SYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010684 {"PC_SYNC_IO", _PC_SYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010685#endif
10686#ifdef _PC_VDISABLE
Victor Stinner8c62be82010-05-06 00:08:46 +000010687 {"PC_VDISABLE", _PC_VDISABLE},
Fred Drakec9680921999-12-13 16:37:25 +000010688#endif
Jesus Cea7e9065c2010-10-25 13:02:04 +000010689#ifdef _PC_ACL_ENABLED
10690 {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
10691#endif
10692#ifdef _PC_MIN_HOLE_SIZE
10693 {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
10694#endif
10695#ifdef _PC_ALLOC_SIZE_MIN
10696 {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
10697#endif
10698#ifdef _PC_REC_INCR_XFER_SIZE
10699 {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
10700#endif
10701#ifdef _PC_REC_MAX_XFER_SIZE
10702 {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
10703#endif
10704#ifdef _PC_REC_MIN_XFER_SIZE
10705 {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
10706#endif
10707#ifdef _PC_REC_XFER_ALIGN
10708 {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
10709#endif
10710#ifdef _PC_SYMLINK_MAX
10711 {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
10712#endif
10713#ifdef _PC_XATTR_ENABLED
10714 {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
10715#endif
10716#ifdef _PC_XATTR_EXISTS
10717 {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
10718#endif
10719#ifdef _PC_TIMESTAMP_RESOLUTION
10720 {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
10721#endif
Fred Drakec9680921999-12-13 16:37:25 +000010722};
10723
Fred Drakec9680921999-12-13 16:37:25 +000010724static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010725conv_path_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010726{
10727 return conv_confname(arg, valuep, posix_constants_pathconf,
10728 sizeof(posix_constants_pathconf)
10729 / sizeof(struct constdef));
10730}
10731#endif
10732
Larry Hastings2f936352014-08-05 14:04:04 +100010733
Fred Drakec9680921999-12-13 16:37:25 +000010734#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010735/*[clinic input]
10736os.fpathconf -> long
10737
10738 fd: int
10739 name: path_confname
10740 /
10741
10742Return the configuration limit name for the file descriptor fd.
10743
10744If there is no limit, return -1.
10745[clinic start generated code]*/
10746
Larry Hastings2f936352014-08-05 14:04:04 +100010747static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010748os_fpathconf_impl(PyObject *module, int fd, int name)
10749/*[clinic end generated code: output=d5b7042425fc3e21 input=5942a024d3777810]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010750{
10751 long limit;
10752
10753 errno = 0;
10754 limit = fpathconf(fd, name);
10755 if (limit == -1 && errno != 0)
10756 posix_error();
10757
10758 return limit;
10759}
10760#endif /* HAVE_FPATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010761
10762
10763#ifdef HAVE_PATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010764/*[clinic input]
10765os.pathconf -> long
10766 path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
10767 name: path_confname
10768
10769Return the configuration limit name for the file or directory path.
10770
10771If there is no limit, return -1.
10772On some platforms, path may also be specified as an open file descriptor.
10773 If this functionality is unavailable, using it raises an exception.
10774[clinic start generated code]*/
10775
Larry Hastings2f936352014-08-05 14:04:04 +100010776static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010777os_pathconf_impl(PyObject *module, path_t *path, int name)
10778/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010779{
Victor Stinner8c62be82010-05-06 00:08:46 +000010780 long limit;
Fred Drakec9680921999-12-13 16:37:25 +000010781
Victor Stinner8c62be82010-05-06 00:08:46 +000010782 errno = 0;
Georg Brandl306336b2012-06-24 12:55:33 +020010783#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010784 if (path->fd != -1)
10785 limit = fpathconf(path->fd, name);
Georg Brandl306336b2012-06-24 12:55:33 +020010786 else
10787#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010788 limit = pathconf(path->narrow, name);
Victor Stinner8c62be82010-05-06 00:08:46 +000010789 if (limit == -1 && errno != 0) {
10790 if (errno == EINVAL)
Stefan Krah99439262010-11-26 12:58:05 +000010791 /* could be a path or name problem */
10792 posix_error();
Fred Drakec9680921999-12-13 16:37:25 +000010793 else
Larry Hastings2f936352014-08-05 14:04:04 +100010794 path_error(path);
Victor Stinner8c62be82010-05-06 00:08:46 +000010795 }
Larry Hastings2f936352014-08-05 14:04:04 +100010796
10797 return limit;
Fred Drakec9680921999-12-13 16:37:25 +000010798}
Larry Hastings2f936352014-08-05 14:04:04 +100010799#endif /* HAVE_PATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010800
10801#ifdef HAVE_CONFSTR
10802static struct constdef posix_constants_confstr[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010803#ifdef _CS_ARCHITECTURE
Victor Stinner8c62be82010-05-06 00:08:46 +000010804 {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
Fred Draked86ed291999-12-15 15:34:33 +000010805#endif
Mark Dickinson876d7c82010-04-16 12:47:52 +000010806#ifdef _CS_GNU_LIBC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010807 {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010808#endif
10809#ifdef _CS_GNU_LIBPTHREAD_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010810 {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010811#endif
Fred Draked86ed291999-12-15 15:34:33 +000010812#ifdef _CS_HOSTNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010813 {"CS_HOSTNAME", _CS_HOSTNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010814#endif
10815#ifdef _CS_HW_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010816 {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010817#endif
10818#ifdef _CS_HW_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010819 {"CS_HW_SERIAL", _CS_HW_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010820#endif
10821#ifdef _CS_INITTAB_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010822 {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010823#endif
Fred Drakec9680921999-12-13 16:37:25 +000010824#ifdef _CS_LFS64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010825 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010826#endif
10827#ifdef _CS_LFS64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010828 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010829#endif
10830#ifdef _CS_LFS64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010831 {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010832#endif
10833#ifdef _CS_LFS64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010834 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010835#endif
10836#ifdef _CS_LFS_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010837 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010838#endif
10839#ifdef _CS_LFS_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010840 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010841#endif
10842#ifdef _CS_LFS_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010843 {"CS_LFS_LIBS", _CS_LFS_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010844#endif
10845#ifdef _CS_LFS_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010846 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010847#endif
Fred Draked86ed291999-12-15 15:34:33 +000010848#ifdef _CS_MACHINE
Victor Stinner8c62be82010-05-06 00:08:46 +000010849 {"CS_MACHINE", _CS_MACHINE},
Fred Draked86ed291999-12-15 15:34:33 +000010850#endif
Fred Drakec9680921999-12-13 16:37:25 +000010851#ifdef _CS_PATH
Victor Stinner8c62be82010-05-06 00:08:46 +000010852 {"CS_PATH", _CS_PATH},
Fred Drakec9680921999-12-13 16:37:25 +000010853#endif
Fred Draked86ed291999-12-15 15:34:33 +000010854#ifdef _CS_RELEASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010855 {"CS_RELEASE", _CS_RELEASE},
Fred Draked86ed291999-12-15 15:34:33 +000010856#endif
10857#ifdef _CS_SRPC_DOMAIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010858 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
Fred Draked86ed291999-12-15 15:34:33 +000010859#endif
10860#ifdef _CS_SYSNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010861 {"CS_SYSNAME", _CS_SYSNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010862#endif
10863#ifdef _CS_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010864 {"CS_VERSION", _CS_VERSION},
Fred Draked86ed291999-12-15 15:34:33 +000010865#endif
Fred Drakec9680921999-12-13 16:37:25 +000010866#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010867 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010868#endif
10869#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010870 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010871#endif
10872#ifdef _CS_XBS5_ILP32_OFF32_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010873 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010874#endif
10875#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010876 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010877#endif
10878#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010879 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010880#endif
10881#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010882 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010883#endif
10884#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010885 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010886#endif
10887#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010888 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010889#endif
10890#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010891 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010892#endif
10893#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010894 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010895#endif
10896#ifdef _CS_XBS5_LP64_OFF64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010897 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010898#endif
10899#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010900 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010901#endif
10902#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010903 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010904#endif
10905#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010906 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010907#endif
10908#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010909 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010910#endif
10911#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010912 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010913#endif
Fred Draked86ed291999-12-15 15:34:33 +000010914#ifdef _MIPS_CS_AVAIL_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010915 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010916#endif
10917#ifdef _MIPS_CS_BASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010918 {"MIPS_CS_BASE", _MIPS_CS_BASE},
Fred Draked86ed291999-12-15 15:34:33 +000010919#endif
10920#ifdef _MIPS_CS_HOSTID
Victor Stinner8c62be82010-05-06 00:08:46 +000010921 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
Fred Draked86ed291999-12-15 15:34:33 +000010922#endif
10923#ifdef _MIPS_CS_HW_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010924 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010925#endif
10926#ifdef _MIPS_CS_NUM_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010927 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010928#endif
10929#ifdef _MIPS_CS_OSREL_MAJ
Victor Stinner8c62be82010-05-06 00:08:46 +000010930 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
Fred Draked86ed291999-12-15 15:34:33 +000010931#endif
10932#ifdef _MIPS_CS_OSREL_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010933 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
Fred Draked86ed291999-12-15 15:34:33 +000010934#endif
10935#ifdef _MIPS_CS_OSREL_PATCH
Victor Stinner8c62be82010-05-06 00:08:46 +000010936 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
Fred Draked86ed291999-12-15 15:34:33 +000010937#endif
10938#ifdef _MIPS_CS_OS_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010939 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010940#endif
10941#ifdef _MIPS_CS_OS_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010942 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010943#endif
10944#ifdef _MIPS_CS_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010945 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010946#endif
10947#ifdef _MIPS_CS_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010948 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010949#endif
10950#ifdef _MIPS_CS_VENDOR
Victor Stinner8c62be82010-05-06 00:08:46 +000010951 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
Fred Draked86ed291999-12-15 15:34:33 +000010952#endif
Fred Drakec9680921999-12-13 16:37:25 +000010953};
10954
10955static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010956conv_confstr_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010957{
10958 return conv_confname(arg, valuep, posix_constants_confstr,
10959 sizeof(posix_constants_confstr)
10960 / sizeof(struct constdef));
10961}
10962
Larry Hastings2f936352014-08-05 14:04:04 +100010963
10964/*[clinic input]
10965os.confstr
10966
10967 name: confstr_confname
10968 /
10969
10970Return a string-valued system configuration variable.
10971[clinic start generated code]*/
10972
Larry Hastings2f936352014-08-05 14:04:04 +100010973static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010974os_confstr_impl(PyObject *module, int name)
10975/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
Fred Drakec9680921999-12-13 16:37:25 +000010976{
10977 PyObject *result = NULL;
Victor Stinnercb043522010-09-10 23:49:04 +000010978 char buffer[255];
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020010979 size_t len;
Fred Drakec9680921999-12-13 16:37:25 +000010980
Victor Stinnercb043522010-09-10 23:49:04 +000010981 errno = 0;
10982 len = confstr(name, buffer, sizeof(buffer));
10983 if (len == 0) {
10984 if (errno) {
10985 posix_error();
10986 return NULL;
Fred Drakec9680921999-12-13 16:37:25 +000010987 }
10988 else {
Victor Stinnercb043522010-09-10 23:49:04 +000010989 Py_RETURN_NONE;
Fred Drakec9680921999-12-13 16:37:25 +000010990 }
10991 }
Victor Stinnercb043522010-09-10 23:49:04 +000010992
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020010993 if (len >= sizeof(buffer)) {
Victor Stinnercbc18f32014-12-05 22:51:51 +010010994 size_t len2;
Victor Stinnercb043522010-09-10 23:49:04 +000010995 char *buf = PyMem_Malloc(len);
10996 if (buf == NULL)
10997 return PyErr_NoMemory();
Victor Stinnercbc18f32014-12-05 22:51:51 +010010998 len2 = confstr(name, buf, len);
10999 assert(len == len2);
Christian Heimes8714cfd2015-04-21 10:57:41 +020011000 result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
Victor Stinnercb043522010-09-10 23:49:04 +000011001 PyMem_Free(buf);
11002 }
11003 else
11004 result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
Fred Drakec9680921999-12-13 16:37:25 +000011005 return result;
11006}
Larry Hastings2f936352014-08-05 14:04:04 +100011007#endif /* HAVE_CONFSTR */
Fred Drakec9680921999-12-13 16:37:25 +000011008
11009
11010#ifdef HAVE_SYSCONF
11011static struct constdef posix_constants_sysconf[] = {
11012#ifdef _SC_2_CHAR_TERM
Victor Stinner8c62be82010-05-06 00:08:46 +000011013 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
Fred Drakec9680921999-12-13 16:37:25 +000011014#endif
11015#ifdef _SC_2_C_BIND
Victor Stinner8c62be82010-05-06 00:08:46 +000011016 {"SC_2_C_BIND", _SC_2_C_BIND},
Fred Drakec9680921999-12-13 16:37:25 +000011017#endif
11018#ifdef _SC_2_C_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011019 {"SC_2_C_DEV", _SC_2_C_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011020#endif
11021#ifdef _SC_2_C_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011022 {"SC_2_C_VERSION", _SC_2_C_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011023#endif
11024#ifdef _SC_2_FORT_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011025 {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011026#endif
11027#ifdef _SC_2_FORT_RUN
Victor Stinner8c62be82010-05-06 00:08:46 +000011028 {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
Fred Drakec9680921999-12-13 16:37:25 +000011029#endif
11030#ifdef _SC_2_LOCALEDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000011031 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
Fred Drakec9680921999-12-13 16:37:25 +000011032#endif
11033#ifdef _SC_2_SW_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011034 {"SC_2_SW_DEV", _SC_2_SW_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011035#endif
11036#ifdef _SC_2_UPE
Victor Stinner8c62be82010-05-06 00:08:46 +000011037 {"SC_2_UPE", _SC_2_UPE},
Fred Drakec9680921999-12-13 16:37:25 +000011038#endif
11039#ifdef _SC_2_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011040 {"SC_2_VERSION", _SC_2_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011041#endif
Fred Draked86ed291999-12-15 15:34:33 +000011042#ifdef _SC_ABI_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011043 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
Fred Draked86ed291999-12-15 15:34:33 +000011044#endif
11045#ifdef _SC_ACL
Victor Stinner8c62be82010-05-06 00:08:46 +000011046 {"SC_ACL", _SC_ACL},
Fred Draked86ed291999-12-15 15:34:33 +000011047#endif
Fred Drakec9680921999-12-13 16:37:25 +000011048#ifdef _SC_AIO_LISTIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011049 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011050#endif
Fred Drakec9680921999-12-13 16:37:25 +000011051#ifdef _SC_AIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011052 {"SC_AIO_MAX", _SC_AIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011053#endif
11054#ifdef _SC_AIO_PRIO_DELTA_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011055 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011056#endif
11057#ifdef _SC_ARG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011058 {"SC_ARG_MAX", _SC_ARG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011059#endif
11060#ifdef _SC_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011061 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011062#endif
11063#ifdef _SC_ATEXIT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011064 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011065#endif
Fred Draked86ed291999-12-15 15:34:33 +000011066#ifdef _SC_AUDIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011067 {"SC_AUDIT", _SC_AUDIT},
Fred Draked86ed291999-12-15 15:34:33 +000011068#endif
Fred Drakec9680921999-12-13 16:37:25 +000011069#ifdef _SC_AVPHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011070 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011071#endif
11072#ifdef _SC_BC_BASE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011073 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011074#endif
11075#ifdef _SC_BC_DIM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011076 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011077#endif
11078#ifdef _SC_BC_SCALE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011079 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011080#endif
11081#ifdef _SC_BC_STRING_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011082 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011083#endif
Fred Draked86ed291999-12-15 15:34:33 +000011084#ifdef _SC_CAP
Victor Stinner8c62be82010-05-06 00:08:46 +000011085 {"SC_CAP", _SC_CAP},
Fred Draked86ed291999-12-15 15:34:33 +000011086#endif
Fred Drakec9680921999-12-13 16:37:25 +000011087#ifdef _SC_CHARCLASS_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011088 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011089#endif
11090#ifdef _SC_CHAR_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011091 {"SC_CHAR_BIT", _SC_CHAR_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011092#endif
11093#ifdef _SC_CHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011094 {"SC_CHAR_MAX", _SC_CHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011095#endif
11096#ifdef _SC_CHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011097 {"SC_CHAR_MIN", _SC_CHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011098#endif
11099#ifdef _SC_CHILD_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011100 {"SC_CHILD_MAX", _SC_CHILD_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011101#endif
11102#ifdef _SC_CLK_TCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011103 {"SC_CLK_TCK", _SC_CLK_TCK},
Fred Drakec9680921999-12-13 16:37:25 +000011104#endif
11105#ifdef _SC_COHER_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011106 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011107#endif
11108#ifdef _SC_COLL_WEIGHTS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011109 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011110#endif
11111#ifdef _SC_DCACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011112 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011113#endif
11114#ifdef _SC_DCACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011115 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011116#endif
11117#ifdef _SC_DCACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011118 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011119#endif
11120#ifdef _SC_DCACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011121 {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011122#endif
11123#ifdef _SC_DCACHE_TBLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011124 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011125#endif
11126#ifdef _SC_DELAYTIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011127 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011128#endif
11129#ifdef _SC_EQUIV_CLASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011130 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011131#endif
11132#ifdef _SC_EXPR_NEST_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011133 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011134#endif
11135#ifdef _SC_FSYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000011136 {"SC_FSYNC", _SC_FSYNC},
Fred Drakec9680921999-12-13 16:37:25 +000011137#endif
11138#ifdef _SC_GETGR_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011139 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011140#endif
11141#ifdef _SC_GETPW_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011142 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011143#endif
11144#ifdef _SC_ICACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011145 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011146#endif
11147#ifdef _SC_ICACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011148 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011149#endif
11150#ifdef _SC_ICACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011151 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011152#endif
11153#ifdef _SC_ICACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011154 {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011155#endif
Fred Draked86ed291999-12-15 15:34:33 +000011156#ifdef _SC_INF
Victor Stinner8c62be82010-05-06 00:08:46 +000011157 {"SC_INF", _SC_INF},
Fred Draked86ed291999-12-15 15:34:33 +000011158#endif
Fred Drakec9680921999-12-13 16:37:25 +000011159#ifdef _SC_INT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011160 {"SC_INT_MAX", _SC_INT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011161#endif
11162#ifdef _SC_INT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011163 {"SC_INT_MIN", _SC_INT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011164#endif
11165#ifdef _SC_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011166 {"SC_IOV_MAX", _SC_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011167#endif
Fred Draked86ed291999-12-15 15:34:33 +000011168#ifdef _SC_IP_SECOPTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011169 {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
Fred Draked86ed291999-12-15 15:34:33 +000011170#endif
Fred Drakec9680921999-12-13 16:37:25 +000011171#ifdef _SC_JOB_CONTROL
Victor Stinner8c62be82010-05-06 00:08:46 +000011172 {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
Fred Drakec9680921999-12-13 16:37:25 +000011173#endif
Fred Draked86ed291999-12-15 15:34:33 +000011174#ifdef _SC_KERN_POINTERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011175 {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
Fred Draked86ed291999-12-15 15:34:33 +000011176#endif
11177#ifdef _SC_KERN_SIM
Victor Stinner8c62be82010-05-06 00:08:46 +000011178 {"SC_KERN_SIM", _SC_KERN_SIM},
Fred Draked86ed291999-12-15 15:34:33 +000011179#endif
Fred Drakec9680921999-12-13 16:37:25 +000011180#ifdef _SC_LINE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011181 {"SC_LINE_MAX", _SC_LINE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011182#endif
11183#ifdef _SC_LOGIN_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011184 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011185#endif
11186#ifdef _SC_LOGNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011187 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011188#endif
11189#ifdef _SC_LONG_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011190 {"SC_LONG_BIT", _SC_LONG_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011191#endif
Fred Draked86ed291999-12-15 15:34:33 +000011192#ifdef _SC_MAC
Victor Stinner8c62be82010-05-06 00:08:46 +000011193 {"SC_MAC", _SC_MAC},
Fred Draked86ed291999-12-15 15:34:33 +000011194#endif
Fred Drakec9680921999-12-13 16:37:25 +000011195#ifdef _SC_MAPPED_FILES
Victor Stinner8c62be82010-05-06 00:08:46 +000011196 {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
Fred Drakec9680921999-12-13 16:37:25 +000011197#endif
11198#ifdef _SC_MAXPID
Victor Stinner8c62be82010-05-06 00:08:46 +000011199 {"SC_MAXPID", _SC_MAXPID},
Fred Drakec9680921999-12-13 16:37:25 +000011200#endif
11201#ifdef _SC_MB_LEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011202 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011203#endif
11204#ifdef _SC_MEMLOCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011205 {"SC_MEMLOCK", _SC_MEMLOCK},
Fred Drakec9680921999-12-13 16:37:25 +000011206#endif
11207#ifdef _SC_MEMLOCK_RANGE
Victor Stinner8c62be82010-05-06 00:08:46 +000011208 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
Fred Drakec9680921999-12-13 16:37:25 +000011209#endif
11210#ifdef _SC_MEMORY_PROTECTION
Victor Stinner8c62be82010-05-06 00:08:46 +000011211 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
Fred Drakec9680921999-12-13 16:37:25 +000011212#endif
11213#ifdef _SC_MESSAGE_PASSING
Victor Stinner8c62be82010-05-06 00:08:46 +000011214 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
Fred Drakec9680921999-12-13 16:37:25 +000011215#endif
Fred Draked86ed291999-12-15 15:34:33 +000011216#ifdef _SC_MMAP_FIXED_ALIGNMENT
Victor Stinner8c62be82010-05-06 00:08:46 +000011217 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
Fred Draked86ed291999-12-15 15:34:33 +000011218#endif
Fred Drakec9680921999-12-13 16:37:25 +000011219#ifdef _SC_MQ_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011220 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011221#endif
11222#ifdef _SC_MQ_PRIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011223 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011224#endif
Fred Draked86ed291999-12-15 15:34:33 +000011225#ifdef _SC_NACLS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011226 {"SC_NACLS_MAX", _SC_NACLS_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000011227#endif
Fred Drakec9680921999-12-13 16:37:25 +000011228#ifdef _SC_NGROUPS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011229 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011230#endif
11231#ifdef _SC_NL_ARGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011232 {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011233#endif
11234#ifdef _SC_NL_LANGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011235 {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011236#endif
11237#ifdef _SC_NL_MSGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011238 {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011239#endif
11240#ifdef _SC_NL_NMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011241 {"SC_NL_NMAX", _SC_NL_NMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011242#endif
11243#ifdef _SC_NL_SETMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011244 {"SC_NL_SETMAX", _SC_NL_SETMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011245#endif
11246#ifdef _SC_NL_TEXTMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011247 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011248#endif
11249#ifdef _SC_NPROCESSORS_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011250 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
Fred Drakec9680921999-12-13 16:37:25 +000011251#endif
11252#ifdef _SC_NPROCESSORS_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011253 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
Fred Drakec9680921999-12-13 16:37:25 +000011254#endif
Fred Draked86ed291999-12-15 15:34:33 +000011255#ifdef _SC_NPROC_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011256 {"SC_NPROC_CONF", _SC_NPROC_CONF},
Fred Draked86ed291999-12-15 15:34:33 +000011257#endif
11258#ifdef _SC_NPROC_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011259 {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
Fred Draked86ed291999-12-15 15:34:33 +000011260#endif
Fred Drakec9680921999-12-13 16:37:25 +000011261#ifdef _SC_NZERO
Victor Stinner8c62be82010-05-06 00:08:46 +000011262 {"SC_NZERO", _SC_NZERO},
Fred Drakec9680921999-12-13 16:37:25 +000011263#endif
11264#ifdef _SC_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011265 {"SC_OPEN_MAX", _SC_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011266#endif
11267#ifdef _SC_PAGESIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011268 {"SC_PAGESIZE", _SC_PAGESIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011269#endif
11270#ifdef _SC_PAGE_SIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011271 {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011272#endif
11273#ifdef _SC_PASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011274 {"SC_PASS_MAX", _SC_PASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011275#endif
11276#ifdef _SC_PHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011277 {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011278#endif
11279#ifdef _SC_PII
Victor Stinner8c62be82010-05-06 00:08:46 +000011280 {"SC_PII", _SC_PII},
Fred Drakec9680921999-12-13 16:37:25 +000011281#endif
11282#ifdef _SC_PII_INTERNET
Victor Stinner8c62be82010-05-06 00:08:46 +000011283 {"SC_PII_INTERNET", _SC_PII_INTERNET},
Fred Drakec9680921999-12-13 16:37:25 +000011284#endif
11285#ifdef _SC_PII_INTERNET_DGRAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011286 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
Fred Drakec9680921999-12-13 16:37:25 +000011287#endif
11288#ifdef _SC_PII_INTERNET_STREAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011289 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
Fred Drakec9680921999-12-13 16:37:25 +000011290#endif
11291#ifdef _SC_PII_OSI
Victor Stinner8c62be82010-05-06 00:08:46 +000011292 {"SC_PII_OSI", _SC_PII_OSI},
Fred Drakec9680921999-12-13 16:37:25 +000011293#endif
11294#ifdef _SC_PII_OSI_CLTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011295 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
Fred Drakec9680921999-12-13 16:37:25 +000011296#endif
11297#ifdef _SC_PII_OSI_COTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011298 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
Fred Drakec9680921999-12-13 16:37:25 +000011299#endif
11300#ifdef _SC_PII_OSI_M
Victor Stinner8c62be82010-05-06 00:08:46 +000011301 {"SC_PII_OSI_M", _SC_PII_OSI_M},
Fred Drakec9680921999-12-13 16:37:25 +000011302#endif
11303#ifdef _SC_PII_SOCKET
Victor Stinner8c62be82010-05-06 00:08:46 +000011304 {"SC_PII_SOCKET", _SC_PII_SOCKET},
Fred Drakec9680921999-12-13 16:37:25 +000011305#endif
11306#ifdef _SC_PII_XTI
Victor Stinner8c62be82010-05-06 00:08:46 +000011307 {"SC_PII_XTI", _SC_PII_XTI},
Fred Drakec9680921999-12-13 16:37:25 +000011308#endif
11309#ifdef _SC_POLL
Victor Stinner8c62be82010-05-06 00:08:46 +000011310 {"SC_POLL", _SC_POLL},
Fred Drakec9680921999-12-13 16:37:25 +000011311#endif
11312#ifdef _SC_PRIORITIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011313 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011314#endif
11315#ifdef _SC_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011316 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011317#endif
11318#ifdef _SC_REALTIME_SIGNALS
Victor Stinner8c62be82010-05-06 00:08:46 +000011319 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
Fred Drakec9680921999-12-13 16:37:25 +000011320#endif
11321#ifdef _SC_RE_DUP_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011322 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011323#endif
11324#ifdef _SC_RTSIG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011325 {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011326#endif
11327#ifdef _SC_SAVED_IDS
Victor Stinner8c62be82010-05-06 00:08:46 +000011328 {"SC_SAVED_IDS", _SC_SAVED_IDS},
Fred Drakec9680921999-12-13 16:37:25 +000011329#endif
11330#ifdef _SC_SCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011331 {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011332#endif
11333#ifdef _SC_SCHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011334 {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011335#endif
11336#ifdef _SC_SELECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011337 {"SC_SELECT", _SC_SELECT},
Fred Drakec9680921999-12-13 16:37:25 +000011338#endif
11339#ifdef _SC_SEMAPHORES
Victor Stinner8c62be82010-05-06 00:08:46 +000011340 {"SC_SEMAPHORES", _SC_SEMAPHORES},
Fred Drakec9680921999-12-13 16:37:25 +000011341#endif
11342#ifdef _SC_SEM_NSEMS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011343 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011344#endif
11345#ifdef _SC_SEM_VALUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011346 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011347#endif
11348#ifdef _SC_SHARED_MEMORY_OBJECTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011349 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
Fred Drakec9680921999-12-13 16:37:25 +000011350#endif
11351#ifdef _SC_SHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011352 {"SC_SHRT_MAX", _SC_SHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011353#endif
11354#ifdef _SC_SHRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011355 {"SC_SHRT_MIN", _SC_SHRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011356#endif
11357#ifdef _SC_SIGQUEUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011358 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011359#endif
11360#ifdef _SC_SIGRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011361 {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011362#endif
11363#ifdef _SC_SIGRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011364 {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011365#endif
Fred Draked86ed291999-12-15 15:34:33 +000011366#ifdef _SC_SOFTPOWER
Victor Stinner8c62be82010-05-06 00:08:46 +000011367 {"SC_SOFTPOWER", _SC_SOFTPOWER},
Fred Draked86ed291999-12-15 15:34:33 +000011368#endif
Fred Drakec9680921999-12-13 16:37:25 +000011369#ifdef _SC_SPLIT_CACHE
Victor Stinner8c62be82010-05-06 00:08:46 +000011370 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
Fred Drakec9680921999-12-13 16:37:25 +000011371#endif
11372#ifdef _SC_SSIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011373 {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011374#endif
11375#ifdef _SC_STACK_PROT
Victor Stinner8c62be82010-05-06 00:08:46 +000011376 {"SC_STACK_PROT", _SC_STACK_PROT},
Fred Drakec9680921999-12-13 16:37:25 +000011377#endif
11378#ifdef _SC_STREAM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011379 {"SC_STREAM_MAX", _SC_STREAM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011380#endif
11381#ifdef _SC_SYNCHRONIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011382 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011383#endif
11384#ifdef _SC_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011385 {"SC_THREADS", _SC_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011386#endif
11387#ifdef _SC_THREAD_ATTR_STACKADDR
Victor Stinner8c62be82010-05-06 00:08:46 +000011388 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
Fred Drakec9680921999-12-13 16:37:25 +000011389#endif
11390#ifdef _SC_THREAD_ATTR_STACKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011391 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011392#endif
11393#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011394 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011395#endif
11396#ifdef _SC_THREAD_KEYS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011397 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011398#endif
11399#ifdef _SC_THREAD_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011400 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011401#endif
11402#ifdef _SC_THREAD_PRIO_INHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011403 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
Fred Drakec9680921999-12-13 16:37:25 +000011404#endif
11405#ifdef _SC_THREAD_PRIO_PROTECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011406 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
Fred Drakec9680921999-12-13 16:37:25 +000011407#endif
11408#ifdef _SC_THREAD_PROCESS_SHARED
Victor Stinner8c62be82010-05-06 00:08:46 +000011409 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
Fred Drakec9680921999-12-13 16:37:25 +000011410#endif
11411#ifdef _SC_THREAD_SAFE_FUNCTIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011412 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011413#endif
11414#ifdef _SC_THREAD_STACK_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011415 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011416#endif
11417#ifdef _SC_THREAD_THREADS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011418 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011419#endif
11420#ifdef _SC_TIMERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011421 {"SC_TIMERS", _SC_TIMERS},
Fred Drakec9680921999-12-13 16:37:25 +000011422#endif
11423#ifdef _SC_TIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011424 {"SC_TIMER_MAX", _SC_TIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011425#endif
11426#ifdef _SC_TTY_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011427 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011428#endif
11429#ifdef _SC_TZNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011430 {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011431#endif
11432#ifdef _SC_T_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011433 {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011434#endif
11435#ifdef _SC_UCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011436 {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011437#endif
11438#ifdef _SC_UINT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011439 {"SC_UINT_MAX", _SC_UINT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011440#endif
11441#ifdef _SC_UIO_MAXIOV
Victor Stinner8c62be82010-05-06 00:08:46 +000011442 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
Fred Drakec9680921999-12-13 16:37:25 +000011443#endif
11444#ifdef _SC_ULONG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011445 {"SC_ULONG_MAX", _SC_ULONG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011446#endif
11447#ifdef _SC_USHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011448 {"SC_USHRT_MAX", _SC_USHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011449#endif
11450#ifdef _SC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011451 {"SC_VERSION", _SC_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011452#endif
11453#ifdef _SC_WORD_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011454 {"SC_WORD_BIT", _SC_WORD_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011455#endif
11456#ifdef _SC_XBS5_ILP32_OFF32
Victor Stinner8c62be82010-05-06 00:08:46 +000011457 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
Fred Drakec9680921999-12-13 16:37:25 +000011458#endif
11459#ifdef _SC_XBS5_ILP32_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011460 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011461#endif
11462#ifdef _SC_XBS5_LP64_OFF64
Victor Stinner8c62be82010-05-06 00:08:46 +000011463 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
Fred Drakec9680921999-12-13 16:37:25 +000011464#endif
11465#ifdef _SC_XBS5_LPBIG_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011466 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011467#endif
11468#ifdef _SC_XOPEN_CRYPT
Victor Stinner8c62be82010-05-06 00:08:46 +000011469 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
Fred Drakec9680921999-12-13 16:37:25 +000011470#endif
11471#ifdef _SC_XOPEN_ENH_I18N
Victor Stinner8c62be82010-05-06 00:08:46 +000011472 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
Fred Drakec9680921999-12-13 16:37:25 +000011473#endif
11474#ifdef _SC_XOPEN_LEGACY
Victor Stinner8c62be82010-05-06 00:08:46 +000011475 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
Fred Drakec9680921999-12-13 16:37:25 +000011476#endif
11477#ifdef _SC_XOPEN_REALTIME
Victor Stinner8c62be82010-05-06 00:08:46 +000011478 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
Fred Drakec9680921999-12-13 16:37:25 +000011479#endif
11480#ifdef _SC_XOPEN_REALTIME_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011481 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011482#endif
11483#ifdef _SC_XOPEN_SHM
Victor Stinner8c62be82010-05-06 00:08:46 +000011484 {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
Fred Drakec9680921999-12-13 16:37:25 +000011485#endif
11486#ifdef _SC_XOPEN_UNIX
Victor Stinner8c62be82010-05-06 00:08:46 +000011487 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
Fred Drakec9680921999-12-13 16:37:25 +000011488#endif
11489#ifdef _SC_XOPEN_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011490 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011491#endif
11492#ifdef _SC_XOPEN_XCU_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011493 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011494#endif
11495#ifdef _SC_XOPEN_XPG2
Victor Stinner8c62be82010-05-06 00:08:46 +000011496 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
Fred Drakec9680921999-12-13 16:37:25 +000011497#endif
11498#ifdef _SC_XOPEN_XPG3
Victor Stinner8c62be82010-05-06 00:08:46 +000011499 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
Fred Drakec9680921999-12-13 16:37:25 +000011500#endif
11501#ifdef _SC_XOPEN_XPG4
Victor Stinner8c62be82010-05-06 00:08:46 +000011502 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
Fred Drakec9680921999-12-13 16:37:25 +000011503#endif
11504};
11505
11506static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011507conv_sysconf_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011508{
11509 return conv_confname(arg, valuep, posix_constants_sysconf,
11510 sizeof(posix_constants_sysconf)
11511 / sizeof(struct constdef));
11512}
11513
Larry Hastings2f936352014-08-05 14:04:04 +100011514
11515/*[clinic input]
11516os.sysconf -> long
11517 name: sysconf_confname
11518 /
11519
11520Return an integer-valued system configuration variable.
11521[clinic start generated code]*/
11522
Larry Hastings2f936352014-08-05 14:04:04 +100011523static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011524os_sysconf_impl(PyObject *module, int name)
11525/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011526{
11527 long value;
11528
11529 errno = 0;
11530 value = sysconf(name);
11531 if (value == -1 && errno != 0)
11532 posix_error();
11533 return value;
11534}
11535#endif /* HAVE_SYSCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011536
11537
Fred Drakebec628d1999-12-15 18:31:10 +000011538/* This code is used to ensure that the tables of configuration value names
Serhiy Storchaka56a6d852014-12-01 18:28:43 +020011539 * are in sorted order as required by conv_confname(), and also to build
Fred Drakebec628d1999-12-15 18:31:10 +000011540 * the exported dictionaries that are used to publish information about the
11541 * names available on the host platform.
11542 *
11543 * Sorting the table at runtime ensures that the table is properly ordered
11544 * when used, even for platforms we're not able to test on. It also makes
11545 * it easier to add additional entries to the tables.
Fred Draked86ed291999-12-15 15:34:33 +000011546 */
Fred Drakebec628d1999-12-15 18:31:10 +000011547
11548static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011549cmp_constdefs(const void *v1, const void *v2)
Fred Drakebec628d1999-12-15 18:31:10 +000011550{
11551 const struct constdef *c1 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011552 (const struct constdef *) v1;
Fred Drakebec628d1999-12-15 18:31:10 +000011553 const struct constdef *c2 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011554 (const struct constdef *) v2;
Fred Drakebec628d1999-12-15 18:31:10 +000011555
11556 return strcmp(c1->name, c2->name);
11557}
11558
11559static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011560setup_confname_table(struct constdef *table, size_t tablesize,
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011561 const char *tablename, PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011562{
Fred Drakebec628d1999-12-15 18:31:10 +000011563 PyObject *d = NULL;
Barry Warsaw3155db32000-04-13 15:20:40 +000011564 size_t i;
Fred Drakebec628d1999-12-15 18:31:10 +000011565
11566 qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
11567 d = PyDict_New();
Barry Warsaw3155db32000-04-13 15:20:40 +000011568 if (d == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +000011569 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011570
Barry Warsaw3155db32000-04-13 15:20:40 +000011571 for (i=0; i < tablesize; ++i) {
Victor Stinner8c62be82010-05-06 00:08:46 +000011572 PyObject *o = PyLong_FromLong(table[i].value);
11573 if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
11574 Py_XDECREF(o);
11575 Py_DECREF(d);
11576 return -1;
11577 }
11578 Py_DECREF(o);
Fred Draked86ed291999-12-15 15:34:33 +000011579 }
Fred Drake4d1e64b2002-04-15 19:40:07 +000011580 return PyModule_AddObject(module, tablename, d);
Fred Draked86ed291999-12-15 15:34:33 +000011581}
11582
Fred Drakebec628d1999-12-15 18:31:10 +000011583/* Return -1 on failure, 0 on success. */
11584static int
Fred Drake4d1e64b2002-04-15 19:40:07 +000011585setup_confname_tables(PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011586{
11587#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
Fred Drakebec628d1999-12-15 18:31:10 +000011588 if (setup_confname_table(posix_constants_pathconf,
Fred Draked86ed291999-12-15 15:34:33 +000011589 sizeof(posix_constants_pathconf)
11590 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011591 "pathconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011592 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011593#endif
11594#ifdef HAVE_CONFSTR
Fred Drakebec628d1999-12-15 18:31:10 +000011595 if (setup_confname_table(posix_constants_confstr,
Fred Draked86ed291999-12-15 15:34:33 +000011596 sizeof(posix_constants_confstr)
11597 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011598 "confstr_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011599 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011600#endif
11601#ifdef HAVE_SYSCONF
Fred Drakebec628d1999-12-15 18:31:10 +000011602 if (setup_confname_table(posix_constants_sysconf,
Fred Draked86ed291999-12-15 15:34:33 +000011603 sizeof(posix_constants_sysconf)
11604 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011605 "sysconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011606 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011607#endif
Fred Drakebec628d1999-12-15 18:31:10 +000011608 return 0;
Fred Draked86ed291999-12-15 15:34:33 +000011609}
Fred Draked86ed291999-12-15 15:34:33 +000011610
11611
Larry Hastings2f936352014-08-05 14:04:04 +100011612/*[clinic input]
11613os.abort
11614
11615Abort the interpreter immediately.
11616
11617This function 'dumps core' or otherwise fails in the hardest way possible
11618on the hosting operating system. This function never returns.
11619[clinic start generated code]*/
11620
Larry Hastings2f936352014-08-05 14:04:04 +100011621static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011622os_abort_impl(PyObject *module)
11623/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011624{
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011625 abort();
11626 /*NOTREACHED*/
Victor Stinner9a2329f2016-12-05 17:56:36 +010011627#ifndef __clang__
11628 /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
11629 GCC emits a warning without "return NULL;" (compiler bug?), but Clang
11630 is smarter and emits a warning on the return. */
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011631 Py_FatalError("abort() called from Python code didn't abort!");
11632 return NULL;
Victor Stinner9a2329f2016-12-05 17:56:36 +010011633#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011634}
Fred Drakebec628d1999-12-15 18:31:10 +000011635
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011636#ifdef MS_WINDOWS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011637/* Grab ShellExecute dynamically from shell32 */
11638static int has_ShellExecute = -1;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011639static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
11640 LPCWSTR, INT);
11641static int
11642check_ShellExecute()
11643{
11644 HINSTANCE hShell32;
11645
11646 /* only recheck */
11647 if (-1 == has_ShellExecute) {
11648 Py_BEGIN_ALLOW_THREADS
Victor Stinnera9912152017-10-13 13:46:57 -070011649 /* Security note: this call is not vulnerable to "DLL hijacking".
11650 SHELL32 is part of "KnownDLLs" and so Windows always load
11651 the system SHELL32.DLL, even if there is another SHELL32.DLL
11652 in the DLL search path. */
Steve Dower7d0e0c92015-01-24 08:18:24 -080011653 hShell32 = LoadLibraryW(L"SHELL32");
Steve Dower7d0e0c92015-01-24 08:18:24 -080011654 if (hShell32) {
Steve Dower7d0e0c92015-01-24 08:18:24 -080011655 *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
11656 "ShellExecuteW");
Steve Dowercc16be82016-09-08 10:35:16 -070011657 has_ShellExecute = Py_ShellExecuteW != NULL;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011658 } else {
11659 has_ShellExecute = 0;
11660 }
Tony Roberts4860f012019-02-02 18:16:42 +010011661 Py_END_ALLOW_THREADS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011662 }
11663 return has_ShellExecute;
11664}
11665
11666
Steve Dowercc16be82016-09-08 10:35:16 -070011667/*[clinic input]
11668os.startfile
11669 filepath: path_t
11670 operation: Py_UNICODE = NULL
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +000011671
Steve Dowercc16be82016-09-08 10:35:16 -070011672Start a file with its associated application.
11673
11674When "operation" is not specified or "open", this acts like
11675double-clicking the file in Explorer, or giving the file name as an
11676argument to the DOS "start" command: the file is opened with whatever
11677application (if any) its extension is associated.
11678When another "operation" is given, it specifies what should be done with
11679the file. A typical operation is "print".
11680
11681startfile returns as soon as the associated application is launched.
11682There is no option to wait for the application to close, and no way
11683to retrieve the application's exit status.
11684
11685The filepath is relative to the current directory. If you want to use
11686an absolute path, make sure the first character is not a slash ("/");
11687the underlying Win32 ShellExecute function doesn't work if it is.
11688[clinic start generated code]*/
11689
11690static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +020011691os_startfile_impl(PyObject *module, path_t *filepath,
11692 const Py_UNICODE *operation)
Serhiy Storchaka279f4462019-09-14 12:24:05 +030011693/*[clinic end generated code: output=66dc311c94d50797 input=c940888a5390f039]*/
Steve Dowercc16be82016-09-08 10:35:16 -070011694{
11695 HINSTANCE rc;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011696
11697 if(!check_ShellExecute()) {
11698 /* If the OS doesn't have ShellExecute, return a
11699 NotImplementedError. */
11700 return PyErr_Format(PyExc_NotImplementedError,
11701 "startfile not available on this platform");
11702 }
11703
Victor Stinner8c62be82010-05-06 00:08:46 +000011704 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -070011705 rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
Steve Dower7d0e0c92015-01-24 08:18:24 -080011706 NULL, NULL, SW_SHOWNORMAL);
Victor Stinner8c62be82010-05-06 00:08:46 +000011707 Py_END_ALLOW_THREADS
11708
Victor Stinner8c62be82010-05-06 00:08:46 +000011709 if (rc <= (HINSTANCE)32) {
Steve Dowercc16be82016-09-08 10:35:16 -070011710 win32_error_object("startfile", filepath->object);
Victor Stinnereb5657a2011-09-30 01:44:27 +020011711 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000011712 }
Steve Dowercc16be82016-09-08 10:35:16 -070011713 Py_RETURN_NONE;
Tim Petersf58a7aa2000-09-22 10:05:54 +000011714}
Larry Hastings2f936352014-08-05 14:04:04 +100011715#endif /* MS_WINDOWS */
11716
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011717
Martin v. Löwis438b5342002-12-27 10:16:42 +000011718#ifdef HAVE_GETLOADAVG
Larry Hastings2f936352014-08-05 14:04:04 +100011719/*[clinic input]
11720os.getloadavg
11721
11722Return average recent system load information.
11723
11724Return the number of processes in the system run queue averaged over
11725the last 1, 5, and 15 minutes as a tuple of three floats.
11726Raises OSError if the load average was unobtainable.
11727[clinic start generated code]*/
11728
Larry Hastings2f936352014-08-05 14:04:04 +100011729static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011730os_getloadavg_impl(PyObject *module)
11731/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
Martin v. Löwis438b5342002-12-27 10:16:42 +000011732{
11733 double loadavg[3];
Martin v. Löwis438b5342002-12-27 10:16:42 +000011734 if (getloadavg(loadavg, 3)!=3) {
Stefan Krah0e803b32010-11-26 16:16:47 +000011735 PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
11736 return NULL;
Martin v. Löwis438b5342002-12-27 10:16:42 +000011737 } else
Stefan Krah0e803b32010-11-26 16:16:47 +000011738 return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
Martin v. Löwis438b5342002-12-27 10:16:42 +000011739}
Larry Hastings2f936352014-08-05 14:04:04 +100011740#endif /* HAVE_GETLOADAVG */
Martin v. Löwis438b5342002-12-27 10:16:42 +000011741
Larry Hastings2f936352014-08-05 14:04:04 +100011742
11743/*[clinic input]
11744os.device_encoding
11745 fd: int
11746
11747Return a string describing the encoding of a terminal's file descriptor.
11748
11749The file descriptor must be attached to a terminal.
11750If the device is not a terminal, return None.
11751[clinic start generated code]*/
11752
Larry Hastings2f936352014-08-05 14:04:04 +100011753static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011754os_device_encoding_impl(PyObject *module, int fd)
11755/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011756{
Brett Cannonefb00c02012-02-29 18:31:31 -050011757 return _Py_device_encoding(fd);
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +000011758}
11759
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011760
Larry Hastings2f936352014-08-05 14:04:04 +100011761#ifdef HAVE_SETRESUID
11762/*[clinic input]
11763os.setresuid
11764
11765 ruid: uid_t
11766 euid: uid_t
11767 suid: uid_t
11768 /
11769
11770Set the current process's real, effective, and saved user ids.
11771[clinic start generated code]*/
11772
Larry Hastings2f936352014-08-05 14:04:04 +100011773static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011774os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
11775/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011776{
Victor Stinner8c62be82010-05-06 00:08:46 +000011777 if (setresuid(ruid, euid, suid) < 0)
11778 return posix_error();
11779 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011780}
Larry Hastings2f936352014-08-05 14:04:04 +100011781#endif /* HAVE_SETRESUID */
11782
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011783
11784#ifdef HAVE_SETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011785/*[clinic input]
11786os.setresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011787
Larry Hastings2f936352014-08-05 14:04:04 +100011788 rgid: gid_t
11789 egid: gid_t
11790 sgid: gid_t
11791 /
11792
11793Set the current process's real, effective, and saved group ids.
11794[clinic start generated code]*/
11795
Larry Hastings2f936352014-08-05 14:04:04 +100011796static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011797os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
11798/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011799{
Victor Stinner8c62be82010-05-06 00:08:46 +000011800 if (setresgid(rgid, egid, sgid) < 0)
11801 return posix_error();
11802 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011803}
Larry Hastings2f936352014-08-05 14:04:04 +100011804#endif /* HAVE_SETRESGID */
11805
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011806
11807#ifdef HAVE_GETRESUID
Larry Hastings2f936352014-08-05 14:04:04 +100011808/*[clinic input]
11809os.getresuid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011810
Larry Hastings2f936352014-08-05 14:04:04 +100011811Return a tuple of the current process's real, effective, and saved user ids.
11812[clinic start generated code]*/
11813
Larry Hastings2f936352014-08-05 14:04:04 +100011814static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011815os_getresuid_impl(PyObject *module)
11816/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011817{
Victor Stinner8c62be82010-05-06 00:08:46 +000011818 uid_t ruid, euid, suid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011819 if (getresuid(&ruid, &euid, &suid) < 0)
11820 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011821 return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
11822 _PyLong_FromUid(euid),
11823 _PyLong_FromUid(suid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011824}
Larry Hastings2f936352014-08-05 14:04:04 +100011825#endif /* HAVE_GETRESUID */
11826
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011827
11828#ifdef HAVE_GETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011829/*[clinic input]
11830os.getresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011831
Larry Hastings2f936352014-08-05 14:04:04 +100011832Return a tuple of the current process's real, effective, and saved group ids.
11833[clinic start generated code]*/
11834
Larry Hastings2f936352014-08-05 14:04:04 +100011835static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011836os_getresgid_impl(PyObject *module)
11837/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011838{
11839 gid_t rgid, egid, sgid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011840 if (getresgid(&rgid, &egid, &sgid) < 0)
11841 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011842 return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
11843 _PyLong_FromGid(egid),
11844 _PyLong_FromGid(sgid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011845}
Larry Hastings2f936352014-08-05 14:04:04 +100011846#endif /* HAVE_GETRESGID */
11847
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011848
Benjamin Peterson9428d532011-09-14 11:45:52 -040011849#ifdef USE_XATTRS
Larry Hastings2f936352014-08-05 14:04:04 +100011850/*[clinic input]
11851os.getxattr
Benjamin Peterson799bd802011-08-31 22:15:17 -040011852
Larry Hastings2f936352014-08-05 14:04:04 +100011853 path: path_t(allow_fd=True)
11854 attribute: path_t
11855 *
11856 follow_symlinks: bool = True
11857
11858Return the value of extended attribute attribute on path.
11859
BNMetricsb9427072018-11-02 15:20:19 +000011860path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011861If follow_symlinks is False, and the last element of the path is a symbolic
11862 link, getxattr will examine the symbolic link itself instead of the file
11863 the link points to.
11864
11865[clinic start generated code]*/
11866
Larry Hastings2f936352014-08-05 14:04:04 +100011867static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011868os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011869 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011870/*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011871{
11872 Py_ssize_t i;
11873 PyObject *buffer = NULL;
11874
11875 if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
11876 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011877
Larry Hastings9cf065c2012-06-22 16:30:09 -070011878 for (i = 0; ; i++) {
11879 void *ptr;
11880 ssize_t result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020011881 static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
Larry Hastings9cf065c2012-06-22 16:30:09 -070011882 Py_ssize_t buffer_size = buffer_sizes[i];
11883 if (!buffer_size) {
Larry Hastings2f936352014-08-05 14:04:04 +100011884 path_error(path);
11885 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011886 }
11887 buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
11888 if (!buffer)
Larry Hastings2f936352014-08-05 14:04:04 +100011889 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011890 ptr = PyBytes_AS_STRING(buffer);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011891
Larry Hastings9cf065c2012-06-22 16:30:09 -070011892 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011893 if (path->fd >= 0)
11894 result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011895 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011896 result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011897 else
Larry Hastings2f936352014-08-05 14:04:04 +100011898 result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011899 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011900
Larry Hastings9cf065c2012-06-22 16:30:09 -070011901 if (result < 0) {
11902 Py_DECREF(buffer);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011903 if (errno == ERANGE)
11904 continue;
Larry Hastings2f936352014-08-05 14:04:04 +100011905 path_error(path);
11906 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011907 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011908
Larry Hastings9cf065c2012-06-22 16:30:09 -070011909 if (result != buffer_size) {
11910 /* Can only shrink. */
11911 _PyBytes_Resize(&buffer, result);
11912 }
11913 break;
11914 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011915
Larry Hastings9cf065c2012-06-22 16:30:09 -070011916 return buffer;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011917}
11918
Larry Hastings2f936352014-08-05 14:04:04 +100011919
11920/*[clinic input]
11921os.setxattr
11922
11923 path: path_t(allow_fd=True)
11924 attribute: path_t
11925 value: Py_buffer
11926 flags: int = 0
11927 *
11928 follow_symlinks: bool = True
11929
11930Set extended attribute attribute on path to value.
11931
BNMetricsb9427072018-11-02 15:20:19 +000011932path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011933If follow_symlinks is False, and the last element of the path is a symbolic
11934 link, setxattr will modify the symbolic link itself instead of the file
11935 the link points to.
11936
11937[clinic start generated code]*/
11938
Benjamin Peterson799bd802011-08-31 22:15:17 -040011939static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011940os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011941 Py_buffer *value, int flags, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011942/*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
Benjamin Peterson799bd802011-08-31 22:15:17 -040011943{
Larry Hastings2f936352014-08-05 14:04:04 +100011944 ssize_t result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011945
Larry Hastings2f936352014-08-05 14:04:04 +100011946 if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
Benjamin Peterson799bd802011-08-31 22:15:17 -040011947 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011948
Benjamin Peterson799bd802011-08-31 22:15:17 -040011949 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011950 if (path->fd > -1)
11951 result = fsetxattr(path->fd, attribute->narrow,
11952 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011953 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011954 result = setxattr(path->narrow, attribute->narrow,
11955 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011956 else
Larry Hastings2f936352014-08-05 14:04:04 +100011957 result = lsetxattr(path->narrow, attribute->narrow,
11958 value->buf, value->len, flags);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011959 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011960
Larry Hastings9cf065c2012-06-22 16:30:09 -070011961 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100011962 path_error(path);
11963 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011964 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011965
Larry Hastings2f936352014-08-05 14:04:04 +100011966 Py_RETURN_NONE;
11967}
11968
11969
11970/*[clinic input]
11971os.removexattr
11972
11973 path: path_t(allow_fd=True)
11974 attribute: path_t
11975 *
11976 follow_symlinks: bool = True
11977
11978Remove extended attribute attribute on path.
11979
BNMetricsb9427072018-11-02 15:20:19 +000011980path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011981If follow_symlinks is False, and the last element of the path is a symbolic
11982 link, removexattr will modify the symbolic link itself instead of the file
11983 the link points to.
11984
11985[clinic start generated code]*/
11986
Larry Hastings2f936352014-08-05 14:04:04 +100011987static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011988os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011989 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011990/*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011991{
11992 ssize_t result;
11993
11994 if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
11995 return NULL;
11996
11997 Py_BEGIN_ALLOW_THREADS;
11998 if (path->fd > -1)
11999 result = fremovexattr(path->fd, attribute->narrow);
12000 else if (follow_symlinks)
12001 result = removexattr(path->narrow, attribute->narrow);
12002 else
12003 result = lremovexattr(path->narrow, attribute->narrow);
12004 Py_END_ALLOW_THREADS;
12005
12006 if (result) {
12007 return path_error(path);
12008 }
12009
12010 Py_RETURN_NONE;
12011}
12012
12013
12014/*[clinic input]
12015os.listxattr
12016
12017 path: path_t(allow_fd=True, nullable=True) = None
12018 *
12019 follow_symlinks: bool = True
12020
12021Return a list of extended attributes on path.
12022
BNMetricsb9427072018-11-02 15:20:19 +000012023path may be either None, a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012024if path is None, listxattr will examine the current directory.
12025If follow_symlinks is False, and the last element of the path is a symbolic
12026 link, listxattr will examine the symbolic link itself instead of the file
12027 the link points to.
12028[clinic start generated code]*/
12029
Larry Hastings2f936352014-08-05 14:04:04 +100012030static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012031os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012032/*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012033{
Larry Hastings9cf065c2012-06-22 16:30:09 -070012034 Py_ssize_t i;
12035 PyObject *result = NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100012036 const char *name;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012037 char *buffer = NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012038
Larry Hastings2f936352014-08-05 14:04:04 +100012039 if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
Larry Hastings9cf065c2012-06-22 16:30:09 -070012040 goto exit;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012041
Larry Hastings2f936352014-08-05 14:04:04 +100012042 name = path->narrow ? path->narrow : ".";
12043
Larry Hastings9cf065c2012-06-22 16:30:09 -070012044 for (i = 0; ; i++) {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012045 const char *start, *trace, *end;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012046 ssize_t length;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012047 static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
Larry Hastings9cf065c2012-06-22 16:30:09 -070012048 Py_ssize_t buffer_size = buffer_sizes[i];
12049 if (!buffer_size) {
Christian Heimes3b9493b2012-09-23 16:11:15 +020012050 /* ERANGE */
Larry Hastings2f936352014-08-05 14:04:04 +100012051 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012052 break;
12053 }
12054 buffer = PyMem_MALLOC(buffer_size);
12055 if (!buffer) {
12056 PyErr_NoMemory();
12057 break;
12058 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012059
Larry Hastings9cf065c2012-06-22 16:30:09 -070012060 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012061 if (path->fd > -1)
12062 length = flistxattr(path->fd, buffer, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012063 else if (follow_symlinks)
12064 length = listxattr(name, buffer, buffer_size);
12065 else
12066 length = llistxattr(name, buffer, buffer_size);
12067 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012068
Larry Hastings9cf065c2012-06-22 16:30:09 -070012069 if (length < 0) {
Antoine Pitrou7f987392013-05-13 19:46:29 +020012070 if (errno == ERANGE) {
12071 PyMem_FREE(buffer);
Benjamin Petersondedac522013-05-13 19:55:40 -050012072 buffer = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012073 continue;
Antoine Pitrou7f987392013-05-13 19:46:29 +020012074 }
Larry Hastings2f936352014-08-05 14:04:04 +100012075 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012076 break;
12077 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012078
Larry Hastings9cf065c2012-06-22 16:30:09 -070012079 result = PyList_New(0);
12080 if (!result) {
12081 goto exit;
12082 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012083
Larry Hastings9cf065c2012-06-22 16:30:09 -070012084 end = buffer + length;
12085 for (trace = start = buffer; trace != end; trace++) {
12086 if (!*trace) {
12087 int error;
12088 PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
12089 trace - start);
12090 if (!attribute) {
12091 Py_DECREF(result);
12092 result = NULL;
12093 goto exit;
12094 }
12095 error = PyList_Append(result, attribute);
12096 Py_DECREF(attribute);
12097 if (error) {
12098 Py_DECREF(result);
12099 result = NULL;
12100 goto exit;
12101 }
12102 start = trace + 1;
12103 }
12104 }
12105 break;
12106 }
12107exit:
Larry Hastings9cf065c2012-06-22 16:30:09 -070012108 if (buffer)
12109 PyMem_FREE(buffer);
12110 return result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012111}
Benjamin Peterson9428d532011-09-14 11:45:52 -040012112#endif /* USE_XATTRS */
Benjamin Peterson799bd802011-08-31 22:15:17 -040012113
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012114
Larry Hastings2f936352014-08-05 14:04:04 +100012115/*[clinic input]
12116os.urandom
12117
12118 size: Py_ssize_t
12119 /
12120
12121Return a bytes object containing random bytes suitable for cryptographic use.
12122[clinic start generated code]*/
12123
Larry Hastings2f936352014-08-05 14:04:04 +100012124static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012125os_urandom_impl(PyObject *module, Py_ssize_t size)
12126/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012127{
12128 PyObject *bytes;
12129 int result;
12130
Georg Brandl2fb477c2012-02-21 00:33:36 +010012131 if (size < 0)
12132 return PyErr_Format(PyExc_ValueError,
12133 "negative argument not allowed");
Larry Hastings2f936352014-08-05 14:04:04 +100012134 bytes = PyBytes_FromStringAndSize(NULL, size);
12135 if (bytes == NULL)
Georg Brandl2fb477c2012-02-21 00:33:36 +010012136 return NULL;
12137
Victor Stinnere66987e2016-09-06 16:33:52 -070012138 result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
Larry Hastings2f936352014-08-05 14:04:04 +100012139 if (result == -1) {
12140 Py_DECREF(bytes);
Georg Brandl2fb477c2012-02-21 00:33:36 +010012141 return NULL;
12142 }
Larry Hastings2f936352014-08-05 14:04:04 +100012143 return bytes;
Georg Brandl2fb477c2012-02-21 00:33:36 +010012144}
12145
Zackery Spytz43fdbd22019-05-29 13:57:07 -060012146#ifdef HAVE_MEMFD_CREATE
12147/*[clinic input]
12148os.memfd_create
12149
12150 name: FSConverter
12151 flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
12152
12153[clinic start generated code]*/
12154
12155static PyObject *
12156os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
12157/*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
12158{
12159 int fd;
12160 const char *bytes = PyBytes_AS_STRING(name);
12161 Py_BEGIN_ALLOW_THREADS
12162 fd = memfd_create(bytes, flags);
12163 Py_END_ALLOW_THREADS
12164 if (fd == -1) {
12165 return PyErr_SetFromErrno(PyExc_OSError);
12166 }
12167 return PyLong_FromLong(fd);
12168}
12169#endif
12170
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012171/* Terminal size querying */
12172
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012173PyDoc_STRVAR(TerminalSize_docstring,
12174 "A tuple of (columns, lines) for holding terminal window size");
12175
12176static PyStructSequence_Field TerminalSize_fields[] = {
12177 {"columns", "width of the terminal window in characters"},
12178 {"lines", "height of the terminal window in characters"},
12179 {NULL, NULL}
12180};
12181
12182static PyStructSequence_Desc TerminalSize_desc = {
12183 "os.terminal_size",
12184 TerminalSize_docstring,
12185 TerminalSize_fields,
12186 2,
12187};
12188
12189#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
Larry Hastings2f936352014-08-05 14:04:04 +100012190/* AC 3.5: fd should accept None */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012191PyDoc_STRVAR(termsize__doc__,
12192 "Return the size of the terminal window as (columns, lines).\n" \
12193 "\n" \
12194 "The optional argument fd (default standard output) specifies\n" \
12195 "which file descriptor should be queried.\n" \
12196 "\n" \
12197 "If the file descriptor is not connected to a terminal, an OSError\n" \
12198 "is thrown.\n" \
12199 "\n" \
12200 "This function will only be defined if an implementation is\n" \
12201 "available for this system.\n" \
12202 "\n" \
oldkaa0735f2018-02-02 16:52:55 +080012203 "shutil.get_terminal_size is the high-level function which should\n" \
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012204 "normally be used, os.get_terminal_size is the low-level implementation.");
12205
12206static PyObject*
12207get_terminal_size(PyObject *self, PyObject *args)
12208{
12209 int columns, lines;
12210 PyObject *termsize;
12211
12212 int fd = fileno(stdout);
12213 /* Under some conditions stdout may not be connected and
12214 * fileno(stdout) may point to an invalid file descriptor. For example
12215 * GUI apps don't have valid standard streams by default.
12216 *
12217 * If this happens, and the optional fd argument is not present,
12218 * the ioctl below will fail returning EBADF. This is what we want.
12219 */
12220
12221 if (!PyArg_ParseTuple(args, "|i", &fd))
12222 return NULL;
12223
12224#ifdef TERMSIZE_USE_IOCTL
12225 {
12226 struct winsize w;
12227 if (ioctl(fd, TIOCGWINSZ, &w))
12228 return PyErr_SetFromErrno(PyExc_OSError);
12229 columns = w.ws_col;
12230 lines = w.ws_row;
12231 }
12232#endif /* TERMSIZE_USE_IOCTL */
12233
12234#ifdef TERMSIZE_USE_CONIO
12235 {
12236 DWORD nhandle;
12237 HANDLE handle;
12238 CONSOLE_SCREEN_BUFFER_INFO csbi;
12239 switch (fd) {
12240 case 0: nhandle = STD_INPUT_HANDLE;
12241 break;
12242 case 1: nhandle = STD_OUTPUT_HANDLE;
12243 break;
12244 case 2: nhandle = STD_ERROR_HANDLE;
12245 break;
12246 default:
12247 return PyErr_Format(PyExc_ValueError, "bad file descriptor");
12248 }
12249 handle = GetStdHandle(nhandle);
12250 if (handle == NULL)
12251 return PyErr_Format(PyExc_OSError, "handle cannot be retrieved");
12252 if (handle == INVALID_HANDLE_VALUE)
12253 return PyErr_SetFromWindowsErr(0);
12254
12255 if (!GetConsoleScreenBufferInfo(handle, &csbi))
12256 return PyErr_SetFromWindowsErr(0);
12257
12258 columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
12259 lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
12260 }
12261#endif /* TERMSIZE_USE_CONIO */
12262
Eddie Elizondob3966632019-11-05 07:16:14 -080012263 PyObject *TerminalSizeType = _posixstate(self)->TerminalSizeType;
12264 termsize = PyStructSequence_New((PyTypeObject *)TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012265 if (termsize == NULL)
12266 return NULL;
12267 PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
12268 PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
12269 if (PyErr_Occurred()) {
12270 Py_DECREF(termsize);
12271 return NULL;
12272 }
12273 return termsize;
12274}
12275#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
12276
Larry Hastings2f936352014-08-05 14:04:04 +100012277
12278/*[clinic input]
12279os.cpu_count
12280
Charles-François Natali80d62e62015-08-13 20:37:08 +010012281Return the number of CPUs in the system; return None if indeterminable.
12282
12283This number is not equivalent to the number of CPUs the current process can
12284use. The number of usable CPUs can be obtained with
12285``len(os.sched_getaffinity(0))``
Larry Hastings2f936352014-08-05 14:04:04 +100012286[clinic start generated code]*/
12287
Larry Hastings2f936352014-08-05 14:04:04 +100012288static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012289os_cpu_count_impl(PyObject *module)
Serhiy Storchaka2954f832016-07-07 18:20:03 +030012290/*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012291{
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012292 int ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012293#ifdef MS_WINDOWS
Steve Doweraa929272019-09-11 16:15:39 +010012294 ncpu = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012295#elif defined(__hpux)
12296 ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
12297#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
12298 ncpu = sysconf(_SC_NPROCESSORS_ONLN);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012299#elif defined(__DragonFly__) || \
12300 defined(__OpenBSD__) || \
12301 defined(__FreeBSD__) || \
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012302 defined(__NetBSD__) || \
12303 defined(__APPLE__)
Charles-Francois Natali7c4f8da2013-05-20 17:40:32 +020012304 int mib[2];
12305 size_t len = sizeof(ncpu);
12306 mib[0] = CTL_HW;
12307 mib[1] = HW_NCPU;
12308 if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
12309 ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012310#endif
12311 if (ncpu >= 1)
12312 return PyLong_FromLong(ncpu);
12313 else
12314 Py_RETURN_NONE;
12315}
12316
Victor Stinnerdaf45552013-08-28 00:53:59 +020012317
Larry Hastings2f936352014-08-05 14:04:04 +100012318/*[clinic input]
12319os.get_inheritable -> bool
12320
12321 fd: int
12322 /
12323
12324Get the close-on-exe flag of the specified file descriptor.
12325[clinic start generated code]*/
12326
Larry Hastings2f936352014-08-05 14:04:04 +100012327static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012328os_get_inheritable_impl(PyObject *module, int fd)
12329/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012330{
Steve Dower8fc89802015-04-12 00:26:27 -040012331 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -040012332 _Py_BEGIN_SUPPRESS_IPH
12333 return_value = _Py_get_inheritable(fd);
12334 _Py_END_SUPPRESS_IPH
12335 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +100012336}
12337
12338
12339/*[clinic input]
12340os.set_inheritable
12341 fd: int
12342 inheritable: int
12343 /
12344
12345Set the inheritable flag of the specified file descriptor.
12346[clinic start generated code]*/
12347
Larry Hastings2f936352014-08-05 14:04:04 +100012348static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012349os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
12350/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
Victor Stinnerdaf45552013-08-28 00:53:59 +020012351{
Steve Dower8fc89802015-04-12 00:26:27 -040012352 int result;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012353
Steve Dower8fc89802015-04-12 00:26:27 -040012354 _Py_BEGIN_SUPPRESS_IPH
12355 result = _Py_set_inheritable(fd, inheritable, NULL);
12356 _Py_END_SUPPRESS_IPH
12357 if (result < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +020012358 return NULL;
12359 Py_RETURN_NONE;
12360}
12361
12362
12363#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100012364/*[clinic input]
12365os.get_handle_inheritable -> bool
Benjamin Petersonca470632016-09-06 13:47:26 -070012366 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012367 /
Victor Stinnerdaf45552013-08-28 00:53:59 +020012368
Larry Hastings2f936352014-08-05 14:04:04 +100012369Get the close-on-exe flag of the specified file descriptor.
12370[clinic start generated code]*/
12371
Larry Hastings2f936352014-08-05 14:04:04 +100012372static int
Benjamin Petersonca470632016-09-06 13:47:26 -070012373os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
Victor Stinner581139c2016-09-06 15:54:20 -070012374/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012375{
12376 DWORD flags;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012377
12378 if (!GetHandleInformation((HANDLE)handle, &flags)) {
12379 PyErr_SetFromWindowsErr(0);
Larry Hastings2f936352014-08-05 14:04:04 +100012380 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012381 }
12382
Larry Hastings2f936352014-08-05 14:04:04 +100012383 return flags & HANDLE_FLAG_INHERIT;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012384}
12385
Victor Stinnerdaf45552013-08-28 00:53:59 +020012386
Larry Hastings2f936352014-08-05 14:04:04 +100012387/*[clinic input]
12388os.set_handle_inheritable
Benjamin Petersonca470632016-09-06 13:47:26 -070012389 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012390 inheritable: bool
12391 /
12392
12393Set the inheritable flag of the specified handle.
12394[clinic start generated code]*/
12395
Larry Hastings2f936352014-08-05 14:04:04 +100012396static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -070012397os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
Larry Hastings89964c42015-04-14 18:07:59 -040012398 int inheritable)
Victor Stinner581139c2016-09-06 15:54:20 -070012399/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012400{
12401 DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012402 if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
12403 PyErr_SetFromWindowsErr(0);
12404 return NULL;
12405 }
12406 Py_RETURN_NONE;
12407}
Larry Hastings2f936352014-08-05 14:04:04 +100012408#endif /* MS_WINDOWS */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012409
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012410#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012411/*[clinic input]
12412os.get_blocking -> bool
12413 fd: int
12414 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012415
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012416Get the blocking mode of the file descriptor.
12417
12418Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
12419[clinic start generated code]*/
12420
12421static int
12422os_get_blocking_impl(PyObject *module, int fd)
12423/*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012424{
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012425 int blocking;
12426
Steve Dower8fc89802015-04-12 00:26:27 -040012427 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012428 blocking = _Py_get_blocking(fd);
Steve Dower8fc89802015-04-12 00:26:27 -040012429 _Py_END_SUPPRESS_IPH
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012430 return blocking;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012431}
12432
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012433/*[clinic input]
12434os.set_blocking
12435 fd: int
12436 blocking: bool(accept={int})
12437 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012438
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012439Set the blocking mode of the specified file descriptor.
12440
12441Set the O_NONBLOCK flag if blocking is False,
12442clear the O_NONBLOCK flag otherwise.
12443[clinic start generated code]*/
12444
12445static PyObject *
12446os_set_blocking_impl(PyObject *module, int fd, int blocking)
12447/*[clinic end generated code: output=384eb43aa0762a9d input=bf5c8efdc5860ff3]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012448{
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012449 int result;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012450
Steve Dower8fc89802015-04-12 00:26:27 -040012451 _Py_BEGIN_SUPPRESS_IPH
12452 result = _Py_set_blocking(fd, blocking);
12453 _Py_END_SUPPRESS_IPH
12454 if (result < 0)
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012455 return NULL;
12456 Py_RETURN_NONE;
12457}
12458#endif /* !MS_WINDOWS */
12459
12460
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012461/*[clinic input]
Eddie Elizondob3966632019-11-05 07:16:14 -080012462class os.DirEntry "DirEntry *" "DirEntryType"
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012463[clinic start generated code]*/
Eddie Elizondob3966632019-11-05 07:16:14 -080012464/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3c18c7a448247980]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012465
12466typedef struct {
12467 PyObject_HEAD
12468 PyObject *name;
12469 PyObject *path;
12470 PyObject *stat;
12471 PyObject *lstat;
12472#ifdef MS_WINDOWS
12473 struct _Py_stat_struct win32_lstat;
Victor Stinner0f6d7332017-03-09 17:34:28 +010012474 uint64_t win32_file_index;
Victor Stinner6036e442015-03-08 01:58:04 +010012475 int got_file_index;
12476#else /* POSIX */
Victor Stinner35a97c02015-03-08 02:59:09 +010012477#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012478 unsigned char d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012479#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012480 ino_t d_ino;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012481 int dir_fd;
Victor Stinner6036e442015-03-08 01:58:04 +010012482#endif
12483} DirEntry;
12484
Eddie Elizondob3966632019-11-05 07:16:14 -080012485static PyObject *
12486_disabled_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
12487{
12488 PyErr_Format(PyExc_TypeError,
12489 "cannot create '%.100s' instances", _PyType_Name(type));
12490 return NULL;
12491}
12492
Victor Stinner6036e442015-03-08 01:58:04 +010012493static void
12494DirEntry_dealloc(DirEntry *entry)
12495{
Eddie Elizondob3966632019-11-05 07:16:14 -080012496 PyTypeObject *tp = Py_TYPE(entry);
Victor Stinner6036e442015-03-08 01:58:04 +010012497 Py_XDECREF(entry->name);
12498 Py_XDECREF(entry->path);
12499 Py_XDECREF(entry->stat);
12500 Py_XDECREF(entry->lstat);
Eddie Elizondob3966632019-11-05 07:16:14 -080012501 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
12502 free_func(entry);
12503 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010012504}
12505
12506/* Forward reference */
12507static int
12508DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits);
12509
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012510/*[clinic input]
12511os.DirEntry.is_symlink -> bool
12512
12513Return True if the entry is a symbolic link; cached per entry.
12514[clinic start generated code]*/
12515
Victor Stinner6036e442015-03-08 01:58:04 +010012516static int
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012517os_DirEntry_is_symlink_impl(DirEntry *self)
12518/*[clinic end generated code: output=42244667d7bcfc25 input=1605a1b4b96976c3]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012519{
12520#ifdef MS_WINDOWS
12521 return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
Victor Stinner35a97c02015-03-08 02:59:09 +010012522#elif defined(HAVE_DIRENT_D_TYPE)
12523 /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010012524 if (self->d_type != DT_UNKNOWN)
12525 return self->d_type == DT_LNK;
12526 else
12527 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner35a97c02015-03-08 02:59:09 +010012528#else
12529 /* POSIX without d_type */
12530 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner6036e442015-03-08 01:58:04 +010012531#endif
12532}
12533
12534static PyObject *
Victor Stinner6036e442015-03-08 01:58:04 +010012535DirEntry_fetch_stat(DirEntry *self, int follow_symlinks)
12536{
12537 int result;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012538 STRUCT_STAT st;
12539 PyObject *ub;
Victor Stinner6036e442015-03-08 01:58:04 +010012540
12541#ifdef MS_WINDOWS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012542 if (!PyUnicode_FSDecoder(self->path, &ub))
12543 return NULL;
12544 const wchar_t *path = PyUnicode_AsUnicode(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012545#else /* POSIX */
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012546 if (!PyUnicode_FSConverter(self->path, &ub))
12547 return NULL;
12548 const char *path = PyBytes_AS_STRING(ub);
12549 if (self->dir_fd != DEFAULT_DIR_FD) {
12550#ifdef HAVE_FSTATAT
12551 result = fstatat(self->dir_fd, path, &st,
12552 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
12553#else
12554 PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
12555 return NULL;
12556#endif /* HAVE_FSTATAT */
12557 }
12558 else
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012559#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012560 {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012561 if (follow_symlinks)
12562 result = STAT(path, &st);
12563 else
12564 result = LSTAT(path, &st);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012565 }
12566 Py_DECREF(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012567
12568 if (result != 0)
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012569 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012570
12571 return _pystat_fromstructstat(&st);
12572}
12573
12574static PyObject *
12575DirEntry_get_lstat(DirEntry *self)
12576{
12577 if (!self->lstat) {
12578#ifdef MS_WINDOWS
12579 self->lstat = _pystat_fromstructstat(&self->win32_lstat);
12580#else /* POSIX */
12581 self->lstat = DirEntry_fetch_stat(self, 0);
12582#endif
12583 }
12584 Py_XINCREF(self->lstat);
12585 return self->lstat;
12586}
12587
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012588/*[clinic input]
12589os.DirEntry.stat
12590 *
12591 follow_symlinks: bool = True
12592
12593Return stat_result object for the entry; cached per entry.
12594[clinic start generated code]*/
12595
Victor Stinner6036e442015-03-08 01:58:04 +010012596static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012597os_DirEntry_stat_impl(DirEntry *self, int follow_symlinks)
12598/*[clinic end generated code: output=008593b3a6d01305 input=280d14c1d6f1d00d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012599{
12600 if (!follow_symlinks)
12601 return DirEntry_get_lstat(self);
12602
12603 if (!self->stat) {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012604 int result = os_DirEntry_is_symlink_impl(self);
Victor Stinner6036e442015-03-08 01:58:04 +010012605 if (result == -1)
12606 return NULL;
12607 else if (result)
12608 self->stat = DirEntry_fetch_stat(self, 1);
12609 else
12610 self->stat = DirEntry_get_lstat(self);
12611 }
12612
12613 Py_XINCREF(self->stat);
12614 return self->stat;
12615}
12616
Victor Stinner6036e442015-03-08 01:58:04 +010012617/* Set exception and return -1 on error, 0 for False, 1 for True */
12618static int
12619DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
12620{
12621 PyObject *stat = NULL;
12622 PyObject *st_mode = NULL;
12623 long mode;
12624 int result;
Victor Stinner35a97c02015-03-08 02:59:09 +010012625#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012626 int is_symlink;
12627 int need_stat;
Victor Stinner35a97c02015-03-08 02:59:09 +010012628#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012629#ifdef MS_WINDOWS
12630 unsigned long dir_bits;
12631#endif
12632
12633#ifdef MS_WINDOWS
12634 is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
12635 need_stat = follow_symlinks && is_symlink;
Victor Stinner35a97c02015-03-08 02:59:09 +010012636#elif defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012637 is_symlink = self->d_type == DT_LNK;
12638 need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
12639#endif
12640
Victor Stinner35a97c02015-03-08 02:59:09 +010012641#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012642 if (need_stat) {
Victor Stinner35a97c02015-03-08 02:59:09 +010012643#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012644 stat = os_DirEntry_stat_impl(self, follow_symlinks);
Victor Stinner6036e442015-03-08 01:58:04 +010012645 if (!stat) {
12646 if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
12647 /* If file doesn't exist (anymore), then return False
12648 (i.e., say it's not a file/directory) */
12649 PyErr_Clear();
12650 return 0;
12651 }
12652 goto error;
12653 }
Eddie Elizondob3966632019-11-05 07:16:14 -080012654 st_mode = PyObject_GetAttr(stat, _posixstate_global->st_mode);
Victor Stinner6036e442015-03-08 01:58:04 +010012655 if (!st_mode)
12656 goto error;
12657
12658 mode = PyLong_AsLong(st_mode);
12659 if (mode == -1 && PyErr_Occurred())
12660 goto error;
12661 Py_CLEAR(st_mode);
12662 Py_CLEAR(stat);
12663 result = (mode & S_IFMT) == mode_bits;
Victor Stinner35a97c02015-03-08 02:59:09 +010012664#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012665 }
12666 else if (is_symlink) {
12667 assert(mode_bits != S_IFLNK);
12668 result = 0;
12669 }
12670 else {
12671 assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
12672#ifdef MS_WINDOWS
12673 dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
12674 if (mode_bits == S_IFDIR)
12675 result = dir_bits != 0;
12676 else
12677 result = dir_bits == 0;
12678#else /* POSIX */
12679 if (mode_bits == S_IFDIR)
12680 result = self->d_type == DT_DIR;
12681 else
12682 result = self->d_type == DT_REG;
12683#endif
12684 }
Victor Stinner35a97c02015-03-08 02:59:09 +010012685#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012686
12687 return result;
12688
12689error:
12690 Py_XDECREF(st_mode);
12691 Py_XDECREF(stat);
12692 return -1;
12693}
12694
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012695/*[clinic input]
12696os.DirEntry.is_dir -> bool
12697 *
12698 follow_symlinks: bool = True
Victor Stinner6036e442015-03-08 01:58:04 +010012699
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012700Return True if the entry is a directory; cached per entry.
12701[clinic start generated code]*/
12702
12703static int
12704os_DirEntry_is_dir_impl(DirEntry *self, int follow_symlinks)
12705/*[clinic end generated code: output=ad2e8d54365da287 input=0135232766f53f58]*/
12706{
12707 return DirEntry_test_mode(self, follow_symlinks, S_IFDIR);
Victor Stinner6036e442015-03-08 01:58:04 +010012708}
12709
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012710/*[clinic input]
12711os.DirEntry.is_file -> bool
12712 *
12713 follow_symlinks: bool = True
12714
12715Return True if the entry is a file; cached per entry.
12716[clinic start generated code]*/
12717
12718static int
12719os_DirEntry_is_file_impl(DirEntry *self, int follow_symlinks)
12720/*[clinic end generated code: output=8462ade481d8a476 input=0dc90be168b041ee]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012721{
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012722 return DirEntry_test_mode(self, follow_symlinks, S_IFREG);
Victor Stinner6036e442015-03-08 01:58:04 +010012723}
12724
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012725/*[clinic input]
12726os.DirEntry.inode
Victor Stinner6036e442015-03-08 01:58:04 +010012727
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012728Return inode of the entry; cached per entry.
12729[clinic start generated code]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012730
12731static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012732os_DirEntry_inode_impl(DirEntry *self)
12733/*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012734{
12735#ifdef MS_WINDOWS
12736 if (!self->got_file_index) {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012737 PyObject *unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012738 const wchar_t *path;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012739 STRUCT_STAT stat;
12740 int result;
Victor Stinner6036e442015-03-08 01:58:04 +010012741
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012742 if (!PyUnicode_FSDecoder(self->path, &unicode))
Victor Stinner6036e442015-03-08 01:58:04 +010012743 return NULL;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012744 path = PyUnicode_AsUnicode(unicode);
12745 result = LSTAT(path, &stat);
12746 Py_DECREF(unicode);
Victor Stinner6036e442015-03-08 01:58:04 +010012747
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012748 if (result != 0)
12749 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012750
12751 self->win32_file_index = stat.st_ino;
12752 self->got_file_index = 1;
12753 }
Victor Stinner0f6d7332017-03-09 17:34:28 +010012754 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->win32_file_index));
12755 return PyLong_FromUnsignedLongLong(self->win32_file_index);
Victor Stinner6036e442015-03-08 01:58:04 +010012756#else /* POSIX */
xdegaye50e86032017-05-22 11:15:08 +020012757 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->d_ino));
12758 return PyLong_FromUnsignedLongLong(self->d_ino);
Victor Stinner6036e442015-03-08 01:58:04 +010012759#endif
12760}
12761
12762static PyObject *
12763DirEntry_repr(DirEntry *self)
12764{
12765 return PyUnicode_FromFormat("<DirEntry %R>", self->name);
12766}
12767
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012768/*[clinic input]
12769os.DirEntry.__fspath__
12770
12771Returns the path for the entry.
12772[clinic start generated code]*/
12773
Brett Cannon96881cd2016-06-10 14:37:21 -070012774static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012775os_DirEntry___fspath___impl(DirEntry *self)
12776/*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
Brett Cannon96881cd2016-06-10 14:37:21 -070012777{
12778 Py_INCREF(self->path);
12779 return self->path;
12780}
12781
Victor Stinner6036e442015-03-08 01:58:04 +010012782static PyMemberDef DirEntry_members[] = {
12783 {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
12784 "the entry's base filename, relative to scandir() \"path\" argument"},
12785 {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
12786 "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
12787 {NULL}
12788};
12789
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012790#include "clinic/posixmodule.c.h"
12791
Victor Stinner6036e442015-03-08 01:58:04 +010012792static PyMethodDef DirEntry_methods[] = {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012793 OS_DIRENTRY_IS_DIR_METHODDEF
12794 OS_DIRENTRY_IS_FILE_METHODDEF
12795 OS_DIRENTRY_IS_SYMLINK_METHODDEF
12796 OS_DIRENTRY_STAT_METHODDEF
12797 OS_DIRENTRY_INODE_METHODDEF
12798 OS_DIRENTRY___FSPATH___METHODDEF
Victor Stinner6036e442015-03-08 01:58:04 +010012799 {NULL}
12800};
12801
Eddie Elizondob3966632019-11-05 07:16:14 -080012802static PyType_Slot DirEntryType_slots[] = {
12803 {Py_tp_new, _disabled_new},
12804 {Py_tp_dealloc, DirEntry_dealloc},
12805 {Py_tp_repr, DirEntry_repr},
12806 {Py_tp_methods, DirEntry_methods},
12807 {Py_tp_members, DirEntry_members},
12808 {0, 0},
Victor Stinner6036e442015-03-08 01:58:04 +010012809};
12810
Eddie Elizondob3966632019-11-05 07:16:14 -080012811static PyType_Spec DirEntryType_spec = {
12812 MODNAME ".DirEntry",
12813 sizeof(DirEntry),
12814 0,
12815 Py_TPFLAGS_DEFAULT,
12816 DirEntryType_slots
12817};
12818
12819
Victor Stinner6036e442015-03-08 01:58:04 +010012820#ifdef MS_WINDOWS
12821
12822static wchar_t *
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012823join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
Victor Stinner6036e442015-03-08 01:58:04 +010012824{
12825 Py_ssize_t path_len;
12826 Py_ssize_t size;
12827 wchar_t *result;
12828 wchar_t ch;
12829
12830 if (!path_wide) { /* Default arg: "." */
12831 path_wide = L".";
12832 path_len = 1;
12833 }
12834 else {
12835 path_len = wcslen(path_wide);
12836 }
12837
12838 /* The +1's are for the path separator and the NUL */
12839 size = path_len + 1 + wcslen(filename) + 1;
12840 result = PyMem_New(wchar_t, size);
12841 if (!result) {
12842 PyErr_NoMemory();
12843 return NULL;
12844 }
12845 wcscpy(result, path_wide);
12846 if (path_len > 0) {
12847 ch = result[path_len - 1];
12848 if (ch != SEP && ch != ALTSEP && ch != L':')
12849 result[path_len++] = SEP;
12850 wcscpy(result + path_len, filename);
12851 }
12852 return result;
12853}
12854
12855static PyObject *
12856DirEntry_from_find_data(path_t *path, WIN32_FIND_DATAW *dataW)
12857{
12858 DirEntry *entry;
12859 BY_HANDLE_FILE_INFORMATION file_info;
12860 ULONG reparse_tag;
12861 wchar_t *joined_path;
12862
Eddie Elizondob3966632019-11-05 07:16:14 -080012863 PyObject *DirEntryType = _posixstate_global->DirEntryType;
12864 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010012865 if (!entry)
12866 return NULL;
12867 entry->name = NULL;
12868 entry->path = NULL;
12869 entry->stat = NULL;
12870 entry->lstat = NULL;
12871 entry->got_file_index = 0;
12872
12873 entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
12874 if (!entry->name)
12875 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012876 if (path->narrow) {
12877 Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
12878 if (!entry->name)
12879 goto error;
12880 }
Victor Stinner6036e442015-03-08 01:58:04 +010012881
12882 joined_path = join_path_filenameW(path->wide, dataW->cFileName);
12883 if (!joined_path)
12884 goto error;
12885
12886 entry->path = PyUnicode_FromWideChar(joined_path, -1);
12887 PyMem_Free(joined_path);
12888 if (!entry->path)
12889 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012890 if (path->narrow) {
12891 Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
12892 if (!entry->path)
12893 goto error;
12894 }
Victor Stinner6036e442015-03-08 01:58:04 +010012895
Steve Dowercc16be82016-09-08 10:35:16 -070012896 find_data_to_file_info(dataW, &file_info, &reparse_tag);
Victor Stinner6036e442015-03-08 01:58:04 +010012897 _Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
12898
12899 return (PyObject *)entry;
12900
12901error:
12902 Py_DECREF(entry);
12903 return NULL;
12904}
12905
12906#else /* POSIX */
12907
12908static char *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012909join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
Victor Stinner6036e442015-03-08 01:58:04 +010012910{
12911 Py_ssize_t path_len;
12912 Py_ssize_t size;
12913 char *result;
12914
12915 if (!path_narrow) { /* Default arg: "." */
12916 path_narrow = ".";
12917 path_len = 1;
12918 }
12919 else {
12920 path_len = strlen(path_narrow);
12921 }
12922
12923 if (filename_len == -1)
12924 filename_len = strlen(filename);
12925
12926 /* The +1's are for the path separator and the NUL */
12927 size = path_len + 1 + filename_len + 1;
12928 result = PyMem_New(char, size);
12929 if (!result) {
12930 PyErr_NoMemory();
12931 return NULL;
12932 }
12933 strcpy(result, path_narrow);
12934 if (path_len > 0 && result[path_len - 1] != '/')
12935 result[path_len++] = '/';
12936 strcpy(result + path_len, filename);
12937 return result;
12938}
12939
12940static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012941DirEntry_from_posix_info(path_t *path, const char *name, Py_ssize_t name_len,
Victor Stinner35a97c02015-03-08 02:59:09 +010012942 ino_t d_ino
12943#ifdef HAVE_DIRENT_D_TYPE
12944 , unsigned char d_type
12945#endif
12946 )
Victor Stinner6036e442015-03-08 01:58:04 +010012947{
12948 DirEntry *entry;
12949 char *joined_path;
12950
Eddie Elizondob3966632019-11-05 07:16:14 -080012951 PyObject *DirEntryType = _posixstate_global->DirEntryType;
12952 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010012953 if (!entry)
12954 return NULL;
12955 entry->name = NULL;
12956 entry->path = NULL;
12957 entry->stat = NULL;
12958 entry->lstat = NULL;
12959
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012960 if (path->fd != -1) {
12961 entry->dir_fd = path->fd;
12962 joined_path = NULL;
12963 }
12964 else {
12965 entry->dir_fd = DEFAULT_DIR_FD;
12966 joined_path = join_path_filename(path->narrow, name, name_len);
12967 if (!joined_path)
12968 goto error;
12969 }
Victor Stinner6036e442015-03-08 01:58:04 +010012970
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +030012971 if (!path->narrow || !PyObject_CheckBuffer(path->object)) {
Victor Stinner6036e442015-03-08 01:58:04 +010012972 entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012973 if (joined_path)
12974 entry->path = PyUnicode_DecodeFSDefault(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010012975 }
12976 else {
12977 entry->name = PyBytes_FromStringAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012978 if (joined_path)
12979 entry->path = PyBytes_FromString(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010012980 }
12981 PyMem_Free(joined_path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012982 if (!entry->name)
12983 goto error;
12984
12985 if (path->fd != -1) {
12986 entry->path = entry->name;
12987 Py_INCREF(entry->path);
12988 }
12989 else if (!entry->path)
Victor Stinner6036e442015-03-08 01:58:04 +010012990 goto error;
12991
Victor Stinner35a97c02015-03-08 02:59:09 +010012992#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012993 entry->d_type = d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012994#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012995 entry->d_ino = d_ino;
12996
12997 return (PyObject *)entry;
12998
12999error:
13000 Py_XDECREF(entry);
13001 return NULL;
13002}
13003
13004#endif
13005
13006
13007typedef struct {
13008 PyObject_HEAD
13009 path_t path;
13010#ifdef MS_WINDOWS
13011 HANDLE handle;
13012 WIN32_FIND_DATAW file_data;
13013 int first_time;
13014#else /* POSIX */
13015 DIR *dirp;
13016#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013017#ifdef HAVE_FDOPENDIR
13018 int fd;
13019#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013020} ScandirIterator;
13021
13022#ifdef MS_WINDOWS
13023
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013024static int
13025ScandirIterator_is_closed(ScandirIterator *iterator)
13026{
13027 return iterator->handle == INVALID_HANDLE_VALUE;
13028}
13029
Victor Stinner6036e442015-03-08 01:58:04 +010013030static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013031ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013032{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013033 HANDLE handle = iterator->handle;
13034
13035 if (handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013036 return;
13037
Victor Stinner6036e442015-03-08 01:58:04 +010013038 iterator->handle = INVALID_HANDLE_VALUE;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013039 Py_BEGIN_ALLOW_THREADS
13040 FindClose(handle);
13041 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013042}
13043
13044static PyObject *
13045ScandirIterator_iternext(ScandirIterator *iterator)
13046{
13047 WIN32_FIND_DATAW *file_data = &iterator->file_data;
13048 BOOL success;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013049 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013050
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013051 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013052 if (iterator->handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013053 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013054
13055 while (1) {
13056 if (!iterator->first_time) {
13057 Py_BEGIN_ALLOW_THREADS
13058 success = FindNextFileW(iterator->handle, file_data);
13059 Py_END_ALLOW_THREADS
13060 if (!success) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013061 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013062 if (GetLastError() != ERROR_NO_MORE_FILES)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013063 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013064 break;
13065 }
13066 }
13067 iterator->first_time = 0;
13068
13069 /* Skip over . and .. */
13070 if (wcscmp(file_data->cFileName, L".") != 0 &&
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013071 wcscmp(file_data->cFileName, L"..") != 0) {
13072 entry = DirEntry_from_find_data(&iterator->path, file_data);
13073 if (!entry)
13074 break;
13075 return entry;
13076 }
Victor Stinner6036e442015-03-08 01:58:04 +010013077
13078 /* Loop till we get a non-dot directory or finish iterating */
13079 }
13080
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013081 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013082 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013083 return NULL;
13084}
13085
13086#else /* POSIX */
13087
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013088static int
13089ScandirIterator_is_closed(ScandirIterator *iterator)
13090{
13091 return !iterator->dirp;
13092}
13093
Victor Stinner6036e442015-03-08 01:58:04 +010013094static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013095ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013096{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013097 DIR *dirp = iterator->dirp;
13098
13099 if (!dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013100 return;
13101
Victor Stinner6036e442015-03-08 01:58:04 +010013102 iterator->dirp = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013103 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013104#ifdef HAVE_FDOPENDIR
13105 if (iterator->path.fd != -1)
13106 rewinddir(dirp);
13107#endif
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013108 closedir(dirp);
13109 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013110 return;
13111}
13112
13113static PyObject *
13114ScandirIterator_iternext(ScandirIterator *iterator)
13115{
13116 struct dirent *direntp;
13117 Py_ssize_t name_len;
13118 int is_dot;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013119 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013120
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013121 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013122 if (!iterator->dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013123 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013124
13125 while (1) {
13126 errno = 0;
13127 Py_BEGIN_ALLOW_THREADS
13128 direntp = readdir(iterator->dirp);
13129 Py_END_ALLOW_THREADS
13130
13131 if (!direntp) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013132 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013133 if (errno != 0)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013134 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013135 break;
13136 }
13137
13138 /* Skip over . and .. */
13139 name_len = NAMLEN(direntp);
13140 is_dot = direntp->d_name[0] == '.' &&
13141 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
13142 if (!is_dot) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013143 entry = DirEntry_from_posix_info(&iterator->path, direntp->d_name,
Victor Stinner35a97c02015-03-08 02:59:09 +010013144 name_len, direntp->d_ino
13145#ifdef HAVE_DIRENT_D_TYPE
13146 , direntp->d_type
13147#endif
13148 );
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013149 if (!entry)
13150 break;
13151 return entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013152 }
13153
13154 /* Loop till we get a non-dot directory or finish iterating */
13155 }
13156
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013157 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013158 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013159 return NULL;
13160}
13161
13162#endif
13163
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013164static PyObject *
13165ScandirIterator_close(ScandirIterator *self, PyObject *args)
13166{
13167 ScandirIterator_closedir(self);
13168 Py_RETURN_NONE;
13169}
13170
13171static PyObject *
13172ScandirIterator_enter(PyObject *self, PyObject *args)
13173{
13174 Py_INCREF(self);
13175 return self;
13176}
13177
13178static PyObject *
13179ScandirIterator_exit(ScandirIterator *self, PyObject *args)
13180{
13181 ScandirIterator_closedir(self);
13182 Py_RETURN_NONE;
13183}
13184
Victor Stinner6036e442015-03-08 01:58:04 +010013185static void
Victor Stinner7bfa4092016-03-23 00:43:54 +010013186ScandirIterator_finalize(ScandirIterator *iterator)
13187{
13188 PyObject *error_type, *error_value, *error_traceback;
13189
13190 /* Save the current exception, if any. */
13191 PyErr_Fetch(&error_type, &error_value, &error_traceback);
13192
13193 if (!ScandirIterator_is_closed(iterator)) {
13194 ScandirIterator_closedir(iterator);
13195
13196 if (PyErr_ResourceWarning((PyObject *)iterator, 1,
13197 "unclosed scandir iterator %R", iterator)) {
13198 /* Spurious errors can appear at shutdown */
13199 if (PyErr_ExceptionMatches(PyExc_Warning)) {
13200 PyErr_WriteUnraisable((PyObject *) iterator);
13201 }
13202 }
13203 }
13204
Victor Stinner7bfa4092016-03-23 00:43:54 +010013205 path_cleanup(&iterator->path);
13206
13207 /* Restore the saved exception. */
13208 PyErr_Restore(error_type, error_value, error_traceback);
13209}
13210
13211static void
Victor Stinner6036e442015-03-08 01:58:04 +010013212ScandirIterator_dealloc(ScandirIterator *iterator)
13213{
Eddie Elizondob3966632019-11-05 07:16:14 -080013214 PyTypeObject *tp = Py_TYPE(iterator);
Victor Stinner7bfa4092016-03-23 00:43:54 +010013215 if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
13216 return;
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013217
Eddie Elizondob3966632019-11-05 07:16:14 -080013218 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
13219 free_func(iterator);
13220 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010013221}
13222
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013223static PyMethodDef ScandirIterator_methods[] = {
13224 {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
13225 {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
13226 {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
13227 {NULL}
13228};
13229
Eddie Elizondob3966632019-11-05 07:16:14 -080013230static PyType_Slot ScandirIteratorType_slots[] = {
13231 {Py_tp_new, _disabled_new},
13232 {Py_tp_dealloc, ScandirIterator_dealloc},
13233 {Py_tp_finalize, ScandirIterator_finalize},
13234 {Py_tp_iter, PyObject_SelfIter},
13235 {Py_tp_iternext, ScandirIterator_iternext},
13236 {Py_tp_methods, ScandirIterator_methods},
13237 {0, 0},
13238};
13239
13240static PyType_Spec ScandirIteratorType_spec = {
13241 MODNAME ".ScandirIterator",
13242 sizeof(ScandirIterator),
13243 0,
13244 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE,
13245 ScandirIteratorType_slots
Victor Stinner6036e442015-03-08 01:58:04 +010013246};
13247
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013248/*[clinic input]
13249os.scandir
13250
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013251 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013252
13253Return an iterator of DirEntry objects for given path.
13254
BNMetricsb9427072018-11-02 15:20:19 +000013255path can be specified as either str, bytes, or a path-like object. If path
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013256is bytes, the names of yielded DirEntry objects will also be bytes; in
13257all other circumstances they will be str.
13258
13259If path is None, uses the path='.'.
13260[clinic start generated code]*/
13261
Victor Stinner6036e442015-03-08 01:58:04 +010013262static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013263os_scandir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +000013264/*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013265{
13266 ScandirIterator *iterator;
Victor Stinner6036e442015-03-08 01:58:04 +010013267#ifdef MS_WINDOWS
13268 wchar_t *path_strW;
13269#else
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013270 const char *path_str;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013271#ifdef HAVE_FDOPENDIR
13272 int fd = -1;
13273#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013274#endif
13275
Steve Dower60419a72019-06-24 08:42:54 -070013276 if (PySys_Audit("os.scandir", "O",
13277 path->object ? path->object : Py_None) < 0) {
13278 return NULL;
13279 }
13280
Eddie Elizondob3966632019-11-05 07:16:14 -080013281 PyObject *ScandirIteratorType = _posixstate(module)->ScandirIteratorType;
13282 iterator = PyObject_New(ScandirIterator, (PyTypeObject *)ScandirIteratorType);
Victor Stinner6036e442015-03-08 01:58:04 +010013283 if (!iterator)
13284 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013285
13286#ifdef MS_WINDOWS
13287 iterator->handle = INVALID_HANDLE_VALUE;
13288#else
13289 iterator->dirp = NULL;
13290#endif
13291
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013292 memcpy(&iterator->path, path, sizeof(path_t));
Serhiy Storchaka095ef732017-02-09 20:05:51 +020013293 /* Move the ownership to iterator->path */
13294 path->object = NULL;
13295 path->cleanup = NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013296
13297#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +010013298 iterator->first_time = 1;
13299
13300 path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
13301 if (!path_strW)
13302 goto error;
13303
13304 Py_BEGIN_ALLOW_THREADS
13305 iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
13306 Py_END_ALLOW_THREADS
13307
13308 PyMem_Free(path_strW);
13309
13310 if (iterator->handle == INVALID_HANDLE_VALUE) {
13311 path_error(&iterator->path);
13312 goto error;
13313 }
13314#else /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010013315 errno = 0;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013316#ifdef HAVE_FDOPENDIR
13317 if (path->fd != -1) {
13318 /* closedir() closes the FD, so we duplicate it */
13319 fd = _Py_dup(path->fd);
13320 if (fd == -1)
13321 goto error;
13322
13323 Py_BEGIN_ALLOW_THREADS
13324 iterator->dirp = fdopendir(fd);
13325 Py_END_ALLOW_THREADS
13326 }
13327 else
13328#endif
13329 {
13330 if (iterator->path.narrow)
13331 path_str = iterator->path.narrow;
13332 else
13333 path_str = ".";
13334
13335 Py_BEGIN_ALLOW_THREADS
13336 iterator->dirp = opendir(path_str);
13337 Py_END_ALLOW_THREADS
13338 }
Victor Stinner6036e442015-03-08 01:58:04 +010013339
13340 if (!iterator->dirp) {
13341 path_error(&iterator->path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013342#ifdef HAVE_FDOPENDIR
13343 if (fd != -1) {
13344 Py_BEGIN_ALLOW_THREADS
13345 close(fd);
13346 Py_END_ALLOW_THREADS
13347 }
13348#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013349 goto error;
13350 }
13351#endif
13352
13353 return (PyObject *)iterator;
13354
13355error:
13356 Py_DECREF(iterator);
13357 return NULL;
13358}
13359
Ethan Furman410ef8e2016-06-04 12:06:26 -070013360/*
13361 Return the file system path representation of the object.
13362
13363 If the object is str or bytes, then allow it to pass through with
13364 an incremented refcount. If the object defines __fspath__(), then
13365 return the result of that method. All other types raise a TypeError.
13366*/
13367PyObject *
13368PyOS_FSPath(PyObject *path)
13369{
Brett Cannon3f9183b2016-08-26 14:44:48 -070013370 /* For error message reasons, this function is manually inlined in
13371 path_converter(). */
Ethan Furman410ef8e2016-06-04 12:06:26 -070013372 PyObject *func = NULL;
13373 PyObject *path_repr = NULL;
13374
13375 if (PyUnicode_Check(path) || PyBytes_Check(path)) {
13376 Py_INCREF(path);
13377 return path;
13378 }
13379
13380 func = _PyObject_LookupSpecial(path, &PyId___fspath__);
13381 if (NULL == func) {
13382 return PyErr_Format(PyExc_TypeError,
13383 "expected str, bytes or os.PathLike object, "
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013384 "not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -080013385 _PyType_Name(Py_TYPE(path)));
Ethan Furman410ef8e2016-06-04 12:06:26 -070013386 }
13387
Victor Stinnerf17c3de2016-12-06 18:46:19 +010013388 path_repr = _PyObject_CallNoArg(func);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013389 Py_DECREF(func);
Brett Cannon044283a2016-07-15 10:41:49 -070013390 if (NULL == path_repr) {
13391 return NULL;
13392 }
13393
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013394 if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
13395 PyErr_Format(PyExc_TypeError,
13396 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -080013397 "not %.200s", _PyType_Name(Py_TYPE(path)),
13398 _PyType_Name(Py_TYPE(path_repr)));
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013399 Py_DECREF(path_repr);
13400 return NULL;
13401 }
13402
Ethan Furman410ef8e2016-06-04 12:06:26 -070013403 return path_repr;
13404}
13405
13406/*[clinic input]
13407os.fspath
13408
13409 path: object
13410
13411Return the file system path representation of the object.
13412
Brett Cannonb4f43e92016-06-09 14:32:08 -070013413If the object is str or bytes, then allow it to pass through as-is. If the
13414object defines __fspath__(), then return the result of that method. All other
13415types raise a TypeError.
Ethan Furman410ef8e2016-06-04 12:06:26 -070013416[clinic start generated code]*/
13417
13418static PyObject *
Serhiy Storchaka2954f832016-07-07 18:20:03 +030013419os_fspath_impl(PyObject *module, PyObject *path)
13420/*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
Ethan Furman410ef8e2016-06-04 12:06:26 -070013421{
13422 return PyOS_FSPath(path);
13423}
Victor Stinner6036e442015-03-08 01:58:04 +010013424
Victor Stinner9b1f4742016-09-06 16:18:52 -070013425#ifdef HAVE_GETRANDOM_SYSCALL
13426/*[clinic input]
13427os.getrandom
13428
13429 size: Py_ssize_t
13430 flags: int=0
13431
13432Obtain a series of random bytes.
13433[clinic start generated code]*/
13434
13435static PyObject *
13436os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
13437/*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
13438{
Victor Stinner9b1f4742016-09-06 16:18:52 -070013439 PyObject *bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013440 Py_ssize_t n;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013441
13442 if (size < 0) {
13443 errno = EINVAL;
13444 return posix_error();
13445 }
13446
Victor Stinnerec2319c2016-09-20 23:00:59 +020013447 bytes = PyBytes_FromStringAndSize(NULL, size);
13448 if (bytes == NULL) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013449 PyErr_NoMemory();
13450 return NULL;
13451 }
13452
13453 while (1) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013454 n = syscall(SYS_getrandom,
13455 PyBytes_AS_STRING(bytes),
13456 PyBytes_GET_SIZE(bytes),
13457 flags);
Victor Stinner9b1f4742016-09-06 16:18:52 -070013458 if (n < 0 && errno == EINTR) {
13459 if (PyErr_CheckSignals() < 0) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013460 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013461 }
Victor Stinnerec2319c2016-09-20 23:00:59 +020013462
13463 /* getrandom() was interrupted by a signal: retry */
Victor Stinner9b1f4742016-09-06 16:18:52 -070013464 continue;
13465 }
13466 break;
13467 }
13468
13469 if (n < 0) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013470 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerec2319c2016-09-20 23:00:59 +020013471 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013472 }
13473
Victor Stinnerec2319c2016-09-20 23:00:59 +020013474 if (n != size) {
13475 _PyBytes_Resize(&bytes, n);
13476 }
Victor Stinner9b1f4742016-09-06 16:18:52 -070013477
13478 return bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013479
13480error:
13481 Py_DECREF(bytes);
13482 return NULL;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013483}
13484#endif /* HAVE_GETRANDOM_SYSCALL */
13485
Steve Dower2438cdf2019-03-29 16:37:16 -070013486#ifdef MS_WINDOWS
13487/* bpo-36085: Helper functions for managing DLL search directories
13488 * on win32
13489 */
13490
13491typedef DLL_DIRECTORY_COOKIE (WINAPI *PAddDllDirectory)(PCWSTR newDirectory);
13492typedef BOOL (WINAPI *PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE cookie);
13493
13494/*[clinic input]
13495os._add_dll_directory
13496
13497 path: path_t
13498
13499Add a path to the DLL search path.
13500
13501This search path is used when resolving dependencies for imported
13502extension modules (the module itself is resolved through sys.path),
13503and also by ctypes.
13504
13505Returns an opaque value that may be passed to os.remove_dll_directory
13506to remove this directory from the search path.
13507[clinic start generated code]*/
13508
13509static PyObject *
13510os__add_dll_directory_impl(PyObject *module, path_t *path)
13511/*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
13512{
13513 HMODULE hKernel32;
13514 PAddDllDirectory AddDllDirectory;
13515 DLL_DIRECTORY_COOKIE cookie = 0;
13516 DWORD err = 0;
13517
13518 /* For Windows 7, we have to load this. As this will be a fairly
13519 infrequent operation, just do it each time. Kernel32 is always
13520 loaded. */
13521 Py_BEGIN_ALLOW_THREADS
13522 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13523 !(AddDllDirectory = (PAddDllDirectory)GetProcAddress(
13524 hKernel32, "AddDllDirectory")) ||
13525 !(cookie = (*AddDllDirectory)(path->wide))) {
13526 err = GetLastError();
13527 }
13528 Py_END_ALLOW_THREADS
13529
13530 if (err) {
13531 return win32_error_object_err("add_dll_directory",
13532 path->object, err);
13533 }
13534
13535 return PyCapsule_New(cookie, "DLL directory cookie", NULL);
13536}
13537
13538/*[clinic input]
13539os._remove_dll_directory
13540
13541 cookie: object
13542
13543Removes a path from the DLL search path.
13544
13545The parameter is an opaque value that was returned from
13546os.add_dll_directory. You can only remove directories that you added
13547yourself.
13548[clinic start generated code]*/
13549
13550static PyObject *
13551os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
13552/*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
13553{
13554 HMODULE hKernel32;
13555 PRemoveDllDirectory RemoveDllDirectory;
13556 DLL_DIRECTORY_COOKIE cookieValue;
13557 DWORD err = 0;
13558
13559 if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
13560 PyErr_SetString(PyExc_TypeError,
13561 "Provided cookie was not returned from os.add_dll_directory");
13562 return NULL;
13563 }
13564
13565 cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
13566 cookie, "DLL directory cookie");
13567
13568 /* For Windows 7, we have to load this. As this will be a fairly
13569 infrequent operation, just do it each time. Kernel32 is always
13570 loaded. */
13571 Py_BEGIN_ALLOW_THREADS
13572 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13573 !(RemoveDllDirectory = (PRemoveDllDirectory)GetProcAddress(
13574 hKernel32, "RemoveDllDirectory")) ||
13575 !(*RemoveDllDirectory)(cookieValue)) {
13576 err = GetLastError();
13577 }
13578 Py_END_ALLOW_THREADS
13579
13580 if (err) {
13581 return win32_error_object_err("remove_dll_directory",
13582 NULL, err);
13583 }
13584
13585 if (PyCapsule_SetName(cookie, NULL)) {
13586 return NULL;
13587 }
13588
13589 Py_RETURN_NONE;
13590}
13591
13592#endif
Larry Hastings31826802013-10-19 00:09:25 -070013593
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013594static PyMethodDef posix_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -070013595
13596 OS_STAT_METHODDEF
13597 OS_ACCESS_METHODDEF
13598 OS_TTYNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013599 OS_CHDIR_METHODDEF
13600 OS_CHFLAGS_METHODDEF
13601 OS_CHMOD_METHODDEF
13602 OS_FCHMOD_METHODDEF
13603 OS_LCHMOD_METHODDEF
13604 OS_CHOWN_METHODDEF
13605 OS_FCHOWN_METHODDEF
13606 OS_LCHOWN_METHODDEF
13607 OS_LCHFLAGS_METHODDEF
13608 OS_CHROOT_METHODDEF
13609 OS_CTERMID_METHODDEF
13610 OS_GETCWD_METHODDEF
13611 OS_GETCWDB_METHODDEF
13612 OS_LINK_METHODDEF
13613 OS_LISTDIR_METHODDEF
13614 OS_LSTAT_METHODDEF
13615 OS_MKDIR_METHODDEF
13616 OS_NICE_METHODDEF
13617 OS_GETPRIORITY_METHODDEF
13618 OS_SETPRIORITY_METHODDEF
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000013619 OS_POSIX_SPAWN_METHODDEF
Joannah Nanjekye92b83222019-01-16 16:29:26 +030013620 OS_POSIX_SPAWNP_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013621 OS_READLINK_METHODDEF
Pablo Galindoaac4d032019-05-31 19:39:47 +010013622 OS_COPY_FILE_RANGE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013623 OS_RENAME_METHODDEF
13624 OS_REPLACE_METHODDEF
13625 OS_RMDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013626 OS_SYMLINK_METHODDEF
13627 OS_SYSTEM_METHODDEF
13628 OS_UMASK_METHODDEF
13629 OS_UNAME_METHODDEF
13630 OS_UNLINK_METHODDEF
13631 OS_REMOVE_METHODDEF
13632 OS_UTIME_METHODDEF
13633 OS_TIMES_METHODDEF
13634 OS__EXIT_METHODDEF
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020013635 OS__FCOPYFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013636 OS_EXECV_METHODDEF
13637 OS_EXECVE_METHODDEF
13638 OS_SPAWNV_METHODDEF
13639 OS_SPAWNVE_METHODDEF
13640 OS_FORK1_METHODDEF
13641 OS_FORK_METHODDEF
Antoine Pitrou346cbd32017-05-27 17:50:54 +020013642 OS_REGISTER_AT_FORK_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013643 OS_SCHED_GET_PRIORITY_MAX_METHODDEF
13644 OS_SCHED_GET_PRIORITY_MIN_METHODDEF
13645 OS_SCHED_GETPARAM_METHODDEF
13646 OS_SCHED_GETSCHEDULER_METHODDEF
13647 OS_SCHED_RR_GET_INTERVAL_METHODDEF
13648 OS_SCHED_SETPARAM_METHODDEF
13649 OS_SCHED_SETSCHEDULER_METHODDEF
13650 OS_SCHED_YIELD_METHODDEF
13651 OS_SCHED_SETAFFINITY_METHODDEF
13652 OS_SCHED_GETAFFINITY_METHODDEF
13653 OS_OPENPTY_METHODDEF
13654 OS_FORKPTY_METHODDEF
13655 OS_GETEGID_METHODDEF
13656 OS_GETEUID_METHODDEF
13657 OS_GETGID_METHODDEF
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +020013658#ifdef HAVE_GETGROUPLIST
13659 {"getgrouplist", posix_getgrouplist, METH_VARARGS, posix_getgrouplist__doc__},
13660#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013661 OS_GETGROUPS_METHODDEF
13662 OS_GETPID_METHODDEF
13663 OS_GETPGRP_METHODDEF
13664 OS_GETPPID_METHODDEF
13665 OS_GETUID_METHODDEF
13666 OS_GETLOGIN_METHODDEF
13667 OS_KILL_METHODDEF
13668 OS_KILLPG_METHODDEF
13669 OS_PLOCK_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013670#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -070013671 OS_STARTFILE_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013672#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013673 OS_SETUID_METHODDEF
13674 OS_SETEUID_METHODDEF
13675 OS_SETREUID_METHODDEF
13676 OS_SETGID_METHODDEF
13677 OS_SETEGID_METHODDEF
13678 OS_SETREGID_METHODDEF
13679 OS_SETGROUPS_METHODDEF
Antoine Pitroub7572f02009-12-02 20:46:48 +000013680#ifdef HAVE_INITGROUPS
Victor Stinner8c62be82010-05-06 00:08:46 +000013681 {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__},
Antoine Pitroub7572f02009-12-02 20:46:48 +000013682#endif /* HAVE_INITGROUPS */
Larry Hastings2f936352014-08-05 14:04:04 +100013683 OS_GETPGID_METHODDEF
13684 OS_SETPGRP_METHODDEF
13685 OS_WAIT_METHODDEF
13686 OS_WAIT3_METHODDEF
13687 OS_WAIT4_METHODDEF
13688 OS_WAITID_METHODDEF
13689 OS_WAITPID_METHODDEF
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -080013690 OS_PIDFD_OPEN_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013691 OS_GETSID_METHODDEF
13692 OS_SETSID_METHODDEF
13693 OS_SETPGID_METHODDEF
13694 OS_TCGETPGRP_METHODDEF
13695 OS_TCSETPGRP_METHODDEF
13696 OS_OPEN_METHODDEF
13697 OS_CLOSE_METHODDEF
13698 OS_CLOSERANGE_METHODDEF
13699 OS_DEVICE_ENCODING_METHODDEF
13700 OS_DUP_METHODDEF
13701 OS_DUP2_METHODDEF
13702 OS_LOCKF_METHODDEF
13703 OS_LSEEK_METHODDEF
13704 OS_READ_METHODDEF
13705 OS_READV_METHODDEF
13706 OS_PREAD_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013707 OS_PREADV_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013708 OS_WRITE_METHODDEF
13709 OS_WRITEV_METHODDEF
13710 OS_PWRITE_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013711 OS_PWRITEV_METHODDEF
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013712#ifdef HAVE_SENDFILE
Serhiy Storchaka62be7422018-11-27 13:27:31 +020013713 {"sendfile", (PyCFunction)(void(*)(void))posix_sendfile, METH_VARARGS | METH_KEYWORDS,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013714 posix_sendfile__doc__},
13715#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013716 OS_FSTAT_METHODDEF
13717 OS_ISATTY_METHODDEF
13718 OS_PIPE_METHODDEF
13719 OS_PIPE2_METHODDEF
13720 OS_MKFIFO_METHODDEF
13721 OS_MKNOD_METHODDEF
13722 OS_MAJOR_METHODDEF
13723 OS_MINOR_METHODDEF
13724 OS_MAKEDEV_METHODDEF
13725 OS_FTRUNCATE_METHODDEF
13726 OS_TRUNCATE_METHODDEF
13727 OS_POSIX_FALLOCATE_METHODDEF
13728 OS_POSIX_FADVISE_METHODDEF
13729 OS_PUTENV_METHODDEF
13730 OS_UNSETENV_METHODDEF
13731 OS_STRERROR_METHODDEF
13732 OS_FCHDIR_METHODDEF
13733 OS_FSYNC_METHODDEF
13734 OS_SYNC_METHODDEF
13735 OS_FDATASYNC_METHODDEF
13736 OS_WCOREDUMP_METHODDEF
13737 OS_WIFCONTINUED_METHODDEF
13738 OS_WIFSTOPPED_METHODDEF
13739 OS_WIFSIGNALED_METHODDEF
13740 OS_WIFEXITED_METHODDEF
13741 OS_WEXITSTATUS_METHODDEF
13742 OS_WTERMSIG_METHODDEF
13743 OS_WSTOPSIG_METHODDEF
13744 OS_FSTATVFS_METHODDEF
13745 OS_STATVFS_METHODDEF
13746 OS_CONFSTR_METHODDEF
13747 OS_SYSCONF_METHODDEF
13748 OS_FPATHCONF_METHODDEF
13749 OS_PATHCONF_METHODDEF
13750 OS_ABORT_METHODDEF
Serhiy Storchakaf0b50152015-05-13 00:52:39 +030013751 OS__GETFULLPATHNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013752 OS__GETDISKUSAGE_METHODDEF
13753 OS__GETFINALPATHNAME_METHODDEF
13754 OS__GETVOLUMEPATHNAME_METHODDEF
13755 OS_GETLOADAVG_METHODDEF
13756 OS_URANDOM_METHODDEF
13757 OS_SETRESUID_METHODDEF
13758 OS_SETRESGID_METHODDEF
13759 OS_GETRESUID_METHODDEF
13760 OS_GETRESGID_METHODDEF
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000013761
Larry Hastings2f936352014-08-05 14:04:04 +100013762 OS_GETXATTR_METHODDEF
13763 OS_SETXATTR_METHODDEF
13764 OS_REMOVEXATTR_METHODDEF
13765 OS_LISTXATTR_METHODDEF
13766
Antoine Pitroubcf2b592012-02-08 23:28:36 +010013767#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
13768 {"get_terminal_size", get_terminal_size, METH_VARARGS, termsize__doc__},
13769#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013770 OS_CPU_COUNT_METHODDEF
13771 OS_GET_INHERITABLE_METHODDEF
13772 OS_SET_INHERITABLE_METHODDEF
13773 OS_GET_HANDLE_INHERITABLE_METHODDEF
13774 OS_SET_HANDLE_INHERITABLE_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013775#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013776 OS_GET_BLOCKING_METHODDEF
13777 OS_SET_BLOCKING_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013778#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013779 OS_SCANDIR_METHODDEF
Ethan Furman410ef8e2016-06-04 12:06:26 -070013780 OS_FSPATH_METHODDEF
Victor Stinner9b1f4742016-09-06 16:18:52 -070013781 OS_GETRANDOM_METHODDEF
Zackery Spytz43fdbd22019-05-29 13:57:07 -060013782 OS_MEMFD_CREATE_METHODDEF
Steve Dower2438cdf2019-03-29 16:37:16 -070013783#ifdef MS_WINDOWS
13784 OS__ADD_DLL_DIRECTORY_METHODDEF
13785 OS__REMOVE_DLL_DIRECTORY_METHODDEF
13786#endif
Victor Stinner8c62be82010-05-06 00:08:46 +000013787 {NULL, NULL} /* Sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013788};
13789
Barry Warsaw4a342091996-12-19 23:50:02 +000013790static int
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013791all_ins(PyObject *m)
Barry Warsaw4a342091996-12-19 23:50:02 +000013792{
Guido van Rossum94f6f721999-01-06 18:42:14 +000013793#ifdef F_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013794 if (PyModule_AddIntMacro(m, F_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013795#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013796#ifdef R_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013797 if (PyModule_AddIntMacro(m, R_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013798#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013799#ifdef W_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013800 if (PyModule_AddIntMacro(m, W_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013801#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013802#ifdef X_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013803 if (PyModule_AddIntMacro(m, X_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013804#endif
Fred Drakec9680921999-12-13 16:37:25 +000013805#ifdef NGROUPS_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013806 if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
Fred Drakec9680921999-12-13 16:37:25 +000013807#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013808#ifdef TMP_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013809 if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013810#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013811#ifdef WCONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013812 if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013813#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013814#ifdef WNOHANG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013815 if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013816#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013817#ifdef WUNTRACED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013818 if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013819#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013820#ifdef O_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013821 if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013822#endif
13823#ifdef O_WRONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013824 if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013825#endif
13826#ifdef O_RDWR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013827 if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013828#endif
13829#ifdef O_NDELAY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013830 if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013831#endif
13832#ifdef O_NONBLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013833 if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013834#endif
13835#ifdef O_APPEND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013836 if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013837#endif
13838#ifdef O_DSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013839 if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013840#endif
13841#ifdef O_RSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013842 if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013843#endif
13844#ifdef O_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013845 if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013846#endif
13847#ifdef O_NOCTTY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013848 if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013849#endif
13850#ifdef O_CREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013851 if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013852#endif
13853#ifdef O_EXCL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013854 if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013855#endif
13856#ifdef O_TRUNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013857 if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013858#endif
Guido van Rossum98d9d091997-08-08 21:48:51 +000013859#ifdef O_BINARY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013860 if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013861#endif
13862#ifdef O_TEXT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013863 if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013864#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013865#ifdef O_XATTR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013866 if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013867#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013868#ifdef O_LARGEFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013869 if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013870#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013871#ifndef __GNU__
Skip Montanaro5ff14922005-05-16 02:42:22 +000013872#ifdef O_SHLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013873 if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013874#endif
13875#ifdef O_EXLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013876 if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013877#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013878#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013879#ifdef O_EXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013880 if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013881#endif
13882#ifdef O_SEARCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013883 if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013884#endif
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013885#ifdef O_PATH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013886 if (PyModule_AddIntMacro(m, O_PATH)) return -1;
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013887#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013888#ifdef O_TTY_INIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013889 if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013890#endif
Christian Heimes177b3f92013-08-16 14:35:09 +020013891#ifdef O_TMPFILE
13892 if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
13893#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013894#ifdef PRIO_PROCESS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013895 if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013896#endif
13897#ifdef PRIO_PGRP
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013898 if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013899#endif
13900#ifdef PRIO_USER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013901 if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013902#endif
Charles-François Natali1e045b12011-05-22 20:42:32 +020013903#ifdef O_CLOEXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013904 if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
Charles-François Natali1e045b12011-05-22 20:42:32 +020013905#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013906#ifdef O_ACCMODE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013907 if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013908#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013909
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013910
Jesus Cea94363612012-06-22 18:32:07 +020013911#ifdef SEEK_HOLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013912 if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013913#endif
13914#ifdef SEEK_DATA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013915 if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013916#endif
13917
Tim Peters5aa91602002-01-30 05:46:57 +000013918/* MS Windows */
13919#ifdef O_NOINHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000013920 /* Don't inherit in child processes. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013921 if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013922#endif
13923#ifdef _O_SHORT_LIVED
Victor Stinner8c62be82010-05-06 00:08:46 +000013924 /* Optimize for short life (keep in memory). */
13925 /* MS forgot to define this one with a non-underscore form too. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013926 if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013927#endif
13928#ifdef O_TEMPORARY
Victor Stinner8c62be82010-05-06 00:08:46 +000013929 /* Automatically delete when last handle is closed. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013930 if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013931#endif
13932#ifdef O_RANDOM
Victor Stinner8c62be82010-05-06 00:08:46 +000013933 /* Optimize for random access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013934 if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013935#endif
13936#ifdef O_SEQUENTIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000013937 /* Optimize for sequential access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013938 if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013939#endif
13940
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013941/* GNU extensions. */
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013942#ifdef O_ASYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000013943 /* Send a SIGIO signal whenever input or output
13944 becomes available on file descriptor */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013945 if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013946#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013947#ifdef O_DIRECT
Victor Stinner8c62be82010-05-06 00:08:46 +000013948 /* Direct disk access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013949 if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013950#endif
13951#ifdef O_DIRECTORY
Victor Stinner8c62be82010-05-06 00:08:46 +000013952 /* Must be a directory. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013953 if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013954#endif
13955#ifdef O_NOFOLLOW
Victor Stinner8c62be82010-05-06 00:08:46 +000013956 /* Do not follow links. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013957 if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013958#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013959#ifdef O_NOLINKS
13960 /* Fails if link count of the named file is greater than 1 */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013961 if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013962#endif
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000013963#ifdef O_NOATIME
Victor Stinner8c62be82010-05-06 00:08:46 +000013964 /* Do not update the access time. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013965 if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000013966#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +000013967
Victor Stinner8c62be82010-05-06 00:08:46 +000013968 /* These come from sysexits.h */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013969#ifdef EX_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013970 if (PyModule_AddIntMacro(m, EX_OK)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013971#endif /* EX_OK */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013972#ifdef EX_USAGE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013973 if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013974#endif /* EX_USAGE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013975#ifdef EX_DATAERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013976 if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013977#endif /* EX_DATAERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013978#ifdef EX_NOINPUT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013979 if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013980#endif /* EX_NOINPUT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013981#ifdef EX_NOUSER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013982 if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013983#endif /* EX_NOUSER */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013984#ifdef EX_NOHOST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013985 if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013986#endif /* EX_NOHOST */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013987#ifdef EX_UNAVAILABLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013988 if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013989#endif /* EX_UNAVAILABLE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013990#ifdef EX_SOFTWARE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013991 if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013992#endif /* EX_SOFTWARE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013993#ifdef EX_OSERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013994 if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013995#endif /* EX_OSERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013996#ifdef EX_OSFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013997 if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013998#endif /* EX_OSFILE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013999#ifdef EX_CANTCREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014000 if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014001#endif /* EX_CANTCREAT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014002#ifdef EX_IOERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014003 if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014004#endif /* EX_IOERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014005#ifdef EX_TEMPFAIL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014006 if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014007#endif /* EX_TEMPFAIL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014008#ifdef EX_PROTOCOL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014009 if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014010#endif /* EX_PROTOCOL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014011#ifdef EX_NOPERM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014012 if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014013#endif /* EX_NOPERM */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014014#ifdef EX_CONFIG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014015 if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014016#endif /* EX_CONFIG */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014017#ifdef EX_NOTFOUND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014018 if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014019#endif /* EX_NOTFOUND */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014020
Amaury Forgeot d'Arc66d00ad2010-09-10 18:11:45 +000014021 /* statvfs */
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014022#ifdef ST_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014023 if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014024#endif /* ST_RDONLY */
14025#ifdef ST_NOSUID
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014026 if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014027#endif /* ST_NOSUID */
14028
doko@ubuntu.comca616a22013-12-08 15:23:07 +010014029 /* GNU extensions */
14030#ifdef ST_NODEV
14031 if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
14032#endif /* ST_NODEV */
14033#ifdef ST_NOEXEC
14034 if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
14035#endif /* ST_NOEXEC */
14036#ifdef ST_SYNCHRONOUS
14037 if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
14038#endif /* ST_SYNCHRONOUS */
14039#ifdef ST_MANDLOCK
14040 if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
14041#endif /* ST_MANDLOCK */
14042#ifdef ST_WRITE
14043 if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
14044#endif /* ST_WRITE */
14045#ifdef ST_APPEND
14046 if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
14047#endif /* ST_APPEND */
14048#ifdef ST_NOATIME
14049 if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
14050#endif /* ST_NOATIME */
14051#ifdef ST_NODIRATIME
14052 if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
14053#endif /* ST_NODIRATIME */
14054#ifdef ST_RELATIME
14055 if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
14056#endif /* ST_RELATIME */
14057
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014058 /* FreeBSD sendfile() constants */
14059#ifdef SF_NODISKIO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014060 if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014061#endif
14062#ifdef SF_MNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014063 if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014064#endif
14065#ifdef SF_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014066 if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014067#endif
14068
Ross Lagerwall7807c352011-03-17 20:20:30 +020014069 /* constants for posix_fadvise */
14070#ifdef POSIX_FADV_NORMAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014071 if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014072#endif
14073#ifdef POSIX_FADV_SEQUENTIAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014074 if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014075#endif
14076#ifdef POSIX_FADV_RANDOM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014077 if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014078#endif
14079#ifdef POSIX_FADV_NOREUSE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014080 if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014081#endif
14082#ifdef POSIX_FADV_WILLNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014083 if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014084#endif
14085#ifdef POSIX_FADV_DONTNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014086 if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014087#endif
14088
14089 /* constants for waitid */
14090#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014091 if (PyModule_AddIntMacro(m, P_PID)) return -1;
14092 if (PyModule_AddIntMacro(m, P_PGID)) return -1;
14093 if (PyModule_AddIntMacro(m, P_ALL)) return -1;
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080014094#ifdef P_PIDFD
14095 if (PyModule_AddIntMacro(m, P_PIDFD)) return -1;
14096#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014097#endif
14098#ifdef WEXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014099 if (PyModule_AddIntMacro(m, WEXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014100#endif
14101#ifdef WNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014102 if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014103#endif
14104#ifdef WSTOPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014105 if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014106#endif
14107#ifdef CLD_EXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014108 if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014109#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014110#ifdef CLD_KILLED
14111 if (PyModule_AddIntMacro(m, CLD_KILLED)) return -1;
14112#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014113#ifdef CLD_DUMPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014114 if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014115#endif
14116#ifdef CLD_TRAPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014117 if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014118#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014119#ifdef CLD_STOPPED
14120 if (PyModule_AddIntMacro(m, CLD_STOPPED)) return -1;
14121#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014122#ifdef CLD_CONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014123 if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014124#endif
14125
14126 /* constants for lockf */
14127#ifdef F_LOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014128 if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014129#endif
14130#ifdef F_TLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014131 if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014132#endif
14133#ifdef F_ULOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014134 if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014135#endif
14136#ifdef F_TEST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014137 if (PyModule_AddIntMacro(m, F_TEST)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014138#endif
14139
Pablo Galindo4defba32018-01-27 16:16:37 +000014140#ifdef RWF_DSYNC
14141 if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
14142#endif
14143#ifdef RWF_HIPRI
14144 if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
14145#endif
14146#ifdef RWF_SYNC
14147 if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
14148#endif
14149#ifdef RWF_NOWAIT
14150 if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
14151#endif
14152
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000014153/* constants for posix_spawn */
14154#ifdef HAVE_POSIX_SPAWN
14155 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
14156 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
14157 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
14158#endif
14159
pxinwrf2d7ac72019-05-21 18:46:37 +080014160#if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014161 if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
14162 if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014163 if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
pxinwrf2d7ac72019-05-21 18:46:37 +080014164#endif
14165#ifdef HAVE_SPAWNV
14166 if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014167 if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
Guido van Rossum246bc171999-02-01 23:54:31 +000014168#endif
14169
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014170#ifdef HAVE_SCHED_H
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014171#ifdef SCHED_OTHER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014172 if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014173#endif
14174#ifdef SCHED_FIFO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014175 if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014176#endif
14177#ifdef SCHED_RR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014178 if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014179#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014180#ifdef SCHED_SPORADIC
messi Liao0d322182017-06-13 22:30:43 +080014181 if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014182#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014183#ifdef SCHED_BATCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014184 if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014185#endif
14186#ifdef SCHED_IDLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014187 if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014188#endif
14189#ifdef SCHED_RESET_ON_FORK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014190 if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014191#endif
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014192#ifdef SCHED_SYS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014193 if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014194#endif
14195#ifdef SCHED_IA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014196 if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014197#endif
14198#ifdef SCHED_FSS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014199 if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014200#endif
14201#ifdef SCHED_FX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014202 if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014203#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014204#endif
14205
Benjamin Peterson9428d532011-09-14 11:45:52 -040014206#ifdef USE_XATTRS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014207 if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
14208 if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
14209 if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
Benjamin Peterson799bd802011-08-31 22:15:17 -040014210#endif
14211
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014212#if HAVE_DECL_RTLD_LAZY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014213 if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014214#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014215#if HAVE_DECL_RTLD_NOW
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014216 if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014217#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014218#if HAVE_DECL_RTLD_GLOBAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014219 if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014220#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014221#if HAVE_DECL_RTLD_LOCAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014222 if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014223#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014224#if HAVE_DECL_RTLD_NODELETE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014225 if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014226#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014227#if HAVE_DECL_RTLD_NOLOAD
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014228 if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014229#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014230#if HAVE_DECL_RTLD_DEEPBIND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014231 if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014232#endif
Michael Feltc5ae1692017-12-19 13:58:49 +010014233#if HAVE_DECL_RTLD_MEMBER
14234 if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
14235#endif
Victor Stinner8b905bd2011-10-25 13:34:04 +020014236
Victor Stinner9b1f4742016-09-06 16:18:52 -070014237#ifdef HAVE_GETRANDOM_SYSCALL
14238 if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
14239 if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
14240#endif
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014241#ifdef HAVE_MEMFD_CREATE
14242 if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
14243 if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
14244#ifdef MFD_HUGETLB
14245 if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014246#endif
14247#ifdef MFD_HUGE_SHIFT
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014248 if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014249#endif
14250#ifdef MFD_HUGE_MASK
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014251 if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014252#endif
14253#ifdef MFD_HUGE_64KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014254 if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014255#endif
14256#ifdef MFD_HUGE_512KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014257 if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014258#endif
14259#ifdef MFD_HUGE_1MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014260 if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014261#endif
14262#ifdef MFD_HUGE_2MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014263 if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014264#endif
14265#ifdef MFD_HUGE_8MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014266 if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014267#endif
14268#ifdef MFD_HUGE_16MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014269 if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014270#endif
14271#ifdef MFD_HUGE_32MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014272 if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014273#endif
14274#ifdef MFD_HUGE_256MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014275 if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014276#endif
14277#ifdef MFD_HUGE_512MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014278 if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014279#endif
14280#ifdef MFD_HUGE_1GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014281 if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014282#endif
14283#ifdef MFD_HUGE_2GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014284 if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014285#endif
14286#ifdef MFD_HUGE_16GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014287 if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
14288#endif
14289#endif
Victor Stinner9b1f4742016-09-06 16:18:52 -070014290
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020014291#if defined(__APPLE__)
14292 if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
14293#endif
14294
Steve Dower2438cdf2019-03-29 16:37:16 -070014295#ifdef MS_WINDOWS
14296 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
14297 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
14298 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
14299 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
14300 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
14301#endif
14302
Victor Stinner8c62be82010-05-06 00:08:46 +000014303 return 0;
Barry Warsaw4a342091996-12-19 23:50:02 +000014304}
14305
14306
Martin v. Löwis1a214512008-06-11 05:26:20 +000014307static struct PyModuleDef posixmodule = {
Victor Stinner8c62be82010-05-06 00:08:46 +000014308 PyModuleDef_HEAD_INIT,
14309 MODNAME,
14310 posix__doc__,
Eddie Elizondob3966632019-11-05 07:16:14 -080014311 sizeof(_posixstate),
Victor Stinner8c62be82010-05-06 00:08:46 +000014312 posix_methods,
14313 NULL,
Eddie Elizondob3966632019-11-05 07:16:14 -080014314 _posix_traverse,
14315 _posix_clear,
14316 _posix_free,
Martin v. Löwis1a214512008-06-11 05:26:20 +000014317};
14318
14319
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014320static const char * const have_functions[] = {
Larry Hastings9cf065c2012-06-22 16:30:09 -070014321
14322#ifdef HAVE_FACCESSAT
14323 "HAVE_FACCESSAT",
14324#endif
14325
14326#ifdef HAVE_FCHDIR
14327 "HAVE_FCHDIR",
14328#endif
14329
14330#ifdef HAVE_FCHMOD
14331 "HAVE_FCHMOD",
14332#endif
14333
14334#ifdef HAVE_FCHMODAT
14335 "HAVE_FCHMODAT",
14336#endif
14337
14338#ifdef HAVE_FCHOWN
14339 "HAVE_FCHOWN",
14340#endif
14341
Larry Hastings00964ed2013-08-12 13:49:30 -040014342#ifdef HAVE_FCHOWNAT
14343 "HAVE_FCHOWNAT",
14344#endif
14345
Larry Hastings9cf065c2012-06-22 16:30:09 -070014346#ifdef HAVE_FEXECVE
14347 "HAVE_FEXECVE",
14348#endif
14349
14350#ifdef HAVE_FDOPENDIR
14351 "HAVE_FDOPENDIR",
14352#endif
14353
Georg Brandl306336b2012-06-24 12:55:33 +020014354#ifdef HAVE_FPATHCONF
14355 "HAVE_FPATHCONF",
14356#endif
14357
Larry Hastings9cf065c2012-06-22 16:30:09 -070014358#ifdef HAVE_FSTATAT
14359 "HAVE_FSTATAT",
14360#endif
14361
14362#ifdef HAVE_FSTATVFS
14363 "HAVE_FSTATVFS",
14364#endif
14365
Steve Dowerfe0a41a2015-03-20 19:50:46 -070014366#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Georg Brandl306336b2012-06-24 12:55:33 +020014367 "HAVE_FTRUNCATE",
14368#endif
14369
Larry Hastings9cf065c2012-06-22 16:30:09 -070014370#ifdef HAVE_FUTIMENS
14371 "HAVE_FUTIMENS",
14372#endif
14373
14374#ifdef HAVE_FUTIMES
14375 "HAVE_FUTIMES",
14376#endif
14377
14378#ifdef HAVE_FUTIMESAT
14379 "HAVE_FUTIMESAT",
14380#endif
14381
14382#ifdef HAVE_LINKAT
14383 "HAVE_LINKAT",
14384#endif
14385
14386#ifdef HAVE_LCHFLAGS
14387 "HAVE_LCHFLAGS",
14388#endif
14389
14390#ifdef HAVE_LCHMOD
14391 "HAVE_LCHMOD",
14392#endif
14393
14394#ifdef HAVE_LCHOWN
14395 "HAVE_LCHOWN",
14396#endif
14397
14398#ifdef HAVE_LSTAT
14399 "HAVE_LSTAT",
14400#endif
14401
14402#ifdef HAVE_LUTIMES
14403 "HAVE_LUTIMES",
14404#endif
14405
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014406#ifdef HAVE_MEMFD_CREATE
14407 "HAVE_MEMFD_CREATE",
14408#endif
14409
Larry Hastings9cf065c2012-06-22 16:30:09 -070014410#ifdef HAVE_MKDIRAT
14411 "HAVE_MKDIRAT",
14412#endif
14413
14414#ifdef HAVE_MKFIFOAT
14415 "HAVE_MKFIFOAT",
14416#endif
14417
14418#ifdef HAVE_MKNODAT
14419 "HAVE_MKNODAT",
14420#endif
14421
14422#ifdef HAVE_OPENAT
14423 "HAVE_OPENAT",
14424#endif
14425
14426#ifdef HAVE_READLINKAT
14427 "HAVE_READLINKAT",
14428#endif
14429
14430#ifdef HAVE_RENAMEAT
14431 "HAVE_RENAMEAT",
14432#endif
14433
14434#ifdef HAVE_SYMLINKAT
14435 "HAVE_SYMLINKAT",
14436#endif
14437
14438#ifdef HAVE_UNLINKAT
14439 "HAVE_UNLINKAT",
14440#endif
14441
14442#ifdef HAVE_UTIMENSAT
14443 "HAVE_UTIMENSAT",
14444#endif
14445
14446#ifdef MS_WINDOWS
14447 "MS_WINDOWS",
14448#endif
14449
14450 NULL
14451};
14452
14453
Mark Hammondfe51c6d2002-08-02 02:27:13 +000014454PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +000014455INITFUNC(void)
Guido van Rossumb6775db1994-08-01 11:34:53 +000014456{
Victor Stinner8c62be82010-05-06 00:08:46 +000014457 PyObject *m, *v;
Larry Hastings9cf065c2012-06-22 16:30:09 -070014458 PyObject *list;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014459 const char * const *trace;
Tim Peters5aa91602002-01-30 05:46:57 +000014460
Eddie Elizondob3966632019-11-05 07:16:14 -080014461 m = PyState_FindModule(&posixmodule);
14462 if (m != NULL) {
14463 Py_INCREF(m);
14464 return m;
14465 }
14466
Victor Stinner8c62be82010-05-06 00:08:46 +000014467 m = PyModule_Create(&posixmodule);
14468 if (m == NULL)
14469 return NULL;
Tim Peters5aa91602002-01-30 05:46:57 +000014470
Victor Stinner8c62be82010-05-06 00:08:46 +000014471 /* Initialize environ dictionary */
14472 v = convertenviron();
14473 Py_XINCREF(v);
14474 if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
14475 return NULL;
14476 Py_DECREF(v);
Fred Drakec9680921999-12-13 16:37:25 +000014477
Victor Stinner8c62be82010-05-06 00:08:46 +000014478 if (all_ins(m))
14479 return NULL;
Barry Warsaw4a342091996-12-19 23:50:02 +000014480
Victor Stinner8c62be82010-05-06 00:08:46 +000014481 if (setup_confname_tables(m))
14482 return NULL;
Fred Drakebec628d1999-12-15 18:31:10 +000014483
Victor Stinner8c62be82010-05-06 00:08:46 +000014484 Py_INCREF(PyExc_OSError);
14485 PyModule_AddObject(m, "error", PyExc_OSError);
Fred Drake762e2061999-08-26 17:23:54 +000014486
Ross Lagerwall7807c352011-03-17 20:20:30 +020014487#if defined(HAVE_WAITID) && !defined(__APPLE__)
Eddie Elizondob3966632019-11-05 07:16:14 -080014488 waitid_result_desc.name = MODNAME ".waitid_result";
14489 PyObject *WaitidResultType = (PyObject *)PyStructSequence_NewType(&waitid_result_desc);
14490 if (WaitidResultType == NULL) {
14491 return NULL;
14492 }
14493 Py_INCREF(WaitidResultType);
14494 PyModule_AddObject(m, "waitid_result", WaitidResultType);
14495 _posixstate(m)->WaitidResultType = WaitidResultType;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014496#endif
14497
Eddie Elizondob3966632019-11-05 07:16:14 -080014498 stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
14499 stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
14500 stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
14501 stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
14502 PyObject *StatResultType = (PyObject *)PyStructSequence_NewType(&stat_result_desc);
14503 if (StatResultType == NULL) {
14504 return NULL;
14505 }
14506 Py_INCREF(StatResultType);
14507 PyModule_AddObject(m, "stat_result", StatResultType);
14508 _posixstate(m)->StatResultType = StatResultType;
14509 structseq_new = ((PyTypeObject *)StatResultType)->tp_new;
14510 ((PyTypeObject *)StatResultType)->tp_new = statresult_new;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014511
Eddie Elizondob3966632019-11-05 07:16:14 -080014512 statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
14513 PyObject *StatVFSResultType = (PyObject *)PyStructSequence_NewType(&statvfs_result_desc);
14514 if (StatVFSResultType == NULL) {
14515 return NULL;
14516 }
14517 Py_INCREF(StatVFSResultType);
14518 PyModule_AddObject(m, "statvfs_result", StatVFSResultType);
14519 _posixstate(m)->StatVFSResultType = StatVFSResultType;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014520#ifdef NEED_TICKS_PER_SECOND
14521# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Eddie Elizondob3966632019-11-05 07:16:14 -080014522 ticks_per_second = sysconf(_SC_CLK_TCK);
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014523# elif defined(HZ)
Eddie Elizondob3966632019-11-05 07:16:14 -080014524 ticks_per_second = HZ;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014525# else
Eddie Elizondob3966632019-11-05 07:16:14 -080014526 ticks_per_second = 60; /* magic fallback value; may be bogus */
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014527# endif
14528#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014529
William Orr81574b82018-10-01 22:19:56 -070014530#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Eddie Elizondob3966632019-11-05 07:16:14 -080014531 sched_param_desc.name = MODNAME ".sched_param";
14532 PyObject *SchedParamType = (PyObject *)PyStructSequence_NewType(&sched_param_desc);
14533 if (SchedParamType == NULL) {
14534 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000014535 }
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014536 Py_INCREF(SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -080014537 PyModule_AddObject(m, "sched_param", SchedParamType);
14538 _posixstate(m)->SchedParamType = SchedParamType;
14539 ((PyTypeObject *)SchedParamType)->tp_new = os_sched_param;
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014540#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +000014541
Eddie Elizondob3966632019-11-05 07:16:14 -080014542 /* initialize TerminalSize_info */
14543 PyObject *TerminalSizeType = (PyObject *)PyStructSequence_NewType(&TerminalSize_desc);
14544 if (TerminalSizeType == NULL) {
14545 return NULL;
14546 }
14547 Py_INCREF(TerminalSizeType);
14548 PyModule_AddObject(m, "terminal_size", TerminalSizeType);
14549 _posixstate(m)->TerminalSizeType = TerminalSizeType;
14550
14551 /* initialize scandir types */
14552 PyObject *ScandirIteratorType = PyType_FromSpec(&ScandirIteratorType_spec);
14553 if (ScandirIteratorType == NULL) {
14554 return NULL;
14555 }
14556 _posixstate(m)->ScandirIteratorType = ScandirIteratorType;
14557
14558 PyObject *DirEntryType = PyType_FromSpec(&DirEntryType_spec);
14559 if (DirEntryType == NULL) {
14560 return NULL;
14561 }
14562 Py_INCREF(DirEntryType);
14563 PyModule_AddObject(m, "DirEntry", DirEntryType);
14564 _posixstate(m)->DirEntryType = DirEntryType;
14565
Larry Hastings605a62d2012-06-24 04:33:36 -070014566 times_result_desc.name = MODNAME ".times_result";
Eddie Elizondob3966632019-11-05 07:16:14 -080014567 PyObject *TimesResultType = (PyObject *)PyStructSequence_NewType(&times_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014568 if (TimesResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014569 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014570 }
Eddie Elizondob3966632019-11-05 07:16:14 -080014571 Py_INCREF(TimesResultType);
14572 PyModule_AddObject(m, "times_result", TimesResultType);
14573 _posixstate(m)->TimesResultType = TimesResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070014574
Eddie Elizondob3966632019-11-05 07:16:14 -080014575 PyTypeObject *UnameResultType = PyStructSequence_NewType(&uname_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014576 if (UnameResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014577 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014578 }
Eddie Elizondob3966632019-11-05 07:16:14 -080014579 Py_INCREF(UnameResultType);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014580 PyModule_AddObject(m, "uname_result", (PyObject *)UnameResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -080014581 _posixstate(m)->UnameResultType = (PyObject *)UnameResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070014582
Thomas Wouters477c8d52006-05-27 19:21:47 +000014583#ifdef __APPLE__
Victor Stinner8c62be82010-05-06 00:08:46 +000014584 /*
14585 * Step 2 of weak-linking support on Mac OS X.
14586 *
14587 * The code below removes functions that are not available on the
14588 * currently active platform.
14589 *
14590 * This block allow one to use a python binary that was build on
Larry Hastings9cf065c2012-06-22 16:30:09 -070014591 * OSX 10.4 on OSX 10.3, without losing access to new APIs on
Victor Stinner8c62be82010-05-06 00:08:46 +000014592 * OSX 10.4.
14593 */
Thomas Wouters477c8d52006-05-27 19:21:47 +000014594#ifdef HAVE_FSTATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014595 if (fstatvfs == NULL) {
14596 if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
14597 return NULL;
14598 }
14599 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014600#endif /* HAVE_FSTATVFS */
14601
14602#ifdef HAVE_STATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014603 if (statvfs == NULL) {
14604 if (PyObject_DelAttrString(m, "statvfs") == -1) {
14605 return NULL;
14606 }
14607 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014608#endif /* HAVE_STATVFS */
14609
14610# ifdef HAVE_LCHOWN
Victor Stinner8c62be82010-05-06 00:08:46 +000014611 if (lchown == NULL) {
14612 if (PyObject_DelAttrString(m, "lchown") == -1) {
14613 return NULL;
14614 }
14615 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014616#endif /* HAVE_LCHOWN */
14617
14618
14619#endif /* __APPLE__ */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014620
Eddie Elizondob3966632019-11-05 07:16:14 -080014621 if ((_posixstate(m)->billion = PyLong_FromLong(1000000000)) == NULL)
14622 return NULL;
14623#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
14624 _posixstate(m)->struct_rusage = PyUnicode_InternFromString("struct_rusage");
14625 if (_posixstate(m)->struct_rusage == NULL)
14626 return NULL;
14627#endif
14628 _posixstate(m)->st_mode = PyUnicode_InternFromString("st_mode");
14629 if (_posixstate(m)->st_mode == NULL)
Larry Hastings6fe20b32012-04-19 15:07:49 -070014630 return NULL;
14631
Larry Hastings9cf065c2012-06-22 16:30:09 -070014632 /* suppress "function not used" warnings */
14633 {
14634 int ignored;
14635 fd_specified("", -1);
14636 follow_symlinks_specified("", 1);
14637 dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
14638 dir_fd_converter(Py_None, &ignored);
14639 dir_fd_unavailable(Py_None, &ignored);
14640 }
14641
14642 /*
14643 * provide list of locally available functions
14644 * so os.py can populate support_* lists
14645 */
14646 list = PyList_New(0);
14647 if (!list)
14648 return NULL;
14649 for (trace = have_functions; *trace; trace++) {
14650 PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
14651 if (!unicode)
14652 return NULL;
14653 if (PyList_Append(list, unicode))
14654 return NULL;
14655 Py_DECREF(unicode);
14656 }
14657 PyModule_AddObject(m, "_have_functions", list);
Ned Deilyeb3be662016-08-15 14:40:38 -040014658
Victor Stinner8c62be82010-05-06 00:08:46 +000014659 return m;
Guido van Rossumb6775db1994-08-01 11:34:53 +000014660}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014661
14662#ifdef __cplusplus
14663}
14664#endif