blob: f7386300c5691ac7f8be7a4625aa31c91b151cf0 [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;
824 PyObject *posix_putenv_garbage;
825 PyObject *DirEntryType;
826 PyObject *ScandirIteratorType;
827#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
828 PyObject *SchedParamType;
829#endif
830 PyObject *StatResultType;
831 PyObject *StatVFSResultType;
832 PyObject *TerminalSizeType;
833 PyObject *TimesResultType;
834 PyObject *UnameResultType;
835#if defined(HAVE_WAITID) && !defined(__APPLE__)
836 PyObject *WaitidResultType;
837#endif
838#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
839 PyObject *struct_rusage;
840#endif
841 PyObject *st_mode;
842} _posixstate;
843
844static struct PyModuleDef posixmodule;
845
846#define _posixstate(o) ((_posixstate *)PyModule_GetState(o))
847#define _posixstate_global ((_posixstate *)PyModule_GetState(PyState_FindModule(&posixmodule)))
Larry Hastings9cf065c2012-06-22 16:30:09 -0700848
Larry Hastings9cf065c2012-06-22 16:30:09 -0700849/*
850 * A PyArg_ParseTuple "converter" function
851 * that handles filesystem paths in the manner
852 * preferred by the os module.
853 *
854 * path_converter accepts (Unicode) strings and their
855 * subclasses, and bytes and their subclasses. What
856 * it does with the argument depends on the platform:
857 *
858 * * On Windows, if we get a (Unicode) string we
859 * extract the wchar_t * and return it; if we get
Steve Dowercc16be82016-09-08 10:35:16 -0700860 * bytes we decode to wchar_t * and return that.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700861 *
862 * * On all other platforms, strings are encoded
863 * to bytes using PyUnicode_FSConverter, then we
864 * extract the char * from the bytes object and
865 * return that.
866 *
867 * path_converter also optionally accepts signed
868 * integers (representing open file descriptors) instead
869 * of path strings.
870 *
871 * Input fields:
872 * path.nullable
873 * If nonzero, the path is permitted to be None.
874 * path.allow_fd
875 * If nonzero, the path is permitted to be a file handle
876 * (a signed int) instead of a string.
877 * path.function_name
878 * If non-NULL, path_converter will use that as the name
879 * of the function in error messages.
Larry Hastings31826802013-10-19 00:09:25 -0700880 * (If path.function_name is NULL it omits the function name.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700881 * path.argument_name
882 * If non-NULL, path_converter will use that as the name
883 * of the parameter in error messages.
884 * (If path.argument_name is NULL it uses "path".)
885 *
886 * Output fields:
887 * path.wide
888 * Points to the path if it was expressed as Unicode
889 * and was not encoded. (Only used on Windows.)
890 * path.narrow
891 * Points to the path if it was expressed as bytes,
Steve Dowercc16be82016-09-08 10:35:16 -0700892 * or it was Unicode and was encoded to bytes. (On Windows,
Martin Panterb1321fb2016-10-10 00:38:21 +0000893 * is a non-zero integer if the path was expressed as bytes.
Steve Dowercc16be82016-09-08 10:35:16 -0700894 * The type is deliberately incompatible to prevent misuse.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700895 * path.fd
896 * Contains a file descriptor if path.accept_fd was true
897 * and the caller provided a signed integer instead of any
898 * sort of string.
899 *
900 * WARNING: if your "path" parameter is optional, and is
901 * unspecified, path_converter will never get called.
902 * So if you set allow_fd, you *MUST* initialize path.fd = -1
903 * yourself!
904 * path.length
905 * The length of the path in characters, if specified as
906 * a string.
907 * path.object
Xiang Zhang04316c42017-01-08 23:26:57 +0800908 * The original object passed in (if get a PathLike object,
909 * the result of PyOS_FSPath() is treated as the original object).
910 * Own a reference to the object.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700911 * path.cleanup
912 * For internal use only. May point to a temporary object.
913 * (Pay no attention to the man behind the curtain.)
914 *
915 * At most one of path.wide or path.narrow will be non-NULL.
916 * If path was None and path.nullable was set,
917 * or if path was an integer and path.allow_fd was set,
918 * both path.wide and path.narrow will be NULL
919 * and path.length will be 0.
Georg Brandlf7875592012-06-24 13:58:31 +0200920 *
Larry Hastings9cf065c2012-06-22 16:30:09 -0700921 * path_converter takes care to not write to the path_t
922 * unless it's successful. However it must reset the
923 * "cleanup" field each time it's called.
924 *
925 * Use as follows:
926 * path_t path;
927 * memset(&path, 0, sizeof(path));
928 * PyArg_ParseTuple(args, "O&", path_converter, &path);
929 * // ... use values from path ...
930 * path_cleanup(&path);
931 *
932 * (Note that if PyArg_Parse fails you don't need to call
933 * path_cleanup(). However it is safe to do so.)
934 */
935typedef struct {
Victor Stinner292c8352012-10-30 02:17:38 +0100936 const char *function_name;
937 const char *argument_name;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700938 int nullable;
939 int allow_fd;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300940 const wchar_t *wide;
Steve Dowercc16be82016-09-08 10:35:16 -0700941#ifdef MS_WINDOWS
942 BOOL narrow;
943#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300944 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700945#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700946 int fd;
947 Py_ssize_t length;
948 PyObject *object;
949 PyObject *cleanup;
950} path_t;
951
Steve Dowercc16be82016-09-08 10:35:16 -0700952#ifdef MS_WINDOWS
953#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
954 {function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
955#else
Larry Hastings2f936352014-08-05 14:04:04 +1000956#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
957 {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
Steve Dowercc16be82016-09-08 10:35:16 -0700958#endif
Larry Hastings31826802013-10-19 00:09:25 -0700959
Larry Hastings9cf065c2012-06-22 16:30:09 -0700960static void
Xiang Zhang04316c42017-01-08 23:26:57 +0800961path_cleanup(path_t *path)
962{
963 Py_CLEAR(path->object);
964 Py_CLEAR(path->cleanup);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700965}
966
967static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300968path_converter(PyObject *o, void *p)
969{
Larry Hastings9cf065c2012-06-22 16:30:09 -0700970 path_t *path = (path_t *)p;
Xiang Zhang04316c42017-01-08 23:26:57 +0800971 PyObject *bytes = NULL;
972 Py_ssize_t length = 0;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700973 int is_index, is_buffer, is_bytes, is_unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300974 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700975#ifdef MS_WINDOWS
Xiang Zhang04316c42017-01-08 23:26:57 +0800976 PyObject *wo = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700977 const wchar_t *wide;
978#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700979
980#define FORMAT_EXCEPTION(exc, fmt) \
981 PyErr_Format(exc, "%s%s" fmt, \
982 path->function_name ? path->function_name : "", \
983 path->function_name ? ": " : "", \
984 path->argument_name ? path->argument_name : "path")
985
986 /* Py_CLEANUP_SUPPORTED support */
987 if (o == NULL) {
988 path_cleanup(path);
989 return 1;
990 }
991
Brett Cannon3f9183b2016-08-26 14:44:48 -0700992 /* Ensure it's always safe to call path_cleanup(). */
Xiang Zhang04316c42017-01-08 23:26:57 +0800993 path->object = path->cleanup = NULL;
994 /* path->object owns a reference to the original object */
995 Py_INCREF(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700996
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300997 if ((o == Py_None) && path->nullable) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700998 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700999#ifdef MS_WINDOWS
1000 path->narrow = FALSE;
1001#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001002 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001003#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07001004 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001005 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001006 }
1007
Brett Cannon3f9183b2016-08-26 14:44:48 -07001008 /* Only call this here so that we don't treat the return value of
1009 os.fspath() as an fd or buffer. */
1010 is_index = path->allow_fd && PyIndex_Check(o);
1011 is_buffer = PyObject_CheckBuffer(o);
1012 is_bytes = PyBytes_Check(o);
1013 is_unicode = PyUnicode_Check(o);
1014
1015 if (!is_index && !is_buffer && !is_unicode && !is_bytes) {
1016 /* Inline PyOS_FSPath() for better error messages. */
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001017 PyObject *func, *res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001018
1019 func = _PyObject_LookupSpecial(o, &PyId___fspath__);
1020 if (NULL == func) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001021 goto error_format;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001022 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001023 res = _PyObject_CallNoArg(func);
Brett Cannon3f9183b2016-08-26 14:44:48 -07001024 Py_DECREF(func);
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001025 if (NULL == res) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001026 goto error_exit;
1027 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001028 else if (PyUnicode_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001029 is_unicode = 1;
1030 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001031 else if (PyBytes_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001032 is_bytes = 1;
1033 }
1034 else {
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001035 PyErr_Format(PyExc_TypeError,
1036 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -08001037 "not %.200s", _PyType_Name(Py_TYPE(o)),
1038 _PyType_Name(Py_TYPE(res)));
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001039 Py_DECREF(res);
1040 goto error_exit;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001041 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001042
1043 /* still owns a reference to the original object */
1044 Py_DECREF(o);
1045 o = res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001046 }
1047
1048 if (is_unicode) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001049#ifdef MS_WINDOWS
Victor Stinner26c03bd2016-09-19 11:55:44 +02001050 wide = PyUnicode_AsUnicodeAndSize(o, &length);
Victor Stinner59799a82013-11-13 14:17:30 +01001051 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001052 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001053 }
Victor Stinner59799a82013-11-13 14:17:30 +01001054 if (length > 32767) {
1055 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001056 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001057 }
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001058 if (wcslen(wide) != length) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001059 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001060 goto error_exit;
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001061 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001062
1063 path->wide = wide;
Xiang Zhang04316c42017-01-08 23:26:57 +08001064 path->narrow = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001065 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001066 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001067#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001068 if (!PyUnicode_FSConverter(o, &bytes)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001069 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001070 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001071#endif
1072 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001073 else if (is_bytes) {
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001074 bytes = o;
1075 Py_INCREF(bytes);
1076 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001077 else if (is_buffer) {
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03001078 /* XXX Replace PyObject_CheckBuffer with PyBytes_Check in other code
Ville Skyttä49b27342017-08-03 09:00:59 +03001079 after removing support of non-bytes buffer objects. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001080 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1081 "%s%s%s should be %s, not %.200s",
1082 path->function_name ? path->function_name : "",
1083 path->function_name ? ": " : "",
1084 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001085 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1086 "integer or None" :
1087 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1088 path->nullable ? "string, bytes, os.PathLike or None" :
1089 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001090 _PyType_Name(Py_TYPE(o)))) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001091 goto error_exit;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001092 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001093 bytes = PyBytes_FromObject(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001094 if (!bytes) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001095 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001096 }
1097 }
Steve Dowercc16be82016-09-08 10:35:16 -07001098 else if (is_index) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001099 if (!_fd_converter(o, &path->fd)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001100 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001101 }
1102 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001103#ifdef MS_WINDOWS
1104 path->narrow = FALSE;
1105#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001106 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001107#endif
Xiang Zhang04316c42017-01-08 23:26:57 +08001108 goto success_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001109 }
1110 else {
Xiang Zhang04316c42017-01-08 23:26:57 +08001111 error_format:
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001112 PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
1113 path->function_name ? path->function_name : "",
1114 path->function_name ? ": " : "",
1115 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001116 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1117 "integer or None" :
1118 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1119 path->nullable ? "string, bytes, os.PathLike or None" :
1120 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001121 _PyType_Name(Py_TYPE(o)));
Xiang Zhang04316c42017-01-08 23:26:57 +08001122 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001123 }
1124
Larry Hastings9cf065c2012-06-22 16:30:09 -07001125 length = PyBytes_GET_SIZE(bytes);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001126 narrow = PyBytes_AS_STRING(bytes);
Victor Stinner706768c2014-08-16 01:03:39 +02001127 if ((size_t)length != strlen(narrow)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03001128 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001129 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001130 }
1131
Steve Dowercc16be82016-09-08 10:35:16 -07001132#ifdef MS_WINDOWS
1133 wo = PyUnicode_DecodeFSDefaultAndSize(
1134 narrow,
1135 length
1136 );
1137 if (!wo) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001138 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001139 }
1140
Xiang Zhang04316c42017-01-08 23:26:57 +08001141 wide = PyUnicode_AsUnicodeAndSize(wo, &length);
Steve Dowercc16be82016-09-08 10:35:16 -07001142 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001143 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001144 }
1145 if (length > 32767) {
1146 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001147 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001148 }
1149 if (wcslen(wide) != length) {
1150 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001151 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001152 }
1153 path->wide = wide;
1154 path->narrow = TRUE;
Xiang Zhang04316c42017-01-08 23:26:57 +08001155 path->cleanup = wo;
1156 Py_DECREF(bytes);
Steve Dowercc16be82016-09-08 10:35:16 -07001157#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001158 path->wide = NULL;
1159 path->narrow = narrow;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001160 if (bytes == o) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001161 /* Still a reference owned by path->object, don't have to
1162 worry about path->narrow is used after free. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001163 Py_DECREF(bytes);
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001164 }
1165 else {
1166 path->cleanup = bytes;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001167 }
Xiang Zhang04316c42017-01-08 23:26:57 +08001168#endif
1169 path->fd = -1;
1170
1171 success_exit:
1172 path->length = length;
1173 path->object = o;
1174 return Py_CLEANUP_SUPPORTED;
1175
1176 error_exit:
1177 Py_XDECREF(o);
1178 Py_XDECREF(bytes);
1179#ifdef MS_WINDOWS
1180 Py_XDECREF(wo);
1181#endif
1182 return 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001183}
1184
1185static void
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001186argument_unavailable_error(const char *function_name, const char *argument_name)
1187{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001188 PyErr_Format(PyExc_NotImplementedError,
1189 "%s%s%s unavailable on this platform",
1190 (function_name != NULL) ? function_name : "",
1191 (function_name != NULL) ? ": ": "",
1192 argument_name);
1193}
1194
1195static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001196dir_fd_unavailable(PyObject *o, void *p)
1197{
1198 int dir_fd;
1199 if (!dir_fd_converter(o, &dir_fd))
Larry Hastings9cf065c2012-06-22 16:30:09 -07001200 return 0;
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001201 if (dir_fd != DEFAULT_DIR_FD) {
1202 argument_unavailable_error(NULL, "dir_fd");
1203 return 0;
1204 }
1205 *(int *)p = dir_fd;
1206 return 1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001207}
1208
1209static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001210fd_specified(const char *function_name, int fd)
1211{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001212 if (fd == -1)
1213 return 0;
1214
1215 argument_unavailable_error(function_name, "fd");
1216 return 1;
1217}
1218
1219static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001220follow_symlinks_specified(const char *function_name, int follow_symlinks)
1221{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001222 if (follow_symlinks)
1223 return 0;
1224
1225 argument_unavailable_error(function_name, "follow_symlinks");
1226 return 1;
1227}
1228
1229static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001230path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
1231{
Steve Dowercc16be82016-09-08 10:35:16 -07001232 if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
1233#ifndef MS_WINDOWS
1234 && !path->narrow
1235#endif
1236 ) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001237 PyErr_Format(PyExc_ValueError,
1238 "%s: can't specify dir_fd without matching path",
1239 function_name);
1240 return 1;
1241 }
1242 return 0;
1243}
1244
1245static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001246dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
1247{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001248 if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
1249 PyErr_Format(PyExc_ValueError,
1250 "%s: can't specify both dir_fd and fd",
1251 function_name);
1252 return 1;
1253 }
1254 return 0;
1255}
1256
1257static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001258fd_and_follow_symlinks_invalid(const char *function_name, int fd,
1259 int follow_symlinks)
1260{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001261 if ((fd > 0) && (!follow_symlinks)) {
1262 PyErr_Format(PyExc_ValueError,
1263 "%s: cannot use fd and follow_symlinks together",
1264 function_name);
1265 return 1;
1266 }
1267 return 0;
1268}
1269
1270static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001271dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
1272 int follow_symlinks)
1273{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001274 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
1275 PyErr_Format(PyExc_ValueError,
1276 "%s: cannot use dir_fd and follow_symlinks together",
1277 function_name);
1278 return 1;
1279 }
1280 return 0;
1281}
1282
Larry Hastings2f936352014-08-05 14:04:04 +10001283#ifdef MS_WINDOWS
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001284 typedef long long Py_off_t;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001285#else
Larry Hastings2f936352014-08-05 14:04:04 +10001286 typedef off_t Py_off_t;
1287#endif
1288
1289static int
1290Py_off_t_converter(PyObject *arg, void *addr)
1291{
1292#ifdef HAVE_LARGEFILE_SUPPORT
1293 *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
1294#else
1295 *((Py_off_t *)addr) = PyLong_AsLong(arg);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001296#endif
1297 if (PyErr_Occurred())
1298 return 0;
1299 return 1;
1300}
Larry Hastings2f936352014-08-05 14:04:04 +10001301
1302static PyObject *
1303PyLong_FromPy_off_t(Py_off_t offset)
1304{
1305#ifdef HAVE_LARGEFILE_SUPPORT
1306 return PyLong_FromLongLong(offset);
1307#else
1308 return PyLong_FromLong(offset);
Ross Lagerwallb1e5d592011-09-19 08:30:43 +02001309#endif
Larry Hastings2f936352014-08-05 14:04:04 +10001310}
1311
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001312#ifdef HAVE_SIGSET_T
1313/* Convert an iterable of integers to a sigset.
1314 Return 1 on success, return 0 and raise an exception on error. */
1315int
1316_Py_Sigset_Converter(PyObject *obj, void *addr)
1317{
1318 sigset_t *mask = (sigset_t *)addr;
1319 PyObject *iterator, *item;
1320 long signum;
1321 int overflow;
1322
Rémi Lapeyref0900192019-05-04 01:30:53 +02001323 // The extra parens suppress the unreachable-code warning with clang on MacOS
1324 if (sigemptyset(mask) < (0)) {
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001325 /* Probably only if mask == NULL. */
1326 PyErr_SetFromErrno(PyExc_OSError);
1327 return 0;
1328 }
1329
1330 iterator = PyObject_GetIter(obj);
1331 if (iterator == NULL) {
1332 return 0;
1333 }
1334
1335 while ((item = PyIter_Next(iterator)) != NULL) {
1336 signum = PyLong_AsLongAndOverflow(item, &overflow);
1337 Py_DECREF(item);
1338 if (signum <= 0 || signum >= NSIG) {
1339 if (overflow || signum != -1 || !PyErr_Occurred()) {
1340 PyErr_Format(PyExc_ValueError,
1341 "signal number %ld out of range", signum);
1342 }
1343 goto error;
1344 }
1345 if (sigaddset(mask, (int)signum)) {
1346 if (errno != EINVAL) {
1347 /* Probably impossible */
1348 PyErr_SetFromErrno(PyExc_OSError);
1349 goto error;
1350 }
1351 /* For backwards compatibility, allow idioms such as
1352 * `range(1, NSIG)` but warn about invalid signal numbers
1353 */
1354 const char msg[] =
1355 "invalid signal number %ld, please use valid_signals()";
1356 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
1357 goto error;
1358 }
1359 }
1360 }
1361 if (!PyErr_Occurred()) {
1362 Py_DECREF(iterator);
1363 return 1;
1364 }
1365
1366error:
1367 Py_DECREF(iterator);
1368 return 0;
1369}
1370#endif /* HAVE_SIGSET_T */
1371
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001372#ifdef MS_WINDOWS
Brian Curtinf5e76d02010-11-24 13:14:05 +00001373
1374static int
Brian Curtind25aef52011-06-13 15:16:04 -05001375win32_get_reparse_tag(HANDLE reparse_point_handle, ULONG *reparse_tag)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001376{
Martin Panter70214ad2016-08-04 02:38:59 +00001377 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1378 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001379 DWORD n_bytes_returned;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001380
1381 if (0 == DeviceIoControl(
1382 reparse_point_handle,
1383 FSCTL_GET_REPARSE_POINT,
1384 NULL, 0, /* in buffer */
1385 target_buffer, sizeof(target_buffer),
1386 &n_bytes_returned,
1387 NULL)) /* we're not using OVERLAPPED_IO */
Brian Curtind25aef52011-06-13 15:16:04 -05001388 return FALSE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001389
1390 if (reparse_tag)
1391 *reparse_tag = rdb->ReparseTag;
1392
Brian Curtind25aef52011-06-13 15:16:04 -05001393 return TRUE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001394}
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001395
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001396#endif /* MS_WINDOWS */
Brian Curtinf5e76d02010-11-24 13:14:05 +00001397
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001398/* Return a dictionary corresponding to the POSIX environment table */
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001399#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Jack Jansenea0c3822002-08-01 21:57:49 +00001400/* On Darwin/MacOSX a shared library or framework has no access to
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001401** environ directly, we must obtain it with _NSGetEnviron(). See also
1402** man environ(7).
Jack Jansenea0c3822002-08-01 21:57:49 +00001403*/
1404#include <crt_externs.h>
1405static char **environ;
pxinwrf2d7ac72019-05-21 18:46:37 +08001406#elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001407extern char **environ;
Guido van Rossuma4916fa1996-05-23 22:58:55 +00001408#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001409
Barry Warsaw53699e91996-12-10 23:23:01 +00001410static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001411convertenviron(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001412{
Victor Stinner8c62be82010-05-06 00:08:46 +00001413 PyObject *d;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001414#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00001415 wchar_t **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001416#else
Victor Stinner8c62be82010-05-06 00:08:46 +00001417 char **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001418#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +00001419
Victor Stinner8c62be82010-05-06 00:08:46 +00001420 d = PyDict_New();
1421 if (d == NULL)
1422 return NULL;
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001423#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Victor Stinner8c62be82010-05-06 00:08:46 +00001424 if (environ == NULL)
1425 environ = *_NSGetEnviron();
1426#endif
1427#ifdef MS_WINDOWS
1428 /* _wenviron must be initialized in this way if the program is started
1429 through main() instead of wmain(). */
1430 _wgetenv(L"");
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001431 e = _wenviron;
Victor Stinner8c62be82010-05-06 00:08:46 +00001432#else
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001433 e = environ;
1434#endif
1435 if (e == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +00001436 return d;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001437 for (; *e != NULL; e++) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001438 PyObject *k;
1439 PyObject *v;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001440#ifdef MS_WINDOWS
1441 const wchar_t *p = wcschr(*e, L'=');
1442#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03001443 const char *p = strchr(*e, '=');
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001444#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001445 if (p == NULL)
1446 continue;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001447#ifdef MS_WINDOWS
1448 k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
1449#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001450 k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001451#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001452 if (k == NULL) {
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001453 Py_DECREF(d);
1454 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001455 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001456#ifdef MS_WINDOWS
1457 v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
1458#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001459 v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001460#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001461 if (v == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001462 Py_DECREF(k);
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001463 Py_DECREF(d);
1464 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001465 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001466 if (PyDict_GetItemWithError(d, k) == NULL) {
1467 if (PyErr_Occurred() || PyDict_SetItem(d, k, v) != 0) {
1468 Py_DECREF(v);
1469 Py_DECREF(k);
1470 Py_DECREF(d);
1471 return NULL;
1472 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001473 }
1474 Py_DECREF(k);
1475 Py_DECREF(v);
Guido van Rossumd48f2521997-12-05 22:19:34 +00001476 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001477 return d;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001478}
1479
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001480/* Set a POSIX-specific error from errno, and return NULL */
1481
Barry Warsawd58d7641998-07-23 16:14:40 +00001482static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001483posix_error(void)
Guido van Rossumad0ee831995-03-01 10:34:45 +00001484{
Victor Stinner8c62be82010-05-06 00:08:46 +00001485 return PyErr_SetFromErrno(PyExc_OSError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001486}
Mark Hammondef8b6542001-05-13 08:04:26 +00001487
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001488#ifdef MS_WINDOWS
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001489static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001490win32_error(const char* function, const char* filename)
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001491{
Victor Stinner8c62be82010-05-06 00:08:46 +00001492 /* XXX We should pass the function name along in the future.
1493 (winreg.c also wants to pass the function name.)
1494 This would however require an additional param to the
1495 Windows error object, which is non-trivial.
1496 */
1497 errno = GetLastError();
1498 if (filename)
1499 return PyErr_SetFromWindowsErrWithFilename(errno, filename);
1500 else
1501 return PyErr_SetFromWindowsErr(errno);
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001502}
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001503
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001504static PyObject *
Steve Dower2438cdf2019-03-29 16:37:16 -07001505win32_error_object_err(const char* function, PyObject* filename, DWORD err)
Victor Stinnereb5657a2011-09-30 01:44:27 +02001506{
1507 /* XXX - see win32_error for comments on 'function' */
Victor Stinnereb5657a2011-09-30 01:44:27 +02001508 if (filename)
1509 return PyErr_SetExcFromWindowsErrWithFilenameObject(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001510 PyExc_OSError,
Steve Dower2438cdf2019-03-29 16:37:16 -07001511 err,
Victor Stinnereb5657a2011-09-30 01:44:27 +02001512 filename);
1513 else
Steve Dower2438cdf2019-03-29 16:37:16 -07001514 return PyErr_SetFromWindowsErr(err);
1515}
1516
1517static PyObject *
1518win32_error_object(const char* function, PyObject* filename)
1519{
1520 errno = GetLastError();
1521 return win32_error_object_err(function, filename, errno);
Victor Stinnereb5657a2011-09-30 01:44:27 +02001522}
1523
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001524#endif /* MS_WINDOWS */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001525
Larry Hastings9cf065c2012-06-22 16:30:09 -07001526static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001527posix_path_object_error(PyObject *path)
1528{
1529 return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
1530}
1531
1532static PyObject *
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001533path_object_error(PyObject *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001534{
1535#ifdef MS_WINDOWS
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001536 return PyErr_SetExcFromWindowsErrWithFilenameObject(
1537 PyExc_OSError, 0, path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001538#else
Alexey Izbyshev83460312018-10-20 03:28:22 +03001539 return posix_path_object_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001540#endif
1541}
1542
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001543static PyObject *
1544path_object_error2(PyObject *path, PyObject *path2)
1545{
1546#ifdef MS_WINDOWS
1547 return PyErr_SetExcFromWindowsErrWithFilenameObjects(
1548 PyExc_OSError, 0, path, path2);
1549#else
1550 return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
1551#endif
1552}
1553
1554static PyObject *
1555path_error(path_t *path)
1556{
1557 return path_object_error(path->object);
1558}
Larry Hastings31826802013-10-19 00:09:25 -07001559
Larry Hastingsb0827312014-02-09 22:05:19 -08001560static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001561posix_path_error(path_t *path)
1562{
1563 return posix_path_object_error(path->object);
1564}
1565
1566static PyObject *
Larry Hastingsb0827312014-02-09 22:05:19 -08001567path_error2(path_t *path, path_t *path2)
1568{
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001569 return path_object_error2(path->object, path2->object);
Larry Hastingsb0827312014-02-09 22:05:19 -08001570}
1571
1572
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001573/* POSIX generic methods */
1574
Larry Hastings2f936352014-08-05 14:04:04 +10001575static int
1576fildes_converter(PyObject *o, void *p)
Fred Drake4d1e64b2002-04-15 19:40:07 +00001577{
Victor Stinner8c62be82010-05-06 00:08:46 +00001578 int fd;
Larry Hastings2f936352014-08-05 14:04:04 +10001579 int *pointer = (int *)p;
1580 fd = PyObject_AsFileDescriptor(o);
Victor Stinner8c62be82010-05-06 00:08:46 +00001581 if (fd < 0)
Larry Hastings2f936352014-08-05 14:04:04 +10001582 return 0;
Larry Hastings2f936352014-08-05 14:04:04 +10001583 *pointer = fd;
1584 return 1;
1585}
1586
1587static PyObject *
1588posix_fildes_fd(int fd, int (*func)(int))
1589{
1590 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001591 int async_err = 0;
1592
1593 do {
1594 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001595 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001596 res = (*func)(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001597 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001598 Py_END_ALLOW_THREADS
1599 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1600 if (res != 0)
1601 return (!async_err) ? posix_error() : NULL;
1602 Py_RETURN_NONE;
Fred Drake4d1e64b2002-04-15 19:40:07 +00001603}
Guido van Rossum21142a01999-01-08 21:05:37 +00001604
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001605
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001606#ifdef MS_WINDOWS
Thomas Wouters477c8d52006-05-27 19:21:47 +00001607/* This is a reimplementation of the C library's chdir function,
1608 but one that produces Win32 errors instead of DOS error codes.
1609 chdir is essentially a wrapper around SetCurrentDirectory; however,
1610 it also needs to set "magic" environment variables indicating
1611 the per-drive current directory, which are of the form =<drive>: */
Benjamin Peterson206e3072008-10-19 14:07:49 +00001612static BOOL __stdcall
Thomas Wouters477c8d52006-05-27 19:21:47 +00001613win32_wchdir(LPCWSTR path)
1614{
Victor Stinnered537822015-12-13 21:40:26 +01001615 wchar_t path_buf[MAX_PATH], *new_path = path_buf;
Victor Stinner8c62be82010-05-06 00:08:46 +00001616 int result;
1617 wchar_t env[4] = L"=x:";
Thomas Wouters477c8d52006-05-27 19:21:47 +00001618
Victor Stinner8c62be82010-05-06 00:08:46 +00001619 if(!SetCurrentDirectoryW(path))
1620 return FALSE;
Victor Stinnered537822015-12-13 21:40:26 +01001621 result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001622 if (!result)
1623 return FALSE;
Victor Stinnere847d712015-12-14 00:21:50 +01001624 if (result > Py_ARRAY_LENGTH(path_buf)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001625 new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00001626 if (!new_path) {
1627 SetLastError(ERROR_OUTOFMEMORY);
1628 return FALSE;
1629 }
1630 result = GetCurrentDirectoryW(result, new_path);
1631 if (!result) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001632 PyMem_RawFree(new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001633 return FALSE;
1634 }
1635 }
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001636 int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
1637 wcsncmp(new_path, L"//", 2) == 0);
1638 if (!is_unc_like_path) {
1639 env[1] = new_path[0];
1640 result = SetEnvironmentVariableW(env, new_path);
1641 }
Victor Stinnered537822015-12-13 21:40:26 +01001642 if (new_path != path_buf)
Victor Stinnerb6404912013-07-07 16:21:41 +02001643 PyMem_RawFree(new_path);
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001644 return result ? TRUE : FALSE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001645}
1646#endif
1647
Martin v. Löwis14694662006-02-03 12:54:16 +00001648#ifdef MS_WINDOWS
1649/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
1650 - time stamps are restricted to second resolution
1651 - file modification times suffer from forth-and-back conversions between
1652 UTC and local time
1653 Therefore, we implement our own stat, based on the Win32 API directly.
1654*/
Victor Stinner8c62be82010-05-06 00:08:46 +00001655#define HAVE_STAT_NSEC 1
Zachary Ware63f277b2014-06-19 09:46:37 -05001656#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001657#define HAVE_STRUCT_STAT_ST_REPARSE_TAG 1
Martin v. Löwis14694662006-02-03 12:54:16 +00001658
Victor Stinner6036e442015-03-08 01:58:04 +01001659static void
Steve Dowercc16be82016-09-08 10:35:16 -07001660find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
1661 BY_HANDLE_FILE_INFORMATION *info,
1662 ULONG *reparse_tag)
Victor Stinner6036e442015-03-08 01:58:04 +01001663{
1664 memset(info, 0, sizeof(*info));
1665 info->dwFileAttributes = pFileData->dwFileAttributes;
1666 info->ftCreationTime = pFileData->ftCreationTime;
1667 info->ftLastAccessTime = pFileData->ftLastAccessTime;
1668 info->ftLastWriteTime = pFileData->ftLastWriteTime;
1669 info->nFileSizeHigh = pFileData->nFileSizeHigh;
1670 info->nFileSizeLow = pFileData->nFileSizeLow;
1671/* info->nNumberOfLinks = 1; */
1672 if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
1673 *reparse_tag = pFileData->dwReserved0;
1674 else
1675 *reparse_tag = 0;
1676}
1677
Guido van Rossumd8faa362007-04-27 19:54:29 +00001678static BOOL
Steve Dowercc16be82016-09-08 10:35:16 -07001679attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001680{
Victor Stinner8c62be82010-05-06 00:08:46 +00001681 HANDLE hFindFile;
1682 WIN32_FIND_DATAW FileData;
1683 hFindFile = FindFirstFileW(pszFile, &FileData);
1684 if (hFindFile == INVALID_HANDLE_VALUE)
1685 return FALSE;
1686 FindClose(hFindFile);
Steve Dowercc16be82016-09-08 10:35:16 -07001687 find_data_to_file_info(&FileData, info, reparse_tag);
Victor Stinner8c62be82010-05-06 00:08:46 +00001688 return TRUE;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001689}
1690
Brian Curtind25aef52011-06-13 15:16:04 -05001691static int
Steve Dowercc16be82016-09-08 10:35:16 -07001692win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
Brian Curtind25aef52011-06-13 15:16:04 -05001693 BOOL traverse)
1694{
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001695 HANDLE hFile;
1696 BY_HANDLE_FILE_INFORMATION fileInfo;
1697 FILE_ATTRIBUTE_TAG_INFO tagInfo = { 0 };
1698 DWORD fileType, error;
1699 BOOL isUnhandledTag = FALSE;
1700 int retval = 0;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001701
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001702 DWORD access = FILE_READ_ATTRIBUTES;
1703 DWORD flags = FILE_FLAG_BACKUP_SEMANTICS; /* Allow opening directories. */
1704 if (!traverse) {
1705 flags |= FILE_FLAG_OPEN_REPARSE_POINT;
1706 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001707
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001708 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING, flags, NULL);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001709 if (hFile == INVALID_HANDLE_VALUE) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001710 /* Either the path doesn't exist, or the caller lacks access. */
1711 error = GetLastError();
1712 switch (error) {
1713 case ERROR_ACCESS_DENIED: /* Cannot sync or read attributes. */
1714 case ERROR_SHARING_VIOLATION: /* It's a paging file. */
1715 /* Try reading the parent directory. */
1716 if (!attributes_from_dir(path, &fileInfo, &tagInfo.ReparseTag)) {
1717 /* Cannot read the parent directory. */
1718 SetLastError(error);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001719 return -1;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001720 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001721 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1722 if (traverse ||
1723 !IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1724 /* The stat call has to traverse but cannot, so fail. */
1725 SetLastError(error);
Brian Curtind25aef52011-06-13 15:16:04 -05001726 return -1;
Mark Becwarb82bfac2019-02-02 16:08:23 -05001727 }
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001728 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001729 break;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001730
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001731 case ERROR_INVALID_PARAMETER:
1732 /* \\.\con requires read or write access. */
1733 hFile = CreateFileW(path, access | GENERIC_READ,
1734 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1735 OPEN_EXISTING, flags, NULL);
1736 if (hFile == INVALID_HANDLE_VALUE) {
1737 SetLastError(error);
1738 return -1;
1739 }
1740 break;
1741
1742 case ERROR_CANT_ACCESS_FILE:
1743 /* bpo37834: open unhandled reparse points if traverse fails. */
1744 if (traverse) {
1745 traverse = FALSE;
1746 isUnhandledTag = TRUE;
1747 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING,
1748 flags | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
1749 }
1750 if (hFile == INVALID_HANDLE_VALUE) {
1751 SetLastError(error);
1752 return -1;
1753 }
1754 break;
1755
1756 default:
1757 return -1;
1758 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001759 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001760
1761 if (hFile != INVALID_HANDLE_VALUE) {
1762 /* Handle types other than files on disk. */
1763 fileType = GetFileType(hFile);
1764 if (fileType != FILE_TYPE_DISK) {
1765 if (fileType == FILE_TYPE_UNKNOWN && GetLastError() != 0) {
1766 retval = -1;
1767 goto cleanup;
1768 }
1769 DWORD fileAttributes = GetFileAttributesW(path);
1770 memset(result, 0, sizeof(*result));
1771 if (fileAttributes != INVALID_FILE_ATTRIBUTES &&
1772 fileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1773 /* \\.\pipe\ or \\.\mailslot\ */
1774 result->st_mode = _S_IFDIR;
1775 } else if (fileType == FILE_TYPE_CHAR) {
1776 /* \\.\nul */
1777 result->st_mode = _S_IFCHR;
1778 } else if (fileType == FILE_TYPE_PIPE) {
1779 /* \\.\pipe\spam */
1780 result->st_mode = _S_IFIFO;
1781 }
1782 /* FILE_TYPE_UNKNOWN, e.g. \\.\mailslot\waitfor.exe\spam */
1783 goto cleanup;
1784 }
1785
1786 /* Query the reparse tag, and traverse a non-link. */
1787 if (!traverse) {
1788 if (!GetFileInformationByHandleEx(hFile, FileAttributeTagInfo,
1789 &tagInfo, sizeof(tagInfo))) {
1790 /* Allow devices that do not support FileAttributeTagInfo. */
1791 switch (GetLastError()) {
1792 case ERROR_INVALID_PARAMETER:
1793 case ERROR_INVALID_FUNCTION:
1794 case ERROR_NOT_SUPPORTED:
1795 tagInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1796 tagInfo.ReparseTag = 0;
1797 break;
1798 default:
1799 retval = -1;
1800 goto cleanup;
1801 }
1802 } else if (tagInfo.FileAttributes &
1803 FILE_ATTRIBUTE_REPARSE_POINT) {
1804 if (IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1805 if (isUnhandledTag) {
1806 /* Traversing previously failed for either this link
1807 or its target. */
1808 SetLastError(ERROR_CANT_ACCESS_FILE);
1809 retval = -1;
1810 goto cleanup;
1811 }
1812 /* Traverse a non-link, but not if traversing already failed
1813 for an unhandled tag. */
1814 } else if (!isUnhandledTag) {
1815 CloseHandle(hFile);
1816 return win32_xstat_impl(path, result, TRUE);
1817 }
1818 }
1819 }
1820
1821 if (!GetFileInformationByHandle(hFile, &fileInfo)) {
1822 switch (GetLastError()) {
1823 case ERROR_INVALID_PARAMETER:
1824 case ERROR_INVALID_FUNCTION:
1825 case ERROR_NOT_SUPPORTED:
Steve Dower772ec0f2019-09-04 14:42:54 -07001826 /* Volumes and physical disks are block devices, e.g.
1827 \\.\C: and \\.\PhysicalDrive0. */
1828 memset(result, 0, sizeof(*result));
1829 result->st_mode = 0x6000; /* S_IFBLK */
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001830 goto cleanup;
1831 }
Steve Dower772ec0f2019-09-04 14:42:54 -07001832 retval = -1;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001833 goto cleanup;
1834 }
1835 }
1836
1837 _Py_attribute_data_to_stat(&fileInfo, tagInfo.ReparseTag, result);
1838
1839 if (!(fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
1840 /* Fix the file execute permissions. This hack sets S_IEXEC if
1841 the filename has an extension that is commonly used by files
1842 that CreateProcessW can execute. A real implementation calls
1843 GetSecurityInfo, OpenThreadToken/OpenProcessToken, and
1844 AccessCheck to check for generic read, write, and execute
1845 access. */
1846 const wchar_t *fileExtension = wcsrchr(path, '.');
1847 if (fileExtension) {
1848 if (_wcsicmp(fileExtension, L".exe") == 0 ||
1849 _wcsicmp(fileExtension, L".bat") == 0 ||
1850 _wcsicmp(fileExtension, L".cmd") == 0 ||
1851 _wcsicmp(fileExtension, L".com") == 0) {
1852 result->st_mode |= 0111;
1853 }
1854 }
1855 }
1856
1857cleanup:
1858 if (hFile != INVALID_HANDLE_VALUE) {
Steve Dower772ec0f2019-09-04 14:42:54 -07001859 /* Preserve last error if we are failing */
1860 error = retval ? GetLastError() : 0;
1861 if (!CloseHandle(hFile)) {
1862 retval = -1;
1863 } else if (retval) {
1864 /* Restore last error */
1865 SetLastError(error);
1866 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001867 }
1868
1869 return retval;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001870}
1871
1872static int
Steve Dowercc16be82016-09-08 10:35:16 -07001873win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001874{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001875 /* Protocol violation: we explicitly clear errno, instead of
1876 setting it to a POSIX error. Callers should use GetLastError. */
Brian Curtind25aef52011-06-13 15:16:04 -05001877 int code = win32_xstat_impl(path, result, traverse);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001878 errno = 0;
1879 return code;
1880}
Brian Curtind25aef52011-06-13 15:16:04 -05001881/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
Brian Curtind40e6f72010-07-08 21:39:08 +00001882
1883 In Posix, stat automatically traverses symlinks and returns the stat
1884 structure for the target. In Windows, the equivalent GetFileAttributes by
1885 default does not traverse symlinks and instead returns attributes for
1886 the symlink.
1887
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001888 Instead, we will open the file (which *does* traverse symlinks by default)
1889 and GetFileInformationByHandle(). */
Brian Curtind40e6f72010-07-08 21:39:08 +00001890
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001891static int
Steve Dowercc16be82016-09-08 10:35:16 -07001892win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
Martin v. Löwis14694662006-02-03 12:54:16 +00001893{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001894 return win32_xstat(path, result, FALSE);
Martin v. Löwis14694662006-02-03 12:54:16 +00001895}
1896
Victor Stinner8c62be82010-05-06 00:08:46 +00001897static int
Steve Dowercc16be82016-09-08 10:35:16 -07001898win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
Brian Curtind40e6f72010-07-08 21:39:08 +00001899{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001900 return win32_xstat(path, result, TRUE);
Brian Curtind40e6f72010-07-08 21:39:08 +00001901}
1902
Martin v. Löwis14694662006-02-03 12:54:16 +00001903#endif /* MS_WINDOWS */
1904
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001905PyDoc_STRVAR(stat_result__doc__,
Larry Hastings9cf065c2012-06-22 16:30:09 -07001906"stat_result: Result from stat, fstat, or lstat.\n\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001907This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001908 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001909or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1910\n\
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001911Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1912or st_flags, they are available as attributes only.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001913\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001914See os.stat for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001915
1916static PyStructSequence_Field stat_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001917 {"st_mode", "protection bits"},
1918 {"st_ino", "inode"},
1919 {"st_dev", "device"},
1920 {"st_nlink", "number of hard links"},
1921 {"st_uid", "user ID of owner"},
1922 {"st_gid", "group ID of owner"},
1923 {"st_size", "total size, in bytes"},
1924 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1925 {NULL, "integer time of last access"},
1926 {NULL, "integer time of last modification"},
1927 {NULL, "integer time of last change"},
1928 {"st_atime", "time of last access"},
1929 {"st_mtime", "time of last modification"},
1930 {"st_ctime", "time of last change"},
Larry Hastings6fe20b32012-04-19 15:07:49 -07001931 {"st_atime_ns", "time of last access in nanoseconds"},
1932 {"st_mtime_ns", "time of last modification in nanoseconds"},
1933 {"st_ctime_ns", "time of last change in nanoseconds"},
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001934#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00001935 {"st_blksize", "blocksize for filesystem I/O"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001936#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001937#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00001938 {"st_blocks", "number of blocks allocated"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001939#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001940#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00001941 {"st_rdev", "device type (if inode device)"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001942#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001943#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00001944 {"st_flags", "user defined flags for file"},
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001945#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001946#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00001947 {"st_gen", "generation number"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001948#endif
1949#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00001950 {"st_birthtime", "time of creation"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001951#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05001952#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1953 {"st_file_attributes", "Windows file attribute bits"},
1954#endif
jcea6c51d512018-01-28 14:00:08 +01001955#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1956 {"st_fstype", "Type of filesystem"},
1957#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001958#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
1959 {"st_reparse_tag", "Windows reparse tag"},
1960#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001961 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001962};
1963
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001964#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Larry Hastings6fe20b32012-04-19 15:07:49 -07001965#define ST_BLKSIZE_IDX 16
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001966#else
Larry Hastings6fe20b32012-04-19 15:07:49 -07001967#define ST_BLKSIZE_IDX 15
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001968#endif
1969
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001970#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001971#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
1972#else
1973#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
1974#endif
1975
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001976#ifdef HAVE_STRUCT_STAT_ST_RDEV
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001977#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
1978#else
1979#define ST_RDEV_IDX ST_BLOCKS_IDX
1980#endif
1981
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001982#ifdef HAVE_STRUCT_STAT_ST_FLAGS
1983#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
1984#else
1985#define ST_FLAGS_IDX ST_RDEV_IDX
1986#endif
1987
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001988#ifdef HAVE_STRUCT_STAT_ST_GEN
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001989#define ST_GEN_IDX (ST_FLAGS_IDX+1)
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001990#else
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001991#define ST_GEN_IDX ST_FLAGS_IDX
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001992#endif
1993
1994#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1995#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
1996#else
1997#define ST_BIRTHTIME_IDX ST_GEN_IDX
1998#endif
1999
Zachary Ware63f277b2014-06-19 09:46:37 -05002000#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2001#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_IDX+1)
2002#else
2003#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_IDX
2004#endif
2005
jcea6c51d512018-01-28 14:00:08 +01002006#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2007#define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
2008#else
2009#define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
2010#endif
2011
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002012#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2013#define ST_REPARSE_TAG_IDX (ST_FSTYPE_IDX+1)
2014#else
2015#define ST_REPARSE_TAG_IDX ST_FSTYPE_IDX
2016#endif
2017
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002018static PyStructSequence_Desc stat_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002019 "stat_result", /* name */
2020 stat_result__doc__, /* doc */
2021 stat_result_fields,
2022 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002023};
2024
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002025PyDoc_STRVAR(statvfs_result__doc__,
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002026"statvfs_result: Result from statvfs or fstatvfs.\n\n\
2027This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00002028 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
Guido van Rossuma4dc73e2001-10-18 20:53:15 +00002029or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002030\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002031See os.statvfs for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002032
2033static PyStructSequence_Field statvfs_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002034 {"f_bsize", },
2035 {"f_frsize", },
2036 {"f_blocks", },
2037 {"f_bfree", },
2038 {"f_bavail", },
2039 {"f_files", },
2040 {"f_ffree", },
2041 {"f_favail", },
2042 {"f_flag", },
2043 {"f_namemax",},
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +01002044 {"f_fsid", },
Victor Stinner8c62be82010-05-06 00:08:46 +00002045 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002046};
2047
2048static PyStructSequence_Desc statvfs_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002049 "statvfs_result", /* name */
2050 statvfs_result__doc__, /* doc */
2051 statvfs_result_fields,
2052 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002053};
2054
Ross Lagerwall7807c352011-03-17 20:20:30 +02002055#if defined(HAVE_WAITID) && !defined(__APPLE__)
2056PyDoc_STRVAR(waitid_result__doc__,
2057"waitid_result: Result from waitid.\n\n\
2058This object may be accessed either as a tuple of\n\
2059 (si_pid, si_uid, si_signo, si_status, si_code),\n\
2060or via the attributes si_pid, si_uid, and so on.\n\
2061\n\
2062See os.waitid for more information.");
2063
2064static PyStructSequence_Field waitid_result_fields[] = {
2065 {"si_pid", },
2066 {"si_uid", },
2067 {"si_signo", },
2068 {"si_status", },
2069 {"si_code", },
2070 {0}
2071};
2072
2073static PyStructSequence_Desc waitid_result_desc = {
2074 "waitid_result", /* name */
2075 waitid_result__doc__, /* doc */
2076 waitid_result_fields,
2077 5
2078};
Benjamin Petersonbad9c2f2011-08-02 18:42:14 -05002079#endif
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002080static newfunc structseq_new;
2081
2082static PyObject *
2083statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2084{
Victor Stinner8c62be82010-05-06 00:08:46 +00002085 PyStructSequence *result;
2086 int i;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002087
Victor Stinner8c62be82010-05-06 00:08:46 +00002088 result = (PyStructSequence*)structseq_new(type, args, kwds);
2089 if (!result)
2090 return NULL;
2091 /* If we have been initialized from a tuple,
2092 st_?time might be set to None. Initialize it
2093 from the int slots. */
2094 for (i = 7; i <= 9; i++) {
2095 if (result->ob_item[i+3] == Py_None) {
2096 Py_DECREF(Py_None);
2097 Py_INCREF(result->ob_item[i]);
2098 result->ob_item[i+3] = result->ob_item[i];
2099 }
2100 }
2101 return (PyObject*)result;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002102}
2103
Eddie Elizondob3966632019-11-05 07:16:14 -08002104static int
2105_posix_clear(PyObject *module)
2106{
2107 Py_CLEAR(_posixstate(module)->billion);
2108 Py_CLEAR(_posixstate(module)->posix_putenv_garbage);
2109 Py_CLEAR(_posixstate(module)->DirEntryType);
2110 Py_CLEAR(_posixstate(module)->ScandirIteratorType);
2111#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
2112 Py_CLEAR(_posixstate(module)->SchedParamType);
2113#endif
2114 Py_CLEAR(_posixstate(module)->StatResultType);
2115 Py_CLEAR(_posixstate(module)->StatVFSResultType);
2116 Py_CLEAR(_posixstate(module)->TerminalSizeType);
2117 Py_CLEAR(_posixstate(module)->TimesResultType);
2118 Py_CLEAR(_posixstate(module)->UnameResultType);
2119#if defined(HAVE_WAITID) && !defined(__APPLE__)
2120 Py_CLEAR(_posixstate(module)->WaitidResultType);
2121#endif
2122#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
2123 Py_CLEAR(_posixstate(module)->struct_rusage);
2124#endif
2125 Py_CLEAR(_posixstate(module)->st_mode);
2126 return 0;
2127}
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002128
Eddie Elizondob3966632019-11-05 07:16:14 -08002129static int
2130_posix_traverse(PyObject *module, visitproc visit, void *arg)
2131{
2132 Py_VISIT(_posixstate(module)->billion);
2133 Py_VISIT(_posixstate(module)->posix_putenv_garbage);
2134 Py_VISIT(_posixstate(module)->DirEntryType);
2135 Py_VISIT(_posixstate(module)->ScandirIteratorType);
2136#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
2137 Py_VISIT(_posixstate(module)->SchedParamType);
2138#endif
2139 Py_VISIT(_posixstate(module)->StatResultType);
2140 Py_VISIT(_posixstate(module)->StatVFSResultType);
2141 Py_VISIT(_posixstate(module)->TerminalSizeType);
2142 Py_VISIT(_posixstate(module)->TimesResultType);
2143 Py_VISIT(_posixstate(module)->UnameResultType);
2144#if defined(HAVE_WAITID) && !defined(__APPLE__)
2145 Py_VISIT(_posixstate(module)->WaitidResultType);
2146#endif
2147#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
2148 Py_VISIT(_posixstate(module)->struct_rusage);
2149#endif
2150 Py_VISIT(_posixstate(module)->st_mode);
2151 return 0;
2152}
2153
2154static void
2155_posix_free(void *module)
2156{
2157 _posix_clear((PyObject *)module);
2158}
Larry Hastings6fe20b32012-04-19 15:07:49 -07002159
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002160static void
Victor Stinner4195b5c2012-02-08 23:03:19 +01002161fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002162{
Larry Hastings6fe20b32012-04-19 15:07:49 -07002163 PyObject *s = _PyLong_FromTime_t(sec);
2164 PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
2165 PyObject *s_in_ns = NULL;
2166 PyObject *ns_total = NULL;
2167 PyObject *float_s = NULL;
2168
2169 if (!(s && ns_fractional))
2170 goto exit;
2171
Eddie Elizondob3966632019-11-05 07:16:14 -08002172 s_in_ns = PyNumber_Multiply(s, _posixstate_global->billion);
Larry Hastings6fe20b32012-04-19 15:07:49 -07002173 if (!s_in_ns)
2174 goto exit;
2175
2176 ns_total = PyNumber_Add(s_in_ns, ns_fractional);
2177 if (!ns_total)
2178 goto exit;
2179
Victor Stinner01b5aab2017-10-24 02:02:00 -07002180 float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
2181 if (!float_s) {
2182 goto exit;
Larry Hastings6fe20b32012-04-19 15:07:49 -07002183 }
2184
2185 PyStructSequence_SET_ITEM(v, index, s);
2186 PyStructSequence_SET_ITEM(v, index+3, float_s);
2187 PyStructSequence_SET_ITEM(v, index+6, ns_total);
2188 s = NULL;
2189 float_s = NULL;
2190 ns_total = NULL;
2191exit:
2192 Py_XDECREF(s);
2193 Py_XDECREF(ns_fractional);
2194 Py_XDECREF(s_in_ns);
2195 Py_XDECREF(ns_total);
2196 Py_XDECREF(float_s);
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002197}
2198
Tim Peters5aa91602002-01-30 05:46:57 +00002199/* pack a system stat C structure into the Python stat tuple
Fred Drake699f3522000-06-29 21:12:41 +00002200 (used by posix_stat() and posix_fstat()) */
2201static PyObject*
Victor Stinner4195b5c2012-02-08 23:03:19 +01002202_pystat_fromstructstat(STRUCT_STAT *st)
Fred Drake699f3522000-06-29 21:12:41 +00002203{
Victor Stinner8c62be82010-05-06 00:08:46 +00002204 unsigned long ansec, mnsec, cnsec;
Eddie Elizondob3966632019-11-05 07:16:14 -08002205 PyObject *StatResultType = _posixstate_global->StatResultType;
2206 PyObject *v = PyStructSequence_New((PyTypeObject *)StatResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +00002207 if (v == NULL)
2208 return NULL;
Fred Drake699f3522000-06-29 21:12:41 +00002209
Victor Stinner8c62be82010-05-06 00:08:46 +00002210 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode));
Victor Stinner0f6d7332017-03-09 17:34:28 +01002211 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(st->st_ino));
xdegaye50e86032017-05-22 11:15:08 +02002212 PyStructSequence_SET_ITEM(v, 1, PyLong_FromUnsignedLongLong(st->st_ino));
Serhiy Storchaka404fa922013-01-02 18:22:23 +02002213#ifdef MS_WINDOWS
2214 PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002215#else
Serhiy Storchakab2653b32015-01-18 11:12:11 +02002216 PyStructSequence_SET_ITEM(v, 2, _PyLong_FromDev(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002217#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002218 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02002219#if defined(MS_WINDOWS)
2220 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong(0));
2221 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong(0));
2222#else
2223 PyStructSequence_SET_ITEM(v, 4, _PyLong_FromUid(st->st_uid));
2224 PyStructSequence_SET_ITEM(v, 5, _PyLong_FromGid(st->st_gid));
2225#endif
xdegaye50e86032017-05-22 11:15:08 +02002226 Py_BUILD_ASSERT(sizeof(long long) >= sizeof(st->st_size));
2227 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLongLong(st->st_size));
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002228
Martin v. Löwis14694662006-02-03 12:54:16 +00002229#if defined(HAVE_STAT_TV_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002230 ansec = st->st_atim.tv_nsec;
2231 mnsec = st->st_mtim.tv_nsec;
2232 cnsec = st->st_ctim.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002233#elif defined(HAVE_STAT_TV_NSEC2)
Victor Stinner8c62be82010-05-06 00:08:46 +00002234 ansec = st->st_atimespec.tv_nsec;
2235 mnsec = st->st_mtimespec.tv_nsec;
2236 cnsec = st->st_ctimespec.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002237#elif defined(HAVE_STAT_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002238 ansec = st->st_atime_nsec;
2239 mnsec = st->st_mtime_nsec;
2240 cnsec = st->st_ctime_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002241#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002242 ansec = mnsec = cnsec = 0;
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002243#endif
Victor Stinner4195b5c2012-02-08 23:03:19 +01002244 fill_time(v, 7, st->st_atime, ansec);
2245 fill_time(v, 8, st->st_mtime, mnsec);
2246 fill_time(v, 9, st->st_ctime, cnsec);
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002247
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002248#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00002249 PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
2250 PyLong_FromLong((long)st->st_blksize));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002251#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002252#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00002253 PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
2254 PyLong_FromLong((long)st->st_blocks));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002255#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002256#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00002257 PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
2258 PyLong_FromLong((long)st->st_rdev));
Fred Drake699f3522000-06-29 21:12:41 +00002259#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002260#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00002261 PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
2262 PyLong_FromLong((long)st->st_gen));
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002263#endif
2264#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00002265 {
Victor Stinner4195b5c2012-02-08 23:03:19 +01002266 PyObject *val;
2267 unsigned long bsec,bnsec;
2268 bsec = (long)st->st_birthtime;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002269#ifdef HAVE_STAT_TV_NSEC2
Victor Stinner4195b5c2012-02-08 23:03:19 +01002270 bnsec = st->st_birthtimespec.tv_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002271#else
Victor Stinner4195b5c2012-02-08 23:03:19 +01002272 bnsec = 0;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002273#endif
Victor Stinner01b5aab2017-10-24 02:02:00 -07002274 val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
Victor Stinner4195b5c2012-02-08 23:03:19 +01002275 PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
2276 val);
Victor Stinner8c62be82010-05-06 00:08:46 +00002277 }
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002278#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002279#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00002280 PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
2281 PyLong_FromLong((long)st->st_flags));
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002282#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05002283#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2284 PyStructSequence_SET_ITEM(v, ST_FILE_ATTRIBUTES_IDX,
2285 PyLong_FromUnsignedLong(st->st_file_attributes));
2286#endif
jcea6c51d512018-01-28 14:00:08 +01002287#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2288 PyStructSequence_SET_ITEM(v, ST_FSTYPE_IDX,
2289 PyUnicode_FromString(st->st_fstype));
2290#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002291#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2292 PyStructSequence_SET_ITEM(v, ST_REPARSE_TAG_IDX,
2293 PyLong_FromUnsignedLong(st->st_reparse_tag));
2294#endif
Fred Drake699f3522000-06-29 21:12:41 +00002295
Victor Stinner8c62be82010-05-06 00:08:46 +00002296 if (PyErr_Occurred()) {
2297 Py_DECREF(v);
2298 return NULL;
2299 }
Fred Drake699f3522000-06-29 21:12:41 +00002300
Victor Stinner8c62be82010-05-06 00:08:46 +00002301 return v;
Fred Drake699f3522000-06-29 21:12:41 +00002302}
2303
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002304/* POSIX methods */
2305
Guido van Rossum94f6f721999-01-06 18:42:14 +00002306
2307static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002308posix_do_stat(const char *function_name, path_t *path,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002309 int dir_fd, int follow_symlinks)
Guido van Rossum94f6f721999-01-06 18:42:14 +00002310{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002311 STRUCT_STAT st;
2312 int result;
2313
2314#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
2315 if (follow_symlinks_specified(function_name, follow_symlinks))
2316 return NULL;
2317#endif
2318
2319 if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
2320 dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
2321 fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
2322 return NULL;
2323
2324 Py_BEGIN_ALLOW_THREADS
2325 if (path->fd != -1)
2326 result = FSTAT(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002327#ifdef MS_WINDOWS
Steve Dower513d7472016-09-08 10:41:50 -07002328 else if (follow_symlinks)
Steve Dowercc16be82016-09-08 10:35:16 -07002329 result = win32_stat(path->wide, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002330 else
Steve Dowercc16be82016-09-08 10:35:16 -07002331 result = win32_lstat(path->wide, &st);
2332#else
2333 else
2334#if defined(HAVE_LSTAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002335 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
2336 result = LSTAT(path->narrow, &st);
2337 else
Steve Dowercc16be82016-09-08 10:35:16 -07002338#endif /* HAVE_LSTAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002339#ifdef HAVE_FSTATAT
2340 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks)
2341 result = fstatat(dir_fd, path->narrow, &st,
2342 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2343 else
Steve Dowercc16be82016-09-08 10:35:16 -07002344#endif /* HAVE_FSTATAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002345 result = STAT(path->narrow, &st);
Steve Dowercc16be82016-09-08 10:35:16 -07002346#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002347 Py_END_ALLOW_THREADS
2348
Victor Stinner292c8352012-10-30 02:17:38 +01002349 if (result != 0) {
2350 return path_error(path);
2351 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07002352
2353 return _pystat_fromstructstat(&st);
2354}
2355
Larry Hastings2f936352014-08-05 14:04:04 +10002356/*[python input]
2357
2358for s in """
2359
2360FACCESSAT
2361FCHMODAT
2362FCHOWNAT
2363FSTATAT
2364LINKAT
2365MKDIRAT
2366MKFIFOAT
2367MKNODAT
2368OPENAT
2369READLINKAT
2370SYMLINKAT
2371UNLINKAT
2372
2373""".strip().split():
2374 s = s.strip()
2375 print("""
2376#ifdef HAVE_{s}
2377 #define {s}_DIR_FD_CONVERTER dir_fd_converter
Larry Hastings31826802013-10-19 00:09:25 -07002378#else
Larry Hastings2f936352014-08-05 14:04:04 +10002379 #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings31826802013-10-19 00:09:25 -07002380#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002381""".rstrip().format(s=s))
2382
2383for s in """
2384
2385FCHDIR
2386FCHMOD
2387FCHOWN
2388FDOPENDIR
2389FEXECVE
2390FPATHCONF
2391FSTATVFS
2392FTRUNCATE
2393
2394""".strip().split():
2395 s = s.strip()
2396 print("""
2397#ifdef HAVE_{s}
2398 #define PATH_HAVE_{s} 1
2399#else
2400 #define PATH_HAVE_{s} 0
2401#endif
2402
2403""".rstrip().format(s=s))
2404[python start generated code]*/
2405
2406#ifdef HAVE_FACCESSAT
2407 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
2408#else
2409 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
2410#endif
2411
2412#ifdef HAVE_FCHMODAT
2413 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
2414#else
2415 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
2416#endif
2417
2418#ifdef HAVE_FCHOWNAT
2419 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
2420#else
2421 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
2422#endif
2423
2424#ifdef HAVE_FSTATAT
2425 #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
2426#else
2427 #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
2428#endif
2429
2430#ifdef HAVE_LINKAT
2431 #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
2432#else
2433 #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2434#endif
2435
2436#ifdef HAVE_MKDIRAT
2437 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
2438#else
2439 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
2440#endif
2441
2442#ifdef HAVE_MKFIFOAT
2443 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
2444#else
2445 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
2446#endif
2447
2448#ifdef HAVE_MKNODAT
2449 #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
2450#else
2451 #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
2452#endif
2453
2454#ifdef HAVE_OPENAT
2455 #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
2456#else
2457 #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
2458#endif
2459
2460#ifdef HAVE_READLINKAT
2461 #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
2462#else
2463 #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2464#endif
2465
2466#ifdef HAVE_SYMLINKAT
2467 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
2468#else
2469 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2470#endif
2471
2472#ifdef HAVE_UNLINKAT
2473 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
2474#else
2475 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2476#endif
2477
2478#ifdef HAVE_FCHDIR
2479 #define PATH_HAVE_FCHDIR 1
2480#else
2481 #define PATH_HAVE_FCHDIR 0
2482#endif
2483
2484#ifdef HAVE_FCHMOD
2485 #define PATH_HAVE_FCHMOD 1
2486#else
2487 #define PATH_HAVE_FCHMOD 0
2488#endif
2489
2490#ifdef HAVE_FCHOWN
2491 #define PATH_HAVE_FCHOWN 1
2492#else
2493 #define PATH_HAVE_FCHOWN 0
2494#endif
2495
2496#ifdef HAVE_FDOPENDIR
2497 #define PATH_HAVE_FDOPENDIR 1
2498#else
2499 #define PATH_HAVE_FDOPENDIR 0
2500#endif
2501
2502#ifdef HAVE_FEXECVE
2503 #define PATH_HAVE_FEXECVE 1
2504#else
2505 #define PATH_HAVE_FEXECVE 0
2506#endif
2507
2508#ifdef HAVE_FPATHCONF
2509 #define PATH_HAVE_FPATHCONF 1
2510#else
2511 #define PATH_HAVE_FPATHCONF 0
2512#endif
2513
2514#ifdef HAVE_FSTATVFS
2515 #define PATH_HAVE_FSTATVFS 1
2516#else
2517 #define PATH_HAVE_FSTATVFS 0
2518#endif
2519
2520#ifdef HAVE_FTRUNCATE
2521 #define PATH_HAVE_FTRUNCATE 1
2522#else
2523 #define PATH_HAVE_FTRUNCATE 0
2524#endif
2525/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
Larry Hastings31826802013-10-19 00:09:25 -07002526
Steve Dowerfe0a41a2015-03-20 19:50:46 -07002527#ifdef MS_WINDOWS
2528 #undef PATH_HAVE_FTRUNCATE
2529 #define PATH_HAVE_FTRUNCATE 1
2530#endif
Larry Hastings31826802013-10-19 00:09:25 -07002531
Larry Hastings61272b72014-01-07 12:41:53 -08002532/*[python input]
Larry Hastings31826802013-10-19 00:09:25 -07002533
2534class path_t_converter(CConverter):
2535
2536 type = "path_t"
2537 impl_by_reference = True
2538 parse_by_reference = True
2539
2540 converter = 'path_converter'
2541
2542 def converter_init(self, *, allow_fd=False, nullable=False):
Larry Hastings31826802013-10-19 00:09:25 -07002543 # right now path_t doesn't support default values.
2544 # to support a default value, you'll need to override initialize().
Larry Hastings2f936352014-08-05 14:04:04 +10002545 if self.default not in (unspecified, None):
Larry Hastings7726ac92014-01-31 22:03:12 -08002546 fail("Can't specify a default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002547
Larry Hastings2f936352014-08-05 14:04:04 +10002548 if self.c_default not in (None, 'Py_None'):
2549 raise RuntimeError("Can't specify a c_default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002550
2551 self.nullable = nullable
2552 self.allow_fd = allow_fd
2553
Larry Hastings7726ac92014-01-31 22:03:12 -08002554 def pre_render(self):
2555 def strify(value):
Larry Hastings2f936352014-08-05 14:04:04 +10002556 if isinstance(value, str):
2557 return value
Larry Hastings7726ac92014-01-31 22:03:12 -08002558 return str(int(bool(value)))
2559
2560 # add self.py_name here when merging with posixmodule conversion
Larry Hastings2f936352014-08-05 14:04:04 +10002561 self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
Larry Hastings31826802013-10-19 00:09:25 -07002562 self.function.name,
Larry Hastings2f936352014-08-05 14:04:04 +10002563 self.name,
Larry Hastings7726ac92014-01-31 22:03:12 -08002564 strify(self.nullable),
2565 strify(self.allow_fd),
Larry Hastings31826802013-10-19 00:09:25 -07002566 )
2567
2568 def cleanup(self):
2569 return "path_cleanup(&" + self.name + ");\n"
2570
2571
2572class dir_fd_converter(CConverter):
2573 type = 'int'
Larry Hastings31826802013-10-19 00:09:25 -07002574
Larry Hastings2f936352014-08-05 14:04:04 +10002575 def converter_init(self, requires=None):
Larry Hastings31826802013-10-19 00:09:25 -07002576 if self.default in (unspecified, None):
2577 self.c_default = 'DEFAULT_DIR_FD'
Larry Hastings2f936352014-08-05 14:04:04 +10002578 if isinstance(requires, str):
2579 self.converter = requires.upper() + '_DIR_FD_CONVERTER'
2580 else:
2581 self.converter = 'dir_fd_converter'
Larry Hastings31826802013-10-19 00:09:25 -07002582
Larry Hastings2f936352014-08-05 14:04:04 +10002583class fildes_converter(CConverter):
2584 type = 'int'
2585 converter = 'fildes_converter'
2586
2587class uid_t_converter(CConverter):
2588 type = "uid_t"
2589 converter = '_Py_Uid_Converter'
2590
2591class gid_t_converter(CConverter):
2592 type = "gid_t"
2593 converter = '_Py_Gid_Converter'
2594
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02002595class dev_t_converter(CConverter):
2596 type = 'dev_t'
2597 converter = '_Py_Dev_Converter'
2598
2599class dev_t_return_converter(unsigned_long_return_converter):
2600 type = 'dev_t'
2601 conversion_fn = '_PyLong_FromDev'
2602 unsigned_cast = '(dev_t)'
2603
Larry Hastings2f936352014-08-05 14:04:04 +10002604class FSConverter_converter(CConverter):
2605 type = 'PyObject *'
2606 converter = 'PyUnicode_FSConverter'
2607 def converter_init(self):
2608 if self.default is not unspecified:
2609 fail("FSConverter_converter does not support default values")
2610 self.c_default = 'NULL'
2611
2612 def cleanup(self):
2613 return "Py_XDECREF(" + self.name + ");\n"
2614
2615class pid_t_converter(CConverter):
2616 type = 'pid_t'
2617 format_unit = '" _Py_PARSE_PID "'
2618
2619class idtype_t_converter(int_converter):
2620 type = 'idtype_t'
2621
2622class id_t_converter(CConverter):
2623 type = 'id_t'
2624 format_unit = '" _Py_PARSE_PID "'
2625
Benjamin Petersonca470632016-09-06 13:47:26 -07002626class intptr_t_converter(CConverter):
2627 type = 'intptr_t'
Larry Hastings2f936352014-08-05 14:04:04 +10002628 format_unit = '" _Py_PARSE_INTPTR "'
2629
2630class Py_off_t_converter(CConverter):
2631 type = 'Py_off_t'
2632 converter = 'Py_off_t_converter'
2633
2634class Py_off_t_return_converter(long_return_converter):
2635 type = 'Py_off_t'
2636 conversion_fn = 'PyLong_FromPy_off_t'
2637
2638class path_confname_converter(CConverter):
2639 type="int"
2640 converter="conv_path_confname"
2641
2642class confstr_confname_converter(path_confname_converter):
2643 converter='conv_confstr_confname'
2644
2645class sysconf_confname_converter(path_confname_converter):
2646 converter="conv_sysconf_confname"
2647
2648class sched_param_converter(CConverter):
2649 type = 'struct sched_param'
2650 converter = 'convert_sched_param'
2651 impl_by_reference = True;
Larry Hastings31826802013-10-19 00:09:25 -07002652
Larry Hastings61272b72014-01-07 12:41:53 -08002653[python start generated code]*/
Victor Stinner581139c2016-09-06 15:54:20 -07002654/*[python end generated code: output=da39a3ee5e6b4b0d input=418fce0e01144461]*/
Larry Hastings31826802013-10-19 00:09:25 -07002655
Larry Hastings61272b72014-01-07 12:41:53 -08002656/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002657
Larry Hastings2a727912014-01-16 11:32:01 -08002658os.stat
Larry Hastings31826802013-10-19 00:09:25 -07002659
2660 path : path_t(allow_fd=True)
BNMetricsb9427072018-11-02 15:20:19 +00002661 Path to be examined; can be string, bytes, a path-like object or
Xiang Zhang4459e002017-01-22 13:04:17 +08002662 open-file-descriptor int.
Larry Hastings31826802013-10-19 00:09:25 -07002663
2664 *
2665
Larry Hastings2f936352014-08-05 14:04:04 +10002666 dir_fd : dir_fd(requires='fstatat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002667 If not None, it should be a file descriptor open to a directory,
2668 and path should be a relative string; path will then be relative to
2669 that directory.
2670
2671 follow_symlinks: bool = True
2672 If False, and the last element of the path is a symbolic link,
2673 stat will examine the symbolic link itself instead of the file
2674 the link points to.
2675
2676Perform a stat system call on the given path.
2677
2678dir_fd and follow_symlinks may not be implemented
2679 on your platform. If they are unavailable, using them will raise a
2680 NotImplementedError.
2681
2682It's an error to use dir_fd or follow_symlinks when specifying path as
2683 an open file descriptor.
2684
Larry Hastings61272b72014-01-07 12:41:53 -08002685[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002686
Larry Hastings31826802013-10-19 00:09:25 -07002687static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002688os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002689/*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
Larry Hastings31826802013-10-19 00:09:25 -07002690{
2691 return posix_do_stat("stat", path, dir_fd, follow_symlinks);
2692}
2693
Larry Hastings2f936352014-08-05 14:04:04 +10002694
2695/*[clinic input]
2696os.lstat
2697
2698 path : path_t
2699
2700 *
2701
2702 dir_fd : dir_fd(requires='fstatat') = None
2703
2704Perform a stat system call on the given path, without following symbolic links.
2705
2706Like stat(), but do not follow symbolic links.
2707Equivalent to stat(path, follow_symlinks=False).
2708[clinic start generated code]*/
2709
Larry Hastings2f936352014-08-05 14:04:04 +10002710static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002711os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
2712/*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002713{
2714 int follow_symlinks = 0;
2715 return posix_do_stat("lstat", path, dir_fd, follow_symlinks);
2716}
Larry Hastings31826802013-10-19 00:09:25 -07002717
Larry Hastings2f936352014-08-05 14:04:04 +10002718
Larry Hastings61272b72014-01-07 12:41:53 -08002719/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10002720os.access -> bool
Larry Hastings31826802013-10-19 00:09:25 -07002721
Benjamin Peterson768f3b42016-09-05 15:29:33 -07002722 path: path_t
BNMetricsb9427072018-11-02 15:20:19 +00002723 Path to be tested; can be string, bytes, or a path-like object.
Larry Hastings31826802013-10-19 00:09:25 -07002724
2725 mode: int
2726 Operating-system mode bitfield. Can be F_OK to test existence,
2727 or the inclusive-OR of R_OK, W_OK, and X_OK.
2728
2729 *
2730
Larry Hastings2f936352014-08-05 14:04:04 +10002731 dir_fd : dir_fd(requires='faccessat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002732 If not None, it should be a file descriptor open to a directory,
2733 and path should be relative; path will then be relative to that
2734 directory.
2735
2736 effective_ids: bool = False
2737 If True, access will use the effective uid/gid instead of
2738 the real uid/gid.
2739
2740 follow_symlinks: bool = True
2741 If False, and the last element of the path is a symbolic link,
2742 access will examine the symbolic link itself instead of the file
2743 the link points to.
2744
2745Use the real uid/gid to test for access to a path.
2746
2747{parameters}
2748dir_fd, effective_ids, and follow_symlinks may not be implemented
2749 on your platform. If they are unavailable, using them will raise a
2750 NotImplementedError.
2751
2752Note that most operations will use the effective uid/gid, therefore this
2753 routine can be used in a suid/sgid environment to test if the invoking user
2754 has the specified access to the path.
2755
Larry Hastings61272b72014-01-07 12:41:53 -08002756[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002757
Larry Hastings2f936352014-08-05 14:04:04 +10002758static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002759os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002760 int effective_ids, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002761/*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
Larry Hastings31826802013-10-19 00:09:25 -07002762{
Larry Hastings2f936352014-08-05 14:04:04 +10002763 int return_value;
Victor Stinner8c62be82010-05-06 00:08:46 +00002764
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002765#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002766 DWORD attr;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002767#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07002768 int result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002769#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07002770
Larry Hastings9cf065c2012-06-22 16:30:09 -07002771#ifndef HAVE_FACCESSAT
2772 if (follow_symlinks_specified("access", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002773 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002774
2775 if (effective_ids) {
2776 argument_unavailable_error("access", "effective_ids");
Larry Hastings2f936352014-08-05 14:04:04 +10002777 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002778 }
2779#endif
2780
2781#ifdef MS_WINDOWS
2782 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002783 attr = GetFileAttributesW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002784 Py_END_ALLOW_THREADS
2785
2786 /*
Georg Brandlf7875592012-06-24 13:58:31 +02002787 * Access is possible if
Larry Hastings9cf065c2012-06-22 16:30:09 -07002788 * * we didn't get a -1, and
2789 * * write access wasn't requested,
2790 * * or the file isn't read-only,
2791 * * or it's a directory.
2792 * (Directories cannot be read-only on Windows.)
2793 */
Larry Hastings2f936352014-08-05 14:04:04 +10002794 return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
Georg Brandl5bb7aa92012-06-23 12:48:40 +02002795 (!(mode & 2) ||
Larry Hastings9cf065c2012-06-22 16:30:09 -07002796 !(attr & FILE_ATTRIBUTE_READONLY) ||
Larry Hastings2f936352014-08-05 14:04:04 +10002797 (attr & FILE_ATTRIBUTE_DIRECTORY));
Larry Hastings9cf065c2012-06-22 16:30:09 -07002798#else
2799
2800 Py_BEGIN_ALLOW_THREADS
2801#ifdef HAVE_FACCESSAT
2802 if ((dir_fd != DEFAULT_DIR_FD) ||
2803 effective_ids ||
2804 !follow_symlinks) {
2805 int flags = 0;
2806 if (!follow_symlinks)
2807 flags |= AT_SYMLINK_NOFOLLOW;
2808 if (effective_ids)
2809 flags |= AT_EACCESS;
Larry Hastings31826802013-10-19 00:09:25 -07002810 result = faccessat(dir_fd, path->narrow, mode, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002811 }
2812 else
2813#endif
Larry Hastings31826802013-10-19 00:09:25 -07002814 result = access(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002815 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10002816 return_value = !result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002817#endif
2818
Larry Hastings9cf065c2012-06-22 16:30:09 -07002819 return return_value;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002820}
2821
Guido van Rossumd371ff11999-01-25 16:12:23 +00002822#ifndef F_OK
2823#define F_OK 0
2824#endif
2825#ifndef R_OK
2826#define R_OK 4
2827#endif
2828#ifndef W_OK
2829#define W_OK 2
2830#endif
2831#ifndef X_OK
2832#define X_OK 1
2833#endif
2834
Larry Hastings31826802013-10-19 00:09:25 -07002835
Guido van Rossumd371ff11999-01-25 16:12:23 +00002836#ifdef HAVE_TTYNAME
Larry Hastings61272b72014-01-07 12:41:53 -08002837/*[clinic input]
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002838os.ttyname
Larry Hastings31826802013-10-19 00:09:25 -07002839
2840 fd: int
2841 Integer file descriptor handle.
2842
2843 /
2844
2845Return the name of the terminal device connected to 'fd'.
Larry Hastings61272b72014-01-07 12:41:53 -08002846[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002847
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002848static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002849os_ttyname_impl(PyObject *module, int fd)
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002850/*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
Larry Hastings31826802013-10-19 00:09:25 -07002851{
Guido van Rossum94f6f721999-01-06 18:42:14 +00002852
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002853 long size = sysconf(_SC_TTY_NAME_MAX);
2854 if (size == -1) {
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002855 return posix_error();
2856 }
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002857 char *buffer = (char *)PyMem_RawMalloc(size);
2858 if (buffer == NULL) {
2859 return PyErr_NoMemory();
2860 }
2861 int ret = ttyname_r(fd, buffer, size);
2862 if (ret != 0) {
2863 PyMem_RawFree(buffer);
2864 errno = ret;
2865 return posix_error();
2866 }
2867 PyObject *res = PyUnicode_DecodeFSDefault(buffer);
2868 PyMem_RawFree(buffer);
2869 return res;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002870}
Guido van Rossumd371ff11999-01-25 16:12:23 +00002871#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +00002872
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002873#ifdef HAVE_CTERMID
Larry Hastings2f936352014-08-05 14:04:04 +10002874/*[clinic input]
2875os.ctermid
2876
2877Return the name of the controlling terminal for this process.
2878[clinic start generated code]*/
2879
Larry Hastings2f936352014-08-05 14:04:04 +10002880static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002881os_ctermid_impl(PyObject *module)
2882/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002883{
Victor Stinner8c62be82010-05-06 00:08:46 +00002884 char *ret;
2885 char buffer[L_ctermid];
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002886
Greg Wardb48bc172000-03-01 21:51:56 +00002887#ifdef USE_CTERMID_R
Victor Stinner8c62be82010-05-06 00:08:46 +00002888 ret = ctermid_r(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002889#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002890 ret = ctermid(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002891#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002892 if (ret == NULL)
2893 return posix_error();
Victor Stinner5fe6de82010-08-15 09:12:51 +00002894 return PyUnicode_DecodeFSDefault(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002895}
Larry Hastings2f936352014-08-05 14:04:04 +10002896#endif /* HAVE_CTERMID */
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002897
Larry Hastings2f936352014-08-05 14:04:04 +10002898
2899/*[clinic input]
2900os.chdir
2901
2902 path: path_t(allow_fd='PATH_HAVE_FCHDIR')
2903
2904Change the current working directory to the specified path.
2905
2906path may always be specified as a string.
2907On some platforms, path may also be specified as an open file descriptor.
2908 If this functionality is unavailable, using it raises an exception.
2909[clinic start generated code]*/
2910
Larry Hastings2f936352014-08-05 14:04:04 +10002911static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002912os_chdir_impl(PyObject *module, path_t *path)
2913/*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002914{
2915 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002916
2917 Py_BEGIN_ALLOW_THREADS
2918#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07002919 /* on unix, success = 0, on windows, success = !0 */
2920 result = !win32_wchdir(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002921#else
2922#ifdef HAVE_FCHDIR
Larry Hastings2f936352014-08-05 14:04:04 +10002923 if (path->fd != -1)
2924 result = fchdir(path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002925 else
2926#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002927 result = chdir(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002928#endif
2929 Py_END_ALLOW_THREADS
2930
2931 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002932 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002933 }
2934
Larry Hastings2f936352014-08-05 14:04:04 +10002935 Py_RETURN_NONE;
2936}
2937
2938
2939#ifdef HAVE_FCHDIR
2940/*[clinic input]
2941os.fchdir
2942
2943 fd: fildes
2944
2945Change to the directory of the given file descriptor.
2946
2947fd must be opened on a directory, not a file.
2948Equivalent to os.chdir(fd).
2949
2950[clinic start generated code]*/
2951
Fred Drake4d1e64b2002-04-15 19:40:07 +00002952static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002953os_fchdir_impl(PyObject *module, int fd)
2954/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
Fred Drake4d1e64b2002-04-15 19:40:07 +00002955{
Larry Hastings2f936352014-08-05 14:04:04 +10002956 return posix_fildes_fd(fd, fchdir);
Fred Drake4d1e64b2002-04-15 19:40:07 +00002957}
2958#endif /* HAVE_FCHDIR */
2959
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00002960
Larry Hastings2f936352014-08-05 14:04:04 +10002961/*[clinic input]
2962os.chmod
2963
2964 path: path_t(allow_fd='PATH_HAVE_FCHMOD')
BNMetricsb9427072018-11-02 15:20:19 +00002965 Path to be modified. May always be specified as a str, bytes, or a path-like object.
Larry Hastings2f936352014-08-05 14:04:04 +10002966 On some platforms, path may also be specified as an open file descriptor.
2967 If this functionality is unavailable, using it raises an exception.
2968
2969 mode: int
2970 Operating-system mode bitfield.
2971
2972 *
2973
2974 dir_fd : dir_fd(requires='fchmodat') = None
2975 If not None, it should be a file descriptor open to a directory,
2976 and path should be relative; path will then be relative to that
2977 directory.
2978
2979 follow_symlinks: bool = True
2980 If False, and the last element of the path is a symbolic link,
2981 chmod will modify the symbolic link itself instead of the file
2982 the link points to.
2983
2984Change the access permissions of a file.
2985
2986It is an error to use dir_fd or follow_symlinks when specifying path as
2987 an open file descriptor.
2988dir_fd and follow_symlinks may not be implemented on your platform.
2989 If they are unavailable, using them will raise a NotImplementedError.
2990
2991[clinic start generated code]*/
2992
Larry Hastings2f936352014-08-05 14:04:04 +10002993static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002994os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002995 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002996/*[clinic end generated code: output=5cf6a94915cc7bff input=989081551c00293b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002997{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002998 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002999
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003000#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003001 DWORD attr;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003002#endif
Hirokazu Yamamoto892a37a2009-06-28 11:07:03 +00003003
Larry Hastings9cf065c2012-06-22 16:30:09 -07003004#ifdef HAVE_FCHMODAT
3005 int fchmodat_nofollow_unsupported = 0;
3006#endif
3007
Larry Hastings9cf065c2012-06-22 16:30:09 -07003008#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
3009 if (follow_symlinks_specified("chmod", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003010 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003011#endif
3012
3013#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003014 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003015 attr = GetFileAttributesW(path->wide);
Tim Golden23005082013-10-25 11:22:37 +01003016 if (attr == INVALID_FILE_ATTRIBUTES)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003017 result = 0;
3018 else {
3019 if (mode & _S_IWRITE)
Victor Stinner8c62be82010-05-06 00:08:46 +00003020 attr &= ~FILE_ATTRIBUTE_READONLY;
3021 else
3022 attr |= FILE_ATTRIBUTE_READONLY;
Steve Dowercc16be82016-09-08 10:35:16 -07003023 result = SetFileAttributesW(path->wide, attr);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003024 }
3025 Py_END_ALLOW_THREADS
3026
3027 if (!result) {
Larry Hastings2f936352014-08-05 14:04:04 +10003028 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003029 }
3030#else /* MS_WINDOWS */
3031 Py_BEGIN_ALLOW_THREADS
3032#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003033 if (path->fd != -1)
3034 result = fchmod(path->fd, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003035 else
3036#endif
3037#ifdef HAVE_LCHMOD
3038 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003039 result = lchmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003040 else
3041#endif
3042#ifdef HAVE_FCHMODAT
3043 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
3044 /*
3045 * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
3046 * The documentation specifically shows how to use it,
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003047 * and then says it isn't implemented yet.
3048 * (true on linux with glibc 2.15, and openindiana 3.x)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003049 *
3050 * Once it is supported, os.chmod will automatically
3051 * support dir_fd and follow_symlinks=False. (Hopefully.)
3052 * Until then, we need to be careful what exception we raise.
3053 */
Larry Hastings2f936352014-08-05 14:04:04 +10003054 result = fchmodat(dir_fd, path->narrow, mode,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003055 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3056 /*
3057 * But wait! We can't throw the exception without allowing threads,
3058 * and we can't do that in this nested scope. (Macro trickery, sigh.)
3059 */
3060 fchmodat_nofollow_unsupported =
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003061 result &&
3062 ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
3063 !follow_symlinks;
Victor Stinner8c62be82010-05-06 00:08:46 +00003064 }
3065 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00003066#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003067 result = chmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003068 Py_END_ALLOW_THREADS
3069
3070 if (result) {
3071#ifdef HAVE_FCHMODAT
3072 if (fchmodat_nofollow_unsupported) {
3073 if (dir_fd != DEFAULT_DIR_FD)
3074 dir_fd_and_follow_symlinks_invalid("chmod",
3075 dir_fd, follow_symlinks);
3076 else
3077 follow_symlinks_specified("chmod", follow_symlinks);
Anthony Sottile233ef242017-12-14 08:57:55 -08003078 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003079 }
3080 else
3081#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003082 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003083 }
3084#endif
3085
Larry Hastings2f936352014-08-05 14:04:04 +10003086 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003087}
3088
Larry Hastings9cf065c2012-06-22 16:30:09 -07003089
Christian Heimes4e30a842007-11-30 22:12:06 +00003090#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003091/*[clinic input]
3092os.fchmod
3093
3094 fd: int
3095 mode: int
3096
3097Change the access permissions of the file given by file descriptor fd.
3098
3099Equivalent to os.chmod(fd, mode).
3100[clinic start generated code]*/
3101
Larry Hastings2f936352014-08-05 14:04:04 +10003102static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003103os_fchmod_impl(PyObject *module, int fd, int mode)
3104/*[clinic end generated code: output=afd9bc05b4e426b3 input=8ab11975ca01ee5b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003105{
3106 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003107 int async_err = 0;
3108
3109 do {
3110 Py_BEGIN_ALLOW_THREADS
3111 res = fchmod(fd, mode);
3112 Py_END_ALLOW_THREADS
3113 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3114 if (res != 0)
3115 return (!async_err) ? posix_error() : NULL;
3116
Victor Stinner8c62be82010-05-06 00:08:46 +00003117 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003118}
3119#endif /* HAVE_FCHMOD */
3120
Larry Hastings2f936352014-08-05 14:04:04 +10003121
Christian Heimes4e30a842007-11-30 22:12:06 +00003122#ifdef HAVE_LCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003123/*[clinic input]
3124os.lchmod
3125
3126 path: path_t
3127 mode: int
3128
3129Change the access permissions of a file, without following symbolic links.
3130
3131If path is a symlink, this affects the link itself rather than the target.
3132Equivalent to chmod(path, mode, follow_symlinks=False)."
3133[clinic start generated code]*/
3134
Larry Hastings2f936352014-08-05 14:04:04 +10003135static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003136os_lchmod_impl(PyObject *module, path_t *path, int mode)
3137/*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003138{
Victor Stinner8c62be82010-05-06 00:08:46 +00003139 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003140 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003141 res = lchmod(path->narrow, mode);
Victor Stinner8c62be82010-05-06 00:08:46 +00003142 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003143 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003144 path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003145 return NULL;
3146 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003147 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003148}
3149#endif /* HAVE_LCHMOD */
3150
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003151
Thomas Wouterscf297e42007-02-23 15:07:44 +00003152#ifdef HAVE_CHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003153/*[clinic input]
3154os.chflags
3155
3156 path: path_t
3157 flags: unsigned_long(bitwise=True)
3158 follow_symlinks: bool=True
3159
3160Set file flags.
3161
3162If follow_symlinks is False, and the last element of the path is a symbolic
3163 link, chflags will change flags on the symbolic link itself instead of the
3164 file the link points to.
3165follow_symlinks may not be implemented on your platform. If it is
3166unavailable, using it will raise a NotImplementedError.
3167
3168[clinic start generated code]*/
3169
Larry Hastings2f936352014-08-05 14:04:04 +10003170static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003171os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
Larry Hastings89964c42015-04-14 18:07:59 -04003172 int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003173/*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003174{
3175 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003176
3177#ifndef HAVE_LCHFLAGS
3178 if (follow_symlinks_specified("chflags", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003179 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003180#endif
3181
Victor Stinner8c62be82010-05-06 00:08:46 +00003182 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003183#ifdef HAVE_LCHFLAGS
3184 if (!follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +10003185 result = lchflags(path->narrow, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003186 else
3187#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003188 result = chflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003189 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003190
Larry Hastings2f936352014-08-05 14:04:04 +10003191 if (result)
3192 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003193
Larry Hastings2f936352014-08-05 14:04:04 +10003194 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003195}
3196#endif /* HAVE_CHFLAGS */
3197
Larry Hastings2f936352014-08-05 14:04:04 +10003198
Thomas Wouterscf297e42007-02-23 15:07:44 +00003199#ifdef HAVE_LCHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003200/*[clinic input]
3201os.lchflags
3202
3203 path: path_t
3204 flags: unsigned_long(bitwise=True)
3205
3206Set file flags.
3207
3208This function will not follow symbolic links.
3209Equivalent to chflags(path, flags, follow_symlinks=False).
3210[clinic start generated code]*/
3211
Larry Hastings2f936352014-08-05 14:04:04 +10003212static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003213os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
3214/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003215{
Victor Stinner8c62be82010-05-06 00:08:46 +00003216 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003217 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003218 res = lchflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003219 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003220 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003221 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003222 }
Victor Stinner292c8352012-10-30 02:17:38 +01003223 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003224}
3225#endif /* HAVE_LCHFLAGS */
3226
Larry Hastings2f936352014-08-05 14:04:04 +10003227
Martin v. Löwis244edc82001-10-04 22:44:26 +00003228#ifdef HAVE_CHROOT
Larry Hastings2f936352014-08-05 14:04:04 +10003229/*[clinic input]
3230os.chroot
3231 path: path_t
3232
3233Change root directory to path.
3234
3235[clinic start generated code]*/
3236
Larry Hastings2f936352014-08-05 14:04:04 +10003237static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003238os_chroot_impl(PyObject *module, path_t *path)
3239/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003240{
3241 int res;
3242 Py_BEGIN_ALLOW_THREADS
3243 res = chroot(path->narrow);
3244 Py_END_ALLOW_THREADS
3245 if (res < 0)
3246 return path_error(path);
3247 Py_RETURN_NONE;
3248}
3249#endif /* HAVE_CHROOT */
3250
Martin v. Löwis244edc82001-10-04 22:44:26 +00003251
Guido van Rossum21142a01999-01-08 21:05:37 +00003252#ifdef HAVE_FSYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003253/*[clinic input]
3254os.fsync
3255
3256 fd: fildes
3257
3258Force write of fd to disk.
3259[clinic start generated code]*/
3260
Larry Hastings2f936352014-08-05 14:04:04 +10003261static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003262os_fsync_impl(PyObject *module, int fd)
3263/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003264{
3265 return posix_fildes_fd(fd, fsync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003266}
3267#endif /* HAVE_FSYNC */
3268
Larry Hastings2f936352014-08-05 14:04:04 +10003269
Ross Lagerwall7807c352011-03-17 20:20:30 +02003270#ifdef HAVE_SYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003271/*[clinic input]
3272os.sync
3273
3274Force write of everything to disk.
3275[clinic start generated code]*/
3276
Larry Hastings2f936352014-08-05 14:04:04 +10003277static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003278os_sync_impl(PyObject *module)
3279/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
Ross Lagerwall7807c352011-03-17 20:20:30 +02003280{
3281 Py_BEGIN_ALLOW_THREADS
3282 sync();
3283 Py_END_ALLOW_THREADS
3284 Py_RETURN_NONE;
3285}
Larry Hastings2f936352014-08-05 14:04:04 +10003286#endif /* HAVE_SYNC */
3287
Ross Lagerwall7807c352011-03-17 20:20:30 +02003288
Guido van Rossum21142a01999-01-08 21:05:37 +00003289#ifdef HAVE_FDATASYNC
Guido van Rossum7f58e2e2000-09-22 17:26:14 +00003290#ifdef __hpux
Guido van Rossumecc23b02000-09-22 16:01:05 +00003291extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
3292#endif
3293
Larry Hastings2f936352014-08-05 14:04:04 +10003294/*[clinic input]
3295os.fdatasync
3296
3297 fd: fildes
3298
3299Force write of fd to disk without forcing update of metadata.
3300[clinic start generated code]*/
3301
Larry Hastings2f936352014-08-05 14:04:04 +10003302static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003303os_fdatasync_impl(PyObject *module, int fd)
3304/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003305{
3306 return posix_fildes_fd(fd, fdatasync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003307}
3308#endif /* HAVE_FDATASYNC */
3309
3310
Fredrik Lundh10723342000-07-10 16:38:09 +00003311#ifdef HAVE_CHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003312/*[clinic input]
3313os.chown
3314
3315 path : path_t(allow_fd='PATH_HAVE_FCHOWN')
BNMetricsb9427072018-11-02 15:20:19 +00003316 Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
Larry Hastings2f936352014-08-05 14:04:04 +10003317
3318 uid: uid_t
3319
3320 gid: gid_t
3321
3322 *
3323
3324 dir_fd : dir_fd(requires='fchownat') = None
3325 If not None, it should be a file descriptor open to a directory,
3326 and path should be relative; path will then be relative to that
3327 directory.
3328
3329 follow_symlinks: bool = True
3330 If False, and the last element of the path is a symbolic link,
3331 stat will examine the symbolic link itself instead of the file
3332 the link points to.
3333
3334Change the owner and group id of path to the numeric uid and gid.\
3335
3336path may always be specified as a string.
3337On some platforms, path may also be specified as an open file descriptor.
3338 If this functionality is unavailable, using it raises an exception.
3339If dir_fd is not None, it should be a file descriptor open to a directory,
3340 and path should be relative; path will then be relative to that directory.
3341If follow_symlinks is False, and the last element of the path is a symbolic
3342 link, chown will modify the symbolic link itself instead of the file the
3343 link points to.
3344It is an error to use dir_fd or follow_symlinks when specifying path as
3345 an open file descriptor.
3346dir_fd and follow_symlinks may not be implemented on your platform.
3347 If they are unavailable, using them will raise a NotImplementedError.
3348
3349[clinic start generated code]*/
3350
Larry Hastings2f936352014-08-05 14:04:04 +10003351static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003352os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
Larry Hastings89964c42015-04-14 18:07:59 -04003353 int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003354/*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003355{
3356 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003357
3358#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
3359 if (follow_symlinks_specified("chown", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003360 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003361#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003362 if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
3363 fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
3364 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003365
3366#ifdef __APPLE__
3367 /*
3368 * This is for Mac OS X 10.3, which doesn't have lchown.
3369 * (But we still have an lchown symbol because of weak-linking.)
3370 * It doesn't have fchownat either. So there's no possibility
3371 * of a graceful failover.
Georg Brandlf7875592012-06-24 13:58:31 +02003372 */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003373 if ((!follow_symlinks) && (lchown == NULL)) {
3374 follow_symlinks_specified("chown", follow_symlinks);
Larry Hastings2f936352014-08-05 14:04:04 +10003375 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003376 }
3377#endif
3378
Victor Stinner8c62be82010-05-06 00:08:46 +00003379 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003380#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003381 if (path->fd != -1)
3382 result = fchown(path->fd, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003383 else
3384#endif
3385#ifdef HAVE_LCHOWN
3386 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003387 result = lchown(path->narrow, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003388 else
3389#endif
3390#ifdef HAVE_FCHOWNAT
3391 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003392 result = fchownat(dir_fd, path->narrow, uid, gid,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003393 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3394 else
3395#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003396 result = chown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003397 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003398
Larry Hastings2f936352014-08-05 14:04:04 +10003399 if (result)
3400 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003401
Larry Hastings2f936352014-08-05 14:04:04 +10003402 Py_RETURN_NONE;
Guido van Rossumb6775db1994-08-01 11:34:53 +00003403}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003404#endif /* HAVE_CHOWN */
Guido van Rossumb6775db1994-08-01 11:34:53 +00003405
Larry Hastings2f936352014-08-05 14:04:04 +10003406
Christian Heimes4e30a842007-11-30 22:12:06 +00003407#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003408/*[clinic input]
3409os.fchown
3410
3411 fd: int
3412 uid: uid_t
3413 gid: gid_t
3414
3415Change the owner and group id of the file specified by file descriptor.
3416
3417Equivalent to os.chown(fd, uid, gid).
3418
3419[clinic start generated code]*/
3420
Larry Hastings2f936352014-08-05 14:04:04 +10003421static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003422os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
3423/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003424{
Victor Stinner8c62be82010-05-06 00:08:46 +00003425 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003426 int async_err = 0;
3427
3428 do {
3429 Py_BEGIN_ALLOW_THREADS
3430 res = fchown(fd, uid, gid);
3431 Py_END_ALLOW_THREADS
3432 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3433 if (res != 0)
3434 return (!async_err) ? posix_error() : NULL;
3435
Victor Stinner8c62be82010-05-06 00:08:46 +00003436 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003437}
3438#endif /* HAVE_FCHOWN */
3439
Larry Hastings2f936352014-08-05 14:04:04 +10003440
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003441#ifdef HAVE_LCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003442/*[clinic input]
3443os.lchown
3444
3445 path : path_t
3446 uid: uid_t
3447 gid: gid_t
3448
3449Change the owner and group id of path to the numeric uid and gid.
3450
3451This function will not follow symbolic links.
3452Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
3453[clinic start generated code]*/
3454
Larry Hastings2f936352014-08-05 14:04:04 +10003455static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003456os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
3457/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003458{
Victor Stinner8c62be82010-05-06 00:08:46 +00003459 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003460 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10003461 res = lchown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003462 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003463 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003464 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003465 }
Larry Hastings2f936352014-08-05 14:04:04 +10003466 Py_RETURN_NONE;
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003467}
3468#endif /* HAVE_LCHOWN */
3469
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003470
Barry Warsaw53699e91996-12-10 23:23:01 +00003471static PyObject *
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003472posix_getcwd(int use_bytes)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003473{
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003474#ifdef MS_WINDOWS
Victor Stinner689830e2019-06-26 17:31:12 +02003475 wchar_t wbuf[MAXPATHLEN];
3476 wchar_t *wbuf2 = wbuf;
3477 DWORD len;
3478
3479 Py_BEGIN_ALLOW_THREADS
3480 len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
3481 /* If the buffer is large enough, len does not include the
3482 terminating \0. If the buffer is too small, len includes
3483 the space needed for the terminator. */
3484 if (len >= Py_ARRAY_LENGTH(wbuf)) {
Victor Stinnerec3e20a2019-06-28 18:01:59 +02003485 if (len <= PY_SSIZE_T_MAX / sizeof(wchar_t)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02003486 wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00003487 }
Victor Stinner689830e2019-06-26 17:31:12 +02003488 else {
3489 wbuf2 = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003490 }
Victor Stinner689830e2019-06-26 17:31:12 +02003491 if (wbuf2) {
3492 len = GetCurrentDirectoryW(len, wbuf2);
Victor Stinner8c62be82010-05-06 00:08:46 +00003493 }
Victor Stinner689830e2019-06-26 17:31:12 +02003494 }
3495 Py_END_ALLOW_THREADS
3496
3497 if (!wbuf2) {
3498 PyErr_NoMemory();
3499 return NULL;
3500 }
3501 if (!len) {
Victor Stinnerb024e842012-10-31 22:24:06 +01003502 if (wbuf2 != wbuf)
Victor Stinnerb6404912013-07-07 16:21:41 +02003503 PyMem_RawFree(wbuf2);
Victor Stinner689830e2019-06-26 17:31:12 +02003504 return PyErr_SetFromWindowsErr(0);
Victor Stinner8c62be82010-05-06 00:08:46 +00003505 }
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01003506
Victor Stinner689830e2019-06-26 17:31:12 +02003507 PyObject *resobj = PyUnicode_FromWideChar(wbuf2, len);
3508 if (wbuf2 != wbuf) {
3509 PyMem_RawFree(wbuf2);
3510 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003511
Victor Stinner689830e2019-06-26 17:31:12 +02003512 if (use_bytes) {
3513 if (resobj == NULL) {
3514 return NULL;
3515 }
3516 Py_SETREF(resobj, PyUnicode_EncodeFSDefault(resobj));
3517 }
3518
3519 return resobj;
3520#else
3521 const size_t chunk = 1024;
3522
3523 char *buf = NULL;
3524 char *cwd = NULL;
3525 size_t buflen = 0;
3526
Victor Stinner8c62be82010-05-06 00:08:46 +00003527 Py_BEGIN_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003528 do {
Victor Stinner689830e2019-06-26 17:31:12 +02003529 char *newbuf;
3530 if (buflen <= PY_SSIZE_T_MAX - chunk) {
3531 buflen += chunk;
3532 newbuf = PyMem_RawRealloc(buf, buflen);
3533 }
3534 else {
3535 newbuf = NULL;
3536 }
3537 if (newbuf == NULL) {
3538 PyMem_RawFree(buf);
3539 buf = NULL;
Victor Stinnerc44f7072016-03-14 18:07:53 +01003540 break;
3541 }
Victor Stinner689830e2019-06-26 17:31:12 +02003542 buf = newbuf;
Victor Stinner4403d7d2015-04-25 00:16:10 +02003543
Victor Stinner4403d7d2015-04-25 00:16:10 +02003544 cwd = getcwd(buf, buflen);
3545 } while (cwd == NULL && errno == ERANGE);
Victor Stinner8c62be82010-05-06 00:08:46 +00003546 Py_END_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003547
Victor Stinner689830e2019-06-26 17:31:12 +02003548 if (buf == NULL) {
3549 return PyErr_NoMemory();
3550 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003551 if (cwd == NULL) {
3552 PyMem_RawFree(buf);
Victor Stinner8c62be82010-05-06 00:08:46 +00003553 return posix_error();
Victor Stinner4403d7d2015-04-25 00:16:10 +02003554 }
3555
Victor Stinner689830e2019-06-26 17:31:12 +02003556 PyObject *obj;
3557 if (use_bytes) {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003558 obj = PyBytes_FromStringAndSize(buf, strlen(buf));
Victor Stinner689830e2019-06-26 17:31:12 +02003559 }
3560 else {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003561 obj = PyUnicode_DecodeFSDefault(buf);
Victor Stinner689830e2019-06-26 17:31:12 +02003562 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003563 PyMem_RawFree(buf);
3564
3565 return obj;
Victor Stinner689830e2019-06-26 17:31:12 +02003566#endif /* !MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003567}
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003568
Larry Hastings2f936352014-08-05 14:04:04 +10003569
3570/*[clinic input]
3571os.getcwd
3572
3573Return a unicode string representing the current working directory.
3574[clinic start generated code]*/
3575
Larry Hastings2f936352014-08-05 14:04:04 +10003576static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003577os_getcwd_impl(PyObject *module)
3578/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003579{
3580 return posix_getcwd(0);
3581}
3582
Larry Hastings2f936352014-08-05 14:04:04 +10003583
3584/*[clinic input]
3585os.getcwdb
3586
3587Return a bytes string representing the current working directory.
3588[clinic start generated code]*/
3589
Larry Hastings2f936352014-08-05 14:04:04 +10003590static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003591os_getcwdb_impl(PyObject *module)
3592/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003593{
3594 return posix_getcwd(1);
3595}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003596
Larry Hastings2f936352014-08-05 14:04:04 +10003597
Larry Hastings9cf065c2012-06-22 16:30:09 -07003598#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
3599#define HAVE_LINK 1
3600#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003601
Guido van Rossumb6775db1994-08-01 11:34:53 +00003602#ifdef HAVE_LINK
Larry Hastings2f936352014-08-05 14:04:04 +10003603/*[clinic input]
3604
3605os.link
3606
3607 src : path_t
3608 dst : path_t
3609 *
3610 src_dir_fd : dir_fd = None
3611 dst_dir_fd : dir_fd = None
3612 follow_symlinks: bool = True
3613
3614Create a hard link to a file.
3615
3616If either src_dir_fd or dst_dir_fd is not None, it should be a file
3617 descriptor open to a directory, and the respective path string (src or dst)
3618 should be relative; the path will then be relative to that directory.
3619If follow_symlinks is False, and the last element of src is a symbolic
3620 link, link will create a link to the symbolic link itself instead of the
3621 file the link points to.
3622src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
3623 platform. If they are unavailable, using them will raise a
3624 NotImplementedError.
3625[clinic start generated code]*/
3626
Larry Hastings2f936352014-08-05 14:04:04 +10003627static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003628os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003629 int dst_dir_fd, int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003630/*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003631{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003632#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07003633 BOOL result = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003634#else
3635 int result;
3636#endif
3637
Larry Hastings9cf065c2012-06-22 16:30:09 -07003638#ifndef HAVE_LINKAT
3639 if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
3640 argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10003641 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003642 }
3643#endif
3644
Steve Dowercc16be82016-09-08 10:35:16 -07003645#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10003646 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003647 PyErr_SetString(PyExc_NotImplementedError,
3648 "link: src and dst must be the same type");
Larry Hastings2f936352014-08-05 14:04:04 +10003649 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003650 }
Steve Dowercc16be82016-09-08 10:35:16 -07003651#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003652
Brian Curtin1b9df392010-11-24 20:24:31 +00003653#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003654 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08003655 result = CreateHardLinkW(dst->wide, src->wide, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003656 Py_END_ALLOW_THREADS
Brian Curtin1b9df392010-11-24 20:24:31 +00003657
Larry Hastings2f936352014-08-05 14:04:04 +10003658 if (!result)
3659 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003660#else
3661 Py_BEGIN_ALLOW_THREADS
Larry Hastings67cbf7b2012-06-22 17:06:48 -07003662#ifdef HAVE_LINKAT
Larry Hastings9cf065c2012-06-22 16:30:09 -07003663 if ((src_dir_fd != DEFAULT_DIR_FD) ||
3664 (dst_dir_fd != DEFAULT_DIR_FD) ||
3665 (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003666 result = linkat(src_dir_fd, src->narrow,
3667 dst_dir_fd, dst->narrow,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003668 follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
3669 else
Steve Dowercc16be82016-09-08 10:35:16 -07003670#endif /* HAVE_LINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10003671 result = link(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003672 Py_END_ALLOW_THREADS
Brian Curtinfc889c42010-11-28 23:59:46 +00003673
Larry Hastings2f936352014-08-05 14:04:04 +10003674 if (result)
3675 return path_error2(src, dst);
Steve Dowercc16be82016-09-08 10:35:16 -07003676#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003677
Larry Hastings2f936352014-08-05 14:04:04 +10003678 Py_RETURN_NONE;
Brian Curtin1b9df392010-11-24 20:24:31 +00003679}
Larry Hastings9cf065c2012-06-22 16:30:09 -07003680#endif
3681
Brian Curtin1b9df392010-11-24 20:24:31 +00003682
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003683#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
Barry Warsaw53699e91996-12-10 23:23:01 +00003684static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003685_listdir_windows_no_opendir(path_t *path, PyObject *list)
Guido van Rossumb6775db1994-08-01 11:34:53 +00003686{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003687 PyObject *v;
3688 HANDLE hFindFile = INVALID_HANDLE_VALUE;
3689 BOOL result;
Steve Dowercc16be82016-09-08 10:35:16 -07003690 wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003691 /* only claim to have space for MAX_PATH */
Victor Stinner75875072013-11-24 19:23:25 +01003692 Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003693 wchar_t *wnamebuf = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003694
Steve Dowercc16be82016-09-08 10:35:16 -07003695 WIN32_FIND_DATAW wFileData;
3696 const wchar_t *po_wchars;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003697
Steve Dowercc16be82016-09-08 10:35:16 -07003698 if (!path->wide) { /* Default arg: "." */
3699 po_wchars = L".";
3700 len = 1;
3701 } else {
3702 po_wchars = path->wide;
3703 len = wcslen(path->wide);
3704 }
3705 /* The +5 is so we can append "\\*.*\0" */
3706 wnamebuf = PyMem_New(wchar_t, len + 5);
3707 if (!wnamebuf) {
3708 PyErr_NoMemory();
Larry Hastings9cf065c2012-06-22 16:30:09 -07003709 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003710 }
Steve Dowercc16be82016-09-08 10:35:16 -07003711 wcscpy(wnamebuf, po_wchars);
Victor Stinner8c62be82010-05-06 00:08:46 +00003712 if (len > 0) {
Steve Dowercc16be82016-09-08 10:35:16 -07003713 wchar_t wch = wnamebuf[len-1];
3714 if (wch != SEP && wch != ALTSEP && wch != L':')
3715 wnamebuf[len++] = SEP;
3716 wcscpy(wnamebuf + len, L"*.*");
Victor Stinner8c62be82010-05-06 00:08:46 +00003717 }
Steve Dowercc16be82016-09-08 10:35:16 -07003718 if ((list = PyList_New(0)) == NULL) {
3719 goto exit;
3720 }
Antoine Pitroub73caab2010-08-09 23:39:31 +00003721 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003722 hFindFile = FindFirstFileW(wnamebuf, &wFileData);
Antoine Pitroub73caab2010-08-09 23:39:31 +00003723 Py_END_ALLOW_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +00003724 if (hFindFile == INVALID_HANDLE_VALUE) {
3725 int error = GetLastError();
3726 if (error == ERROR_FILE_NOT_FOUND)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003727 goto exit;
3728 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003729 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003730 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003731 }
3732 do {
3733 /* Skip over . and .. */
Steve Dowercc16be82016-09-08 10:35:16 -07003734 if (wcscmp(wFileData.cFileName, L".") != 0 &&
3735 wcscmp(wFileData.cFileName, L"..") != 0) {
3736 v = PyUnicode_FromWideChar(wFileData.cFileName,
3737 wcslen(wFileData.cFileName));
3738 if (path->narrow && v) {
3739 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3740 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003741 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003742 Py_DECREF(list);
3743 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003744 break;
3745 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003746 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003747 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003748 Py_DECREF(list);
3749 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003750 break;
3751 }
3752 Py_DECREF(v);
3753 }
3754 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003755 result = FindNextFileW(hFindFile, &wFileData);
Victor Stinner8c62be82010-05-06 00:08:46 +00003756 Py_END_ALLOW_THREADS
3757 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
3758 it got to the end of the directory. */
3759 if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003760 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003761 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003762 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003763 }
3764 } while (result == TRUE);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003765
Larry Hastings9cf065c2012-06-22 16:30:09 -07003766exit:
3767 if (hFindFile != INVALID_HANDLE_VALUE) {
3768 if (FindClose(hFindFile) == FALSE) {
3769 if (list != NULL) {
3770 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003771 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003772 }
3773 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003774 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003775 PyMem_Free(wnamebuf);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003776
Larry Hastings9cf065c2012-06-22 16:30:09 -07003777 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003778} /* end of _listdir_windows_no_opendir */
3779
3780#else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
3781
3782static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003783_posix_listdir(path_t *path, PyObject *list)
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003784{
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003785 PyObject *v;
3786 DIR *dirp = NULL;
3787 struct dirent *ep;
3788 int return_str; /* if false, return bytes */
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003789#ifdef HAVE_FDOPENDIR
3790 int fd = -1;
3791#endif
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003792
Victor Stinner8c62be82010-05-06 00:08:46 +00003793 errno = 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003794#ifdef HAVE_FDOPENDIR
Gregory P. Smith40a21602013-03-20 20:52:50 -07003795 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003796 /* closedir() closes the FD, so we duplicate it */
Victor Stinnerdaf45552013-08-28 00:53:59 +02003797 fd = _Py_dup(path->fd);
Victor Stinnerf3266652013-12-19 13:24:49 +01003798 if (fd == -1)
3799 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003800
Larry Hastingsfdaea062012-06-25 04:42:23 -07003801 return_str = 1;
3802
Larry Hastings9cf065c2012-06-22 16:30:09 -07003803 Py_BEGIN_ALLOW_THREADS
3804 dirp = fdopendir(fd);
3805 Py_END_ALLOW_THREADS
3806 }
3807 else
3808#endif
3809 {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003810 const char *name;
Gregory P. Smith40a21602013-03-20 20:52:50 -07003811 if (path->narrow) {
3812 name = path->narrow;
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03003813 /* only return bytes if they specified a bytes-like object */
3814 return_str = !PyObject_CheckBuffer(path->object);
Larry Hastingsfdaea062012-06-25 04:42:23 -07003815 }
3816 else {
3817 name = ".";
3818 return_str = 1;
3819 }
3820
Larry Hastings9cf065c2012-06-22 16:30:09 -07003821 Py_BEGIN_ALLOW_THREADS
3822 dirp = opendir(name);
3823 Py_END_ALLOW_THREADS
3824 }
3825
3826 if (dirp == NULL) {
Gregory P. Smith40a21602013-03-20 20:52:50 -07003827 list = path_error(path);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003828#ifdef HAVE_FDOPENDIR
3829 if (fd != -1) {
3830 Py_BEGIN_ALLOW_THREADS
3831 close(fd);
3832 Py_END_ALLOW_THREADS
3833 }
3834#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003835 goto exit;
3836 }
3837 if ((list = PyList_New(0)) == NULL) {
3838 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003839 }
3840 for (;;) {
3841 errno = 0;
3842 Py_BEGIN_ALLOW_THREADS
3843 ep = readdir(dirp);
3844 Py_END_ALLOW_THREADS
3845 if (ep == NULL) {
3846 if (errno == 0) {
3847 break;
3848 } else {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003849 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003850 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003851 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003852 }
3853 }
3854 if (ep->d_name[0] == '.' &&
3855 (NAMLEN(ep) == 1 ||
3856 (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
3857 continue;
Larry Hastingsfdaea062012-06-25 04:42:23 -07003858 if (return_str)
Victor Stinnera45598a2010-05-14 16:35:39 +00003859 v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
3860 else
3861 v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
Victor Stinner8c62be82010-05-06 00:08:46 +00003862 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003863 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003864 break;
3865 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003866 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003867 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003868 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003869 break;
3870 }
3871 Py_DECREF(v);
3872 }
Guido van Rossum0ee42cd1991-04-08 21:01:03 +00003873
Larry Hastings9cf065c2012-06-22 16:30:09 -07003874exit:
3875 if (dirp != NULL) {
3876 Py_BEGIN_ALLOW_THREADS
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003877#ifdef HAVE_FDOPENDIR
Larry Hastings9cf065c2012-06-22 16:30:09 -07003878 if (fd > -1)
3879 rewinddir(dirp);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003880#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003881 closedir(dirp);
3882 Py_END_ALLOW_THREADS
3883 }
3884
Larry Hastings9cf065c2012-06-22 16:30:09 -07003885 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003886} /* end of _posix_listdir */
3887#endif /* which OS */
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003888
Larry Hastings2f936352014-08-05 14:04:04 +10003889
3890/*[clinic input]
3891os.listdir
3892
3893 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
3894
3895Return a list containing the names of the files in the directory.
3896
BNMetricsb9427072018-11-02 15:20:19 +00003897path can be specified as either str, bytes, or a path-like object. If path is bytes,
Larry Hastings2f936352014-08-05 14:04:04 +10003898 the filenames returned will also be bytes; in all other circumstances
3899 the filenames returned will be str.
3900If path is None, uses the path='.'.
3901On some platforms, path may also be specified as an open file descriptor;\
3902 the file descriptor must refer to a directory.
3903 If this functionality is unavailable, using it raises NotImplementedError.
3904
3905The list is in arbitrary order. It does not include the special
3906entries '.' and '..' even if they are present in the directory.
3907
3908
3909[clinic start generated code]*/
3910
Larry Hastings2f936352014-08-05 14:04:04 +10003911static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003912os_listdir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +00003913/*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003914{
Steve Dower60419a72019-06-24 08:42:54 -07003915 if (PySys_Audit("os.listdir", "O",
3916 path->object ? path->object : Py_None) < 0) {
3917 return NULL;
3918 }
Larry Hastings2f936352014-08-05 14:04:04 +10003919#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
3920 return _listdir_windows_no_opendir(path, NULL);
3921#else
3922 return _posix_listdir(path, NULL);
3923#endif
3924}
3925
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00003926#ifdef MS_WINDOWS
Mark Hammondef8b6542001-05-13 08:04:26 +00003927/* A helper function for abspath on win32 */
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003928/*[clinic input]
3929os._getfullpathname
Victor Stinnereb5657a2011-09-30 01:44:27 +02003930
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003931 path: path_t
3932 /
3933
3934[clinic start generated code]*/
3935
3936static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003937os__getfullpathname_impl(PyObject *module, path_t *path)
3938/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003939{
Victor Stinner3939c322019-06-25 15:02:43 +02003940 wchar_t *abspath;
Victor Stinnereb5657a2011-09-30 01:44:27 +02003941
Victor Stinner3939c322019-06-25 15:02:43 +02003942 /* _Py_abspath() is implemented with GetFullPathNameW() on Windows */
3943 if (_Py_abspath(path->wide, &abspath) < 0) {
3944 return win32_error_object("GetFullPathNameW", path->object);
Victor Stinner8c62be82010-05-06 00:08:46 +00003945 }
Victor Stinner3939c322019-06-25 15:02:43 +02003946 if (abspath == NULL) {
3947 return PyErr_NoMemory();
3948 }
3949
3950 PyObject *str = PyUnicode_FromWideChar(abspath, wcslen(abspath));
3951 PyMem_RawFree(abspath);
3952 if (str == NULL) {
3953 return NULL;
3954 }
3955 if (path->narrow) {
3956 Py_SETREF(str, PyUnicode_EncodeFSDefault(str));
3957 }
3958 return str;
Larry Hastings2f936352014-08-05 14:04:04 +10003959}
Brian Curtind40e6f72010-07-08 21:39:08 +00003960
Brian Curtind25aef52011-06-13 15:16:04 -05003961
Larry Hastings2f936352014-08-05 14:04:04 +10003962/*[clinic input]
3963os._getfinalpathname
Brian Curtinf5e76d02010-11-24 13:14:05 +00003964
Steve Dower23ad6d02018-02-22 10:39:10 -08003965 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10003966 /
3967
3968A helper function for samepath on windows.
3969[clinic start generated code]*/
3970
Larry Hastings2f936352014-08-05 14:04:04 +10003971static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08003972os__getfinalpathname_impl(PyObject *module, path_t *path)
3973/*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
Brian Curtind40e6f72010-07-08 21:39:08 +00003974{
3975 HANDLE hFile;
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003976 wchar_t buf[MAXPATHLEN], *target_path = buf;
3977 int buf_size = Py_ARRAY_LENGTH(buf);
Brian Curtind40e6f72010-07-08 21:39:08 +00003978 int result_length;
Larry Hastings2f936352014-08-05 14:04:04 +10003979 PyObject *result;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003980
Steve Dower23ad6d02018-02-22 10:39:10 -08003981 Py_BEGIN_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00003982 hFile = CreateFileW(
Steve Dower23ad6d02018-02-22 10:39:10 -08003983 path->wide,
Brian Curtind40e6f72010-07-08 21:39:08 +00003984 0, /* desired access */
3985 0, /* share mode */
3986 NULL, /* security attributes */
3987 OPEN_EXISTING,
3988 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
3989 FILE_FLAG_BACKUP_SEMANTICS,
3990 NULL);
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003991 Py_END_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003992
Steve Dower23ad6d02018-02-22 10:39:10 -08003993 if (hFile == INVALID_HANDLE_VALUE) {
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003994 return win32_error_object("CreateFileW", path->object);
Steve Dower23ad6d02018-02-22 10:39:10 -08003995 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003996
3997 /* We have a good handle to the target, use it to determine the
3998 target path name. */
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003999 while (1) {
4000 Py_BEGIN_ALLOW_THREADS
4001 result_length = GetFinalPathNameByHandleW(hFile, target_path,
4002 buf_size, VOLUME_NAME_DOS);
4003 Py_END_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00004004
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004005 if (!result_length) {
4006 result = win32_error_object("GetFinalPathNameByHandleW",
4007 path->object);
4008 goto cleanup;
4009 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004010
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004011 if (result_length < buf_size) {
4012 break;
4013 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004014
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004015 wchar_t *tmp;
4016 tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
4017 result_length * sizeof(*tmp));
4018 if (!tmp) {
4019 result = PyErr_NoMemory();
4020 goto cleanup;
4021 }
4022
4023 buf_size = result_length;
4024 target_path = tmp;
Steve Dower23ad6d02018-02-22 10:39:10 -08004025 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004026
Victor Stinner9d3b93b2011-11-22 02:27:30 +01004027 result = PyUnicode_FromWideChar(target_path, result_length);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004028 if (result && path->narrow) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004029 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004030 }
Steve Dower23ad6d02018-02-22 10:39:10 -08004031
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004032cleanup:
4033 if (target_path != buf) {
4034 PyMem_Free(target_path);
4035 }
4036 CloseHandle(hFile);
4037 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10004038}
Brian Curtin62857742010-09-06 17:07:27 +00004039
Tim Golden6b528062013-08-01 12:44:00 +01004040
Larry Hastings2f936352014-08-05 14:04:04 +10004041/*[clinic input]
4042os._getvolumepathname
4043
Steve Dower23ad6d02018-02-22 10:39:10 -08004044 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10004045
4046A helper function for ismount on Win32.
4047[clinic start generated code]*/
4048
Larry Hastings2f936352014-08-05 14:04:04 +10004049static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08004050os__getvolumepathname_impl(PyObject *module, path_t *path)
4051/*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004052{
4053 PyObject *result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004054 wchar_t *mountpath=NULL;
Victor Stinner6edddfa2013-11-24 19:22:57 +01004055 size_t buflen;
Tim Golden6b528062013-08-01 12:44:00 +01004056 BOOL ret;
4057
Tim Golden6b528062013-08-01 12:44:00 +01004058 /* Volume path should be shorter than entire path */
Steve Dower23ad6d02018-02-22 10:39:10 -08004059 buflen = Py_MAX(path->length, MAX_PATH);
Victor Stinner6edddfa2013-11-24 19:22:57 +01004060
Victor Stinner850a18e2017-10-24 16:53:32 -07004061 if (buflen > PY_DWORD_MAX) {
Victor Stinner6edddfa2013-11-24 19:22:57 +01004062 PyErr_SetString(PyExc_OverflowError, "path too long");
4063 return NULL;
4064 }
4065
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004066 mountpath = PyMem_New(wchar_t, buflen);
Tim Golden6b528062013-08-01 12:44:00 +01004067 if (mountpath == NULL)
4068 return PyErr_NoMemory();
4069
4070 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -08004071 ret = GetVolumePathNameW(path->wide, mountpath,
Victor Stinner6edddfa2013-11-24 19:22:57 +01004072 Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
Tim Golden6b528062013-08-01 12:44:00 +01004073 Py_END_ALLOW_THREADS
4074
4075 if (!ret) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004076 result = win32_error_object("_getvolumepathname", path->object);
Tim Golden6b528062013-08-01 12:44:00 +01004077 goto exit;
4078 }
4079 result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
Steve Dower23ad6d02018-02-22 10:39:10 -08004080 if (path->narrow)
4081 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Tim Golden6b528062013-08-01 12:44:00 +01004082
4083exit:
4084 PyMem_Free(mountpath);
4085 return result;
4086}
Tim Golden6b528062013-08-01 12:44:00 +01004087
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004088#endif /* MS_WINDOWS */
Mark Hammondef8b6542001-05-13 08:04:26 +00004089
Larry Hastings2f936352014-08-05 14:04:04 +10004090
4091/*[clinic input]
4092os.mkdir
4093
4094 path : path_t
4095
4096 mode: int = 0o777
4097
4098 *
4099
4100 dir_fd : dir_fd(requires='mkdirat') = None
4101
4102# "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
4103
4104Create a directory.
4105
4106If dir_fd is not None, it should be a file descriptor open to a directory,
4107 and path should be relative; path will then be relative to that directory.
4108dir_fd may not be implemented on your platform.
4109 If it is unavailable, using it will raise a NotImplementedError.
4110
4111The mode argument is ignored on Windows.
4112[clinic start generated code]*/
4113
Larry Hastings2f936352014-08-05 14:04:04 +10004114static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004115os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
4116/*[clinic end generated code: output=a70446903abe821f input=e965f68377e9b1ce]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004117{
4118 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004119
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004120#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004121 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004122 result = CreateDirectoryW(path->wide, NULL);
Victor Stinner8c62be82010-05-06 00:08:46 +00004123 Py_END_ALLOW_THREADS
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004124
Larry Hastings2f936352014-08-05 14:04:04 +10004125 if (!result)
4126 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004127#else
Victor Stinner8c62be82010-05-06 00:08:46 +00004128 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004129#if HAVE_MKDIRAT
4130 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004131 result = mkdirat(dir_fd, path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004132 else
4133#endif
Erik Bray03eb11f2017-10-27 14:27:06 +02004134#if defined(__WATCOMC__) && !defined(__QNX__)
Larry Hastings2f936352014-08-05 14:04:04 +10004135 result = mkdir(path->narrow);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004136#else
Larry Hastings2f936352014-08-05 14:04:04 +10004137 result = mkdir(path->narrow, mode);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004138#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004139 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004140 if (result < 0)
4141 return path_error(path);
Steve Dowercc16be82016-09-08 10:35:16 -07004142#endif /* MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10004143 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004144}
4145
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004146
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004147/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
4148#if defined(HAVE_SYS_RESOURCE_H)
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004149#include <sys/resource.h>
4150#endif
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004151
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004152
4153#ifdef HAVE_NICE
Larry Hastings2f936352014-08-05 14:04:04 +10004154/*[clinic input]
4155os.nice
4156
4157 increment: int
4158 /
4159
4160Add increment to the priority of process and return the new priority.
4161[clinic start generated code]*/
4162
Larry Hastings2f936352014-08-05 14:04:04 +10004163static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004164os_nice_impl(PyObject *module, int increment)
4165/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004166{
4167 int value;
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004168
Victor Stinner8c62be82010-05-06 00:08:46 +00004169 /* There are two flavours of 'nice': one that returns the new
4170 priority (as required by almost all standards out there) and the
Benjamin Peterson288d1da2017-09-28 22:44:27 -07004171 Linux/FreeBSD one, which returns '0' on success and advices
Victor Stinner8c62be82010-05-06 00:08:46 +00004172 the use of getpriority() to get the new priority.
Tim Peters5aa91602002-01-30 05:46:57 +00004173
Victor Stinner8c62be82010-05-06 00:08:46 +00004174 If we are of the nice family that returns the new priority, we
4175 need to clear errno before the call, and check if errno is filled
4176 before calling posix_error() on a returnvalue of -1, because the
4177 -1 may be the actual new priority! */
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004178
Victor Stinner8c62be82010-05-06 00:08:46 +00004179 errno = 0;
4180 value = nice(increment);
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004181#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
Victor Stinner8c62be82010-05-06 00:08:46 +00004182 if (value == 0)
4183 value = getpriority(PRIO_PROCESS, 0);
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004184#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004185 if (value == -1 && errno != 0)
4186 /* either nice() or getpriority() returned an error */
4187 return posix_error();
4188 return PyLong_FromLong((long) value);
Guido van Rossum775f4da1993-01-09 17:18:52 +00004189}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004190#endif /* HAVE_NICE */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004191
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004192
4193#ifdef HAVE_GETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004194/*[clinic input]
4195os.getpriority
4196
4197 which: int
4198 who: int
4199
4200Return program scheduling priority.
4201[clinic start generated code]*/
4202
Larry Hastings2f936352014-08-05 14:04:04 +10004203static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004204os_getpriority_impl(PyObject *module, int which, int who)
4205/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004206{
4207 int retval;
4208
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004209 errno = 0;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004210 retval = getpriority(which, who);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004211 if (errno != 0)
4212 return posix_error();
4213 return PyLong_FromLong((long)retval);
4214}
4215#endif /* HAVE_GETPRIORITY */
4216
4217
4218#ifdef HAVE_SETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004219/*[clinic input]
4220os.setpriority
4221
4222 which: int
4223 who: int
4224 priority: int
4225
4226Set program scheduling priority.
4227[clinic start generated code]*/
4228
Larry Hastings2f936352014-08-05 14:04:04 +10004229static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004230os_setpriority_impl(PyObject *module, int which, int who, int priority)
4231/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004232{
4233 int retval;
4234
4235 retval = setpriority(which, who, priority);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004236 if (retval == -1)
4237 return posix_error();
4238 Py_RETURN_NONE;
4239}
4240#endif /* HAVE_SETPRIORITY */
4241
4242
Barry Warsaw53699e91996-12-10 23:23:01 +00004243static PyObject *
Larry Hastings2f936352014-08-05 14:04:04 +10004244internal_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 +00004245{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004246 const char *function_name = is_replace ? "replace" : "rename";
Larry Hastings9cf065c2012-06-22 16:30:09 -07004247 int dir_fd_specified;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004248
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004249#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004250 BOOL result;
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004251 int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004252#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004253 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004254#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004255
Larry Hastings9cf065c2012-06-22 16:30:09 -07004256 dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
4257 (dst_dir_fd != DEFAULT_DIR_FD);
4258#ifndef HAVE_RENAMEAT
4259 if (dir_fd_specified) {
4260 argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10004261 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004262 }
4263#endif
4264
Larry Hastings9cf065c2012-06-22 16:30:09 -07004265#ifdef MS_WINDOWS
4266 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004267 result = MoveFileExW(src->wide, dst->wide, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004268 Py_END_ALLOW_THREADS
4269
Larry Hastings2f936352014-08-05 14:04:04 +10004270 if (!result)
4271 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004272
4273#else
Steve Dowercc16be82016-09-08 10:35:16 -07004274 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
4275 PyErr_Format(PyExc_ValueError,
4276 "%s: src and dst must be the same type", function_name);
4277 return NULL;
4278 }
4279
Larry Hastings9cf065c2012-06-22 16:30:09 -07004280 Py_BEGIN_ALLOW_THREADS
4281#ifdef HAVE_RENAMEAT
4282 if (dir_fd_specified)
Larry Hastings2f936352014-08-05 14:04:04 +10004283 result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004284 else
4285#endif
Steve Dowercc16be82016-09-08 10:35:16 -07004286 result = rename(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004287 Py_END_ALLOW_THREADS
4288
Larry Hastings2f936352014-08-05 14:04:04 +10004289 if (result)
4290 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004291#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004292 Py_RETURN_NONE;
4293}
Larry Hastings9cf065c2012-06-22 16:30:09 -07004294
Larry Hastings2f936352014-08-05 14:04:04 +10004295
4296/*[clinic input]
4297os.rename
4298
4299 src : path_t
4300 dst : path_t
4301 *
4302 src_dir_fd : dir_fd = None
4303 dst_dir_fd : dir_fd = None
4304
4305Rename a file or directory.
4306
4307If either src_dir_fd or dst_dir_fd is not None, it should be a file
4308 descriptor open to a directory, and the respective path string (src or dst)
4309 should be relative; the path will then be relative to that directory.
4310src_dir_fd and dst_dir_fd, may not be implemented on your platform.
4311 If they are unavailable, using them will raise a NotImplementedError.
4312[clinic start generated code]*/
4313
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004314static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004315os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04004316 int dst_dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004317/*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004318{
Larry Hastings2f936352014-08-05 14:04:04 +10004319 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004320}
4321
Larry Hastings2f936352014-08-05 14:04:04 +10004322
4323/*[clinic input]
4324os.replace = os.rename
4325
4326Rename a file or directory, overwriting the destination.
4327
4328If either src_dir_fd or dst_dir_fd is not None, it should be a file
4329 descriptor open to a directory, and the respective path string (src or dst)
4330 should be relative; the path will then be relative to that directory.
4331src_dir_fd and dst_dir_fd, may not be implemented on your platform.
Anthony Sottile73d60022019-02-12 23:15:54 -05004332 If they are unavailable, using them will raise a NotImplementedError.
Larry Hastings2f936352014-08-05 14:04:04 +10004333[clinic start generated code]*/
4334
Larry Hastings2f936352014-08-05 14:04:04 +10004335static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004336os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
4337 int dst_dir_fd)
Anthony Sottile73d60022019-02-12 23:15:54 -05004338/*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004339{
4340 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
4341}
4342
4343
4344/*[clinic input]
4345os.rmdir
4346
4347 path: path_t
4348 *
4349 dir_fd: dir_fd(requires='unlinkat') = None
4350
4351Remove a directory.
4352
4353If dir_fd is not None, it should be a file descriptor open to a directory,
4354 and path should be relative; path will then be relative to that directory.
4355dir_fd may not be implemented on your platform.
4356 If it is unavailable, using it will raise a NotImplementedError.
4357[clinic start generated code]*/
4358
Larry Hastings2f936352014-08-05 14:04:04 +10004359static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004360os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
4361/*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004362{
4363 int result;
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004364
4365 Py_BEGIN_ALLOW_THREADS
4366#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004367 /* Windows, success=1, UNIX, success=0 */
4368 result = !RemoveDirectoryW(path->wide);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004369#else
4370#ifdef HAVE_UNLINKAT
4371 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004372 result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004373 else
4374#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004375 result = rmdir(path->narrow);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004376#endif
4377 Py_END_ALLOW_THREADS
4378
Larry Hastings2f936352014-08-05 14:04:04 +10004379 if (result)
4380 return path_error(path);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004381
Larry Hastings2f936352014-08-05 14:04:04 +10004382 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004383}
4384
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004385
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004386#ifdef HAVE_SYSTEM
Larry Hastings2f936352014-08-05 14:04:04 +10004387#ifdef MS_WINDOWS
4388/*[clinic input]
4389os.system -> long
4390
4391 command: Py_UNICODE
4392
4393Execute the command in a subshell.
4394[clinic start generated code]*/
4395
Larry Hastings2f936352014-08-05 14:04:04 +10004396static long
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02004397os_system_impl(PyObject *module, const Py_UNICODE *command)
4398/*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004399{
4400 long result;
Steve Dowerb82e17e2019-05-23 08:45:22 -07004401
Steve Dowerfbe3c762019-10-18 00:52:15 -07004402 if (PySys_Audit("os.system", "(u)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004403 return -1;
4404 }
4405
Victor Stinner8c62be82010-05-06 00:08:46 +00004406 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08004407 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10004408 result = _wsystem(command);
Steve Dowerc3630612016-11-19 18:41:16 -08004409 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00004410 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004411 return result;
4412}
4413#else /* MS_WINDOWS */
4414/*[clinic input]
4415os.system -> long
4416
4417 command: FSConverter
4418
4419Execute the command in a subshell.
4420[clinic start generated code]*/
4421
Larry Hastings2f936352014-08-05 14:04:04 +10004422static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004423os_system_impl(PyObject *module, PyObject *command)
4424/*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004425{
4426 long result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004427 const char *bytes = PyBytes_AsString(command);
Steve Dowerb82e17e2019-05-23 08:45:22 -07004428
Steve Dowerfbe3c762019-10-18 00:52:15 -07004429 if (PySys_Audit("os.system", "(O)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004430 return -1;
4431 }
4432
Larry Hastings2f936352014-08-05 14:04:04 +10004433 Py_BEGIN_ALLOW_THREADS
4434 result = system(bytes);
4435 Py_END_ALLOW_THREADS
4436 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004437}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004438#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004439#endif /* HAVE_SYSTEM */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004440
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004441
Larry Hastings2f936352014-08-05 14:04:04 +10004442/*[clinic input]
4443os.umask
4444
4445 mask: int
4446 /
4447
4448Set the current numeric umask and return the previous umask.
4449[clinic start generated code]*/
4450
Larry Hastings2f936352014-08-05 14:04:04 +10004451static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004452os_umask_impl(PyObject *module, int mask)
4453/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004454{
4455 int i = (int)umask(mask);
Victor Stinner8c62be82010-05-06 00:08:46 +00004456 if (i < 0)
4457 return posix_error();
4458 return PyLong_FromLong((long)i);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004459}
4460
Brian Curtind40e6f72010-07-08 21:39:08 +00004461#ifdef MS_WINDOWS
4462
4463/* override the default DeleteFileW behavior so that directory
4464symlinks can be removed with this function, the same as with
4465Unix symlinks */
4466BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
4467{
4468 WIN32_FILE_ATTRIBUTE_DATA info;
4469 WIN32_FIND_DATAW find_data;
4470 HANDLE find_data_handle;
4471 int is_directory = 0;
4472 int is_link = 0;
4473
4474 if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
4475 is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004476
Brian Curtind40e6f72010-07-08 21:39:08 +00004477 /* Get WIN32_FIND_DATA structure for the path to determine if
4478 it is a symlink */
4479 if(is_directory &&
4480 info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
4481 find_data_handle = FindFirstFileW(lpFileName, &find_data);
4482
4483 if(find_data_handle != INVALID_HANDLE_VALUE) {
Tim Golden0321cf22014-05-05 19:46:17 +01004484 /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
4485 IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
4486 is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
4487 find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
Brian Curtind40e6f72010-07-08 21:39:08 +00004488 FindClose(find_data_handle);
4489 }
4490 }
4491 }
4492
4493 if (is_directory && is_link)
4494 return RemoveDirectoryW(lpFileName);
4495
4496 return DeleteFileW(lpFileName);
4497}
4498#endif /* MS_WINDOWS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004499
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004500
Larry Hastings2f936352014-08-05 14:04:04 +10004501/*[clinic input]
4502os.unlink
4503
4504 path: path_t
4505 *
4506 dir_fd: dir_fd(requires='unlinkat')=None
4507
4508Remove a file (same as remove()).
4509
4510If dir_fd is not None, it should be a file descriptor open to a directory,
4511 and path should be relative; path will then be relative to that directory.
4512dir_fd may not be implemented on your platform.
4513 If it is unavailable, using it will raise a NotImplementedError.
4514
4515[clinic start generated code]*/
4516
Larry Hastings2f936352014-08-05 14:04:04 +10004517static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004518os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
4519/*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004520{
4521 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004522
4523 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04004524 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004525#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004526 /* Windows, success=1, UNIX, success=0 */
4527 result = !Py_DeleteFileW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004528#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004529#ifdef HAVE_UNLINKAT
4530 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004531 result = unlinkat(dir_fd, path->narrow, 0);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004532 else
4533#endif /* HAVE_UNLINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10004534 result = unlink(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004535#endif
Steve Dower8fc89802015-04-12 00:26:27 -04004536 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004537 Py_END_ALLOW_THREADS
4538
Larry Hastings2f936352014-08-05 14:04:04 +10004539 if (result)
4540 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004541
Larry Hastings2f936352014-08-05 14:04:04 +10004542 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004543}
4544
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004545
Larry Hastings2f936352014-08-05 14:04:04 +10004546/*[clinic input]
4547os.remove = os.unlink
4548
4549Remove a file (same as unlink()).
4550
4551If dir_fd is not None, it should be a file descriptor open to a directory,
4552 and path should be relative; path will then be relative to that directory.
4553dir_fd may not be implemented on your platform.
4554 If it is unavailable, using it will raise a NotImplementedError.
4555[clinic start generated code]*/
4556
Larry Hastings2f936352014-08-05 14:04:04 +10004557static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004558os_remove_impl(PyObject *module, path_t *path, int dir_fd)
4559/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004560{
4561 return os_unlink_impl(module, path, dir_fd);
4562}
4563
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004564
Larry Hastings605a62d2012-06-24 04:33:36 -07004565static PyStructSequence_Field uname_result_fields[] = {
4566 {"sysname", "operating system name"},
4567 {"nodename", "name of machine on network (implementation-defined)"},
4568 {"release", "operating system release"},
4569 {"version", "operating system version"},
4570 {"machine", "hardware identifier"},
4571 {NULL}
4572};
4573
4574PyDoc_STRVAR(uname_result__doc__,
4575"uname_result: Result from os.uname().\n\n\
4576This object may be accessed either as a tuple of\n\
4577 (sysname, nodename, release, version, machine),\n\
4578or via the attributes sysname, nodename, release, version, and machine.\n\
4579\n\
4580See os.uname for more information.");
4581
4582static PyStructSequence_Desc uname_result_desc = {
Eddie Elizondob3966632019-11-05 07:16:14 -08004583 MODNAME ".uname_result", /* name */
Larry Hastings605a62d2012-06-24 04:33:36 -07004584 uname_result__doc__, /* doc */
4585 uname_result_fields,
4586 5
4587};
4588
Larry Hastings605a62d2012-06-24 04:33:36 -07004589#ifdef HAVE_UNAME
Larry Hastings2f936352014-08-05 14:04:04 +10004590/*[clinic input]
4591os.uname
4592
4593Return an object identifying the current operating system.
4594
4595The object behaves like a named tuple with the following fields:
4596 (sysname, nodename, release, version, machine)
4597
4598[clinic start generated code]*/
4599
Larry Hastings2f936352014-08-05 14:04:04 +10004600static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004601os_uname_impl(PyObject *module)
4602/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004603{
Victor Stinner8c62be82010-05-06 00:08:46 +00004604 struct utsname u;
4605 int res;
Larry Hastings605a62d2012-06-24 04:33:36 -07004606 PyObject *value;
Neal Norwitze241ce82003-02-17 18:17:05 +00004607
Victor Stinner8c62be82010-05-06 00:08:46 +00004608 Py_BEGIN_ALLOW_THREADS
4609 res = uname(&u);
4610 Py_END_ALLOW_THREADS
4611 if (res < 0)
4612 return posix_error();
Larry Hastings605a62d2012-06-24 04:33:36 -07004613
Eddie Elizondob3966632019-11-05 07:16:14 -08004614 PyObject *UnameResultType = _posixstate(module)->UnameResultType;
4615 value = PyStructSequence_New((PyTypeObject *)UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07004616 if (value == NULL)
4617 return NULL;
4618
4619#define SET(i, field) \
4620 { \
Victor Stinnera534fc42013-06-03 22:07:27 +02004621 PyObject *o = PyUnicode_DecodeFSDefault(field); \
Larry Hastings605a62d2012-06-24 04:33:36 -07004622 if (!o) { \
4623 Py_DECREF(value); \
4624 return NULL; \
4625 } \
4626 PyStructSequence_SET_ITEM(value, i, o); \
4627 } \
4628
4629 SET(0, u.sysname);
4630 SET(1, u.nodename);
4631 SET(2, u.release);
4632 SET(3, u.version);
4633 SET(4, u.machine);
4634
4635#undef SET
4636
4637 return value;
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004638}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004639#endif /* HAVE_UNAME */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004640
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004641
Larry Hastings9cf065c2012-06-22 16:30:09 -07004642
4643typedef struct {
4644 int now;
4645 time_t atime_s;
4646 long atime_ns;
4647 time_t mtime_s;
4648 long mtime_ns;
4649} utime_t;
4650
4651/*
Victor Stinner484df002014-10-09 13:52:31 +02004652 * these macros assume that "ut" is a pointer to a utime_t
Larry Hastings9cf065c2012-06-22 16:30:09 -07004653 * they also intentionally leak the declaration of a pointer named "time"
4654 */
4655#define UTIME_TO_TIMESPEC \
4656 struct timespec ts[2]; \
4657 struct timespec *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004658 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004659 time = NULL; \
4660 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004661 ts[0].tv_sec = ut->atime_s; \
4662 ts[0].tv_nsec = ut->atime_ns; \
4663 ts[1].tv_sec = ut->mtime_s; \
4664 ts[1].tv_nsec = ut->mtime_ns; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004665 time = ts; \
4666 } \
4667
4668#define UTIME_TO_TIMEVAL \
4669 struct timeval tv[2]; \
4670 struct timeval *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004671 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004672 time = NULL; \
4673 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004674 tv[0].tv_sec = ut->atime_s; \
4675 tv[0].tv_usec = ut->atime_ns / 1000; \
4676 tv[1].tv_sec = ut->mtime_s; \
4677 tv[1].tv_usec = ut->mtime_ns / 1000; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004678 time = tv; \
4679 } \
4680
4681#define UTIME_TO_UTIMBUF \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004682 struct utimbuf u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004683 struct utimbuf *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004684 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004685 time = NULL; \
4686 else { \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004687 u.actime = ut->atime_s; \
4688 u.modtime = ut->mtime_s; \
4689 time = &u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004690 }
4691
4692#define UTIME_TO_TIME_T \
4693 time_t timet[2]; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004694 time_t *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004695 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004696 time = NULL; \
4697 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004698 timet[0] = ut->atime_s; \
4699 timet[1] = ut->mtime_s; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004700 time = timet; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004701 } \
4702
4703
Victor Stinner528a9ab2015-09-03 21:30:26 +02004704#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004705
4706static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004707utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004708{
4709#ifdef HAVE_UTIMENSAT
4710 int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
4711 UTIME_TO_TIMESPEC;
4712 return utimensat(dir_fd, path, time, flags);
4713#elif defined(HAVE_FUTIMESAT)
4714 UTIME_TO_TIMEVAL;
4715 /*
4716 * follow_symlinks will never be false here;
4717 * we only allow !follow_symlinks and dir_fd together
4718 * if we have utimensat()
4719 */
4720 assert(follow_symlinks);
4721 return futimesat(dir_fd, path, time);
4722#endif
4723}
4724
Larry Hastings2f936352014-08-05 14:04:04 +10004725 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
4726#else
4727 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings9cf065c2012-06-22 16:30:09 -07004728#endif
4729
Victor Stinner528a9ab2015-09-03 21:30:26 +02004730#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004731
4732static int
Victor Stinner484df002014-10-09 13:52:31 +02004733utime_fd(utime_t *ut, int fd)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004734{
4735#ifdef HAVE_FUTIMENS
4736 UTIME_TO_TIMESPEC;
4737 return futimens(fd, time);
4738#else
4739 UTIME_TO_TIMEVAL;
4740 return futimes(fd, time);
4741#endif
4742}
4743
Larry Hastings2f936352014-08-05 14:04:04 +10004744 #define PATH_UTIME_HAVE_FD 1
4745#else
4746 #define PATH_UTIME_HAVE_FD 0
Larry Hastings9cf065c2012-06-22 16:30:09 -07004747#endif
4748
Victor Stinner5ebae872015-09-22 01:29:33 +02004749#if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
4750# define UTIME_HAVE_NOFOLLOW_SYMLINKS
4751#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004752
Victor Stinner4552ced2015-09-21 22:37:15 +02004753#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004754
4755static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004756utime_nofollow_symlinks(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004757{
4758#ifdef HAVE_UTIMENSAT
4759 UTIME_TO_TIMESPEC;
4760 return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
4761#else
4762 UTIME_TO_TIMEVAL;
4763 return lutimes(path, time);
4764#endif
4765}
4766
4767#endif
4768
4769#ifndef MS_WINDOWS
4770
4771static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004772utime_default(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004773{
4774#ifdef HAVE_UTIMENSAT
4775 UTIME_TO_TIMESPEC;
4776 return utimensat(DEFAULT_DIR_FD, path, time, 0);
4777#elif defined(HAVE_UTIMES)
4778 UTIME_TO_TIMEVAL;
4779 return utimes(path, time);
4780#elif defined(HAVE_UTIME_H)
4781 UTIME_TO_UTIMBUF;
4782 return utime(path, time);
4783#else
4784 UTIME_TO_TIME_T;
4785 return utime(path, time);
4786#endif
4787}
4788
4789#endif
4790
Larry Hastings76ad59b2012-05-03 00:30:07 -07004791static int
4792split_py_long_to_s_and_ns(PyObject *py_long, time_t *s, long *ns)
4793{
4794 int result = 0;
Benjamin Petersonfbd85a02012-05-04 11:06:09 -04004795 PyObject *divmod;
Eddie Elizondob3966632019-11-05 07:16:14 -08004796 divmod = PyNumber_Divmod(py_long, _posixstate_global->billion);
Larry Hastings76ad59b2012-05-03 00:30:07 -07004797 if (!divmod)
4798 goto exit;
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004799 if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
4800 PyErr_Format(PyExc_TypeError,
4801 "%.200s.__divmod__() must return a 2-tuple, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -08004802 _PyType_Name(Py_TYPE(py_long)), _PyType_Name(Py_TYPE(divmod)));
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004803 goto exit;
4804 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004805 *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
4806 if ((*s == -1) && PyErr_Occurred())
4807 goto exit;
4808 *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
Benjamin Peterson35a8f0d2012-05-04 01:10:59 -04004809 if ((*ns == -1) && PyErr_Occurred())
Larry Hastings76ad59b2012-05-03 00:30:07 -07004810 goto exit;
4811
4812 result = 1;
4813exit:
4814 Py_XDECREF(divmod);
4815 return result;
4816}
4817
Larry Hastings2f936352014-08-05 14:04:04 +10004818
4819/*[clinic input]
4820os.utime
4821
4822 path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004823 times: object = None
Larry Hastings2f936352014-08-05 14:04:04 +10004824 *
4825 ns: object = NULL
4826 dir_fd: dir_fd(requires='futimensat') = None
4827 follow_symlinks: bool=True
4828
Martin Panter0ff89092015-09-09 01:56:53 +00004829# "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
Larry Hastings2f936352014-08-05 14:04:04 +10004830
4831Set the access and modified time of path.
4832
4833path may always be specified as a string.
4834On some platforms, path may also be specified as an open file descriptor.
4835 If this functionality is unavailable, using it raises an exception.
4836
4837If times is not None, it must be a tuple (atime, mtime);
4838 atime and mtime should be expressed as float seconds since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004839If ns is specified, it must be a tuple (atime_ns, mtime_ns);
Larry Hastings2f936352014-08-05 14:04:04 +10004840 atime_ns and mtime_ns should be expressed as integer nanoseconds
4841 since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004842If times is None and ns is unspecified, utime uses the current time.
Larry Hastings2f936352014-08-05 14:04:04 +10004843Specifying tuples for both times and ns is an error.
4844
4845If dir_fd is not None, it should be a file descriptor open to a directory,
4846 and path should be relative; path will then be relative to that directory.
4847If follow_symlinks is False, and the last element of the path is a symbolic
4848 link, utime will modify the symbolic link itself instead of the file the
4849 link points to.
4850It is an error to use dir_fd or follow_symlinks when specifying path
4851 as an open file descriptor.
4852dir_fd and follow_symlinks may not be available on your platform.
4853 If they are unavailable, using them will raise a NotImplementedError.
4854
4855[clinic start generated code]*/
4856
Larry Hastings2f936352014-08-05 14:04:04 +10004857static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004858os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
4859 int dir_fd, int follow_symlinks)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004860/*[clinic end generated code: output=cfcac69d027b82cf input=2fbd62a2f228f8f4]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004861{
Larry Hastings9cf065c2012-06-22 16:30:09 -07004862#ifdef MS_WINDOWS
4863 HANDLE hFile;
4864 FILETIME atime, mtime;
4865#else
4866 int result;
4867#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004868
Larry Hastings2f936352014-08-05 14:04:04 +10004869 utime_t utime;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004870
Christian Heimesb3c87242013-08-01 00:08:16 +02004871 memset(&utime, 0, sizeof(utime_t));
Larry Hastings76ad59b2012-05-03 00:30:07 -07004872
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004873 if (times != Py_None && ns) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004874 PyErr_SetString(PyExc_ValueError,
4875 "utime: you may specify either 'times'"
4876 " or 'ns' but not both");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004877 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004878 }
4879
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004880 if (times != Py_None) {
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004881 time_t a_sec, m_sec;
4882 long a_nsec, m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004883 if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004884 PyErr_SetString(PyExc_TypeError,
4885 "utime: 'times' must be either"
4886 " a tuple of two ints or None");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004887 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004888 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004889 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004890 if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004891 &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004892 _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004893 &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004894 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004895 }
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004896 utime.atime_s = a_sec;
4897 utime.atime_ns = a_nsec;
4898 utime.mtime_s = m_sec;
4899 utime.mtime_ns = m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004900 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004901 else if (ns) {
Larry Hastings76ad59b2012-05-03 00:30:07 -07004902 if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004903 PyErr_SetString(PyExc_TypeError,
4904 "utime: 'ns' must be a tuple of two ints");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004905 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004906 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004907 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004908 if (!split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 0),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004909 &utime.atime_s, &utime.atime_ns) ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004910 !split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 1),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004911 &utime.mtime_s, &utime.mtime_ns)) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004912 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004913 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004914 }
4915 else {
4916 /* times and ns are both None/unspecified. use "now". */
4917 utime.now = 1;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004918 }
4919
Victor Stinner4552ced2015-09-21 22:37:15 +02004920#if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004921 if (follow_symlinks_specified("utime", follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004922 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004923#endif
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004924
Larry Hastings2f936352014-08-05 14:04:04 +10004925 if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
4926 dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
4927 fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004928 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004929
Larry Hastings9cf065c2012-06-22 16:30:09 -07004930#if !defined(HAVE_UTIMENSAT)
4931 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
Georg Brandl969288e2012-06-26 09:25:44 +02004932 PyErr_SetString(PyExc_ValueError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07004933 "utime: cannot use dir_fd and follow_symlinks "
4934 "together on this platform");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004935 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004936 }
4937#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004938
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004939#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004940 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004941 hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
4942 NULL, OPEN_EXISTING,
4943 FILE_FLAG_BACKUP_SEMANTICS, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004944 Py_END_ALLOW_THREADS
4945 if (hFile == INVALID_HANDLE_VALUE) {
Larry Hastings2f936352014-08-05 14:04:04 +10004946 path_error(path);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004947 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004948 }
4949
Larry Hastings9cf065c2012-06-22 16:30:09 -07004950 if (utime.now) {
Antoine Pitrou91a7af32013-11-23 15:23:26 +01004951 GetSystemTimeAsFileTime(&mtime);
4952 atime = mtime;
Victor Stinner8c62be82010-05-06 00:08:46 +00004953 }
Victor Stinner8c62be82010-05-06 00:08:46 +00004954 else {
Steve Dowerbf1f3762015-02-21 15:26:02 -08004955 _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
4956 _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
Victor Stinner8c62be82010-05-06 00:08:46 +00004957 }
4958 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
4959 /* Avoid putting the file name into the error here,
4960 as that may confuse the user into believing that
4961 something is wrong with the file, when it also
4962 could be the time stamp that gives a problem. */
Victor Stinnerb024e842012-10-31 22:24:06 +01004963 PyErr_SetFromWindowsErr(0);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004964 CloseHandle(hFile);
4965 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004966 }
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004967 CloseHandle(hFile);
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004968#else /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07004969 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004970
Victor Stinner4552ced2015-09-21 22:37:15 +02004971#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004972 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10004973 result = utime_nofollow_symlinks(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004974 else
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004975#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004976
Victor Stinner528a9ab2015-09-03 21:30:26 +02004977#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004978 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10004979 result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004980 else
4981#endif
4982
Victor Stinner528a9ab2015-09-03 21:30:26 +02004983#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings2f936352014-08-05 14:04:04 +10004984 if (path->fd != -1)
4985 result = utime_fd(&utime, path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004986 else
4987#endif
4988
Larry Hastings2f936352014-08-05 14:04:04 +10004989 result = utime_default(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004990
4991 Py_END_ALLOW_THREADS
4992
4993 if (result < 0) {
4994 /* see previous comment about not putting filename in error here */
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004995 posix_error();
4996 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004997 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004998
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004999#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07005000
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005001 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005002}
5003
Guido van Rossum3b066191991-06-04 19:40:25 +00005004/* Process operations */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005005
Larry Hastings2f936352014-08-05 14:04:04 +10005006
5007/*[clinic input]
5008os._exit
5009
5010 status: int
5011
5012Exit to the system with specified status, without normal exit processing.
5013[clinic start generated code]*/
5014
Larry Hastings2f936352014-08-05 14:04:04 +10005015static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005016os__exit_impl(PyObject *module, int status)
5017/*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005018{
5019 _exit(status);
Victor Stinner8c62be82010-05-06 00:08:46 +00005020 return NULL; /* Make gcc -Wall happy */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005021}
5022
Steve Dowercc16be82016-09-08 10:35:16 -07005023#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5024#define EXECV_CHAR wchar_t
5025#else
5026#define EXECV_CHAR char
5027#endif
5028
pxinwrf2d7ac72019-05-21 18:46:37 +08005029#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005030static void
Steve Dowercc16be82016-09-08 10:35:16 -07005031free_string_array(EXECV_CHAR **array, Py_ssize_t count)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005032{
Victor Stinner8c62be82010-05-06 00:08:46 +00005033 Py_ssize_t i;
5034 for (i = 0; i < count; i++)
5035 PyMem_Free(array[i]);
5036 PyMem_DEL(array);
Martin v. Löwis114619e2002-10-07 06:44:21 +00005037}
Martin v. Löwis011e8422009-05-05 04:43:17 +00005038
Berker Peksag81816462016-09-15 20:19:47 +03005039static int
5040fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
Martin v. Löwis011e8422009-05-05 04:43:17 +00005041{
Victor Stinner8c62be82010-05-06 00:08:46 +00005042 Py_ssize_t size;
Berker Peksag81816462016-09-15 20:19:47 +03005043 PyObject *ub;
5044 int result = 0;
Steve Dowercc16be82016-09-08 10:35:16 -07005045#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
Berker Peksag81816462016-09-15 20:19:47 +03005046 if (!PyUnicode_FSDecoder(o, &ub))
Steve Dowercc16be82016-09-08 10:35:16 -07005047 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005048 *out = PyUnicode_AsWideCharString(ub, &size);
5049 if (*out)
5050 result = 1;
Steve Dowercc16be82016-09-08 10:35:16 -07005051#else
Berker Peksag81816462016-09-15 20:19:47 +03005052 if (!PyUnicode_FSConverter(o, &ub))
Victor Stinner8c62be82010-05-06 00:08:46 +00005053 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005054 size = PyBytes_GET_SIZE(ub);
5055 *out = PyMem_Malloc(size + 1);
5056 if (*out) {
5057 memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
5058 result = 1;
5059 } else
Victor Stinner50abf222013-11-07 23:56:10 +01005060 PyErr_NoMemory();
Steve Dowercc16be82016-09-08 10:35:16 -07005061#endif
Berker Peksag81816462016-09-15 20:19:47 +03005062 Py_DECREF(ub);
5063 return result;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005064}
Martin v. Löwis114619e2002-10-07 06:44:21 +00005065#endif
5066
pxinwrf2d7ac72019-05-21 18:46:37 +08005067#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
Steve Dowercc16be82016-09-08 10:35:16 -07005068static EXECV_CHAR**
Victor Stinner13bb71c2010-04-23 21:41:56 +00005069parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
5070{
Victor Stinner8c62be82010-05-06 00:08:46 +00005071 Py_ssize_t i, pos, envc;
5072 PyObject *keys=NULL, *vals=NULL;
Berker Peksag81816462016-09-15 20:19:47 +03005073 PyObject *key, *val, *key2, *val2, *keyval;
Steve Dowercc16be82016-09-08 10:35:16 -07005074 EXECV_CHAR **envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005075
Victor Stinner8c62be82010-05-06 00:08:46 +00005076 i = PyMapping_Size(env);
5077 if (i < 0)
5078 return NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07005079 envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005080 if (envlist == NULL) {
5081 PyErr_NoMemory();
5082 return NULL;
5083 }
5084 envc = 0;
5085 keys = PyMapping_Keys(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005086 if (!keys)
5087 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00005088 vals = PyMapping_Values(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005089 if (!vals)
Victor Stinner8c62be82010-05-06 00:08:46 +00005090 goto error;
5091 if (!PyList_Check(keys) || !PyList_Check(vals)) {
5092 PyErr_Format(PyExc_TypeError,
5093 "env.keys() or env.values() is not a list");
5094 goto error;
5095 }
Victor Stinner13bb71c2010-04-23 21:41:56 +00005096
Victor Stinner8c62be82010-05-06 00:08:46 +00005097 for (pos = 0; pos < i; pos++) {
5098 key = PyList_GetItem(keys, pos);
5099 val = PyList_GetItem(vals, pos);
5100 if (!key || !val)
5101 goto error;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005102
Berker Peksag81816462016-09-15 20:19:47 +03005103#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5104 if (!PyUnicode_FSDecoder(key, &key2))
5105 goto error;
5106 if (!PyUnicode_FSDecoder(val, &val2)) {
5107 Py_DECREF(key2);
5108 goto error;
5109 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005110 /* Search from index 1 because on Windows starting '=' is allowed for
5111 defining hidden environment variables. */
5112 if (PyUnicode_GET_LENGTH(key2) == 0 ||
5113 PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
5114 {
5115 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005116 Py_DECREF(key2);
5117 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005118 goto error;
5119 }
Berker Peksag81816462016-09-15 20:19:47 +03005120 keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
5121#else
5122 if (!PyUnicode_FSConverter(key, &key2))
5123 goto error;
5124 if (!PyUnicode_FSConverter(val, &val2)) {
5125 Py_DECREF(key2);
5126 goto error;
5127 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005128 if (PyBytes_GET_SIZE(key2) == 0 ||
5129 strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
5130 {
5131 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005132 Py_DECREF(key2);
5133 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005134 goto error;
5135 }
Berker Peksag81816462016-09-15 20:19:47 +03005136 keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
5137 PyBytes_AS_STRING(val2));
5138#endif
5139 Py_DECREF(key2);
5140 Py_DECREF(val2);
Steve Dowercc16be82016-09-08 10:35:16 -07005141 if (!keyval)
Victor Stinner8c62be82010-05-06 00:08:46 +00005142 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -07005143
5144 if (!fsconvert_strdup(keyval, &envlist[envc++])) {
5145 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005146 goto error;
5147 }
Berker Peksag81816462016-09-15 20:19:47 +03005148
Steve Dowercc16be82016-09-08 10:35:16 -07005149 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005150 }
5151 Py_DECREF(vals);
5152 Py_DECREF(keys);
Victor Stinner13bb71c2010-04-23 21:41:56 +00005153
Victor Stinner8c62be82010-05-06 00:08:46 +00005154 envlist[envc] = 0;
5155 *envc_ptr = envc;
5156 return envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005157
5158error:
Victor Stinner8c62be82010-05-06 00:08:46 +00005159 Py_XDECREF(keys);
5160 Py_XDECREF(vals);
Steve Dowercc16be82016-09-08 10:35:16 -07005161 free_string_array(envlist, envc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005162 return NULL;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005163}
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005164
Steve Dowercc16be82016-09-08 10:35:16 -07005165static EXECV_CHAR**
Ross Lagerwall7807c352011-03-17 20:20:30 +02005166parse_arglist(PyObject* argv, Py_ssize_t *argc)
5167{
5168 int i;
Steve Dowercc16be82016-09-08 10:35:16 -07005169 EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005170 if (argvlist == NULL) {
5171 PyErr_NoMemory();
5172 return NULL;
5173 }
5174 for (i = 0; i < *argc; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005175 PyObject* item = PySequence_ITEM(argv, i);
5176 if (item == NULL)
5177 goto fail;
5178 if (!fsconvert_strdup(item, &argvlist[i])) {
5179 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005180 goto fail;
5181 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005182 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005183 }
5184 argvlist[*argc] = NULL;
5185 return argvlist;
5186fail:
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005187 *argc = i;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005188 free_string_array(argvlist, *argc);
5189 return NULL;
5190}
Steve Dowercc16be82016-09-08 10:35:16 -07005191
Ross Lagerwall7807c352011-03-17 20:20:30 +02005192#endif
5193
Larry Hastings2f936352014-08-05 14:04:04 +10005194
Ross Lagerwall7807c352011-03-17 20:20:30 +02005195#ifdef HAVE_EXECV
Larry Hastings2f936352014-08-05 14:04:04 +10005196/*[clinic input]
5197os.execv
5198
Steve Dowercc16be82016-09-08 10:35:16 -07005199 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005200 Path of executable file.
5201 argv: object
5202 Tuple or list of strings.
5203 /
5204
5205Execute an executable path with arguments, replacing current process.
5206[clinic start generated code]*/
5207
Larry Hastings2f936352014-08-05 14:04:04 +10005208static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005209os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
5210/*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005211{
Steve Dowercc16be82016-09-08 10:35:16 -07005212 EXECV_CHAR **argvlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005213 Py_ssize_t argc;
5214
5215 /* execv has two arguments: (path, argv), where
5216 argv is a list or tuple of strings. */
5217
Ross Lagerwall7807c352011-03-17 20:20:30 +02005218 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
5219 PyErr_SetString(PyExc_TypeError,
5220 "execv() arg 2 must be a tuple or list");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005221 return NULL;
5222 }
5223 argc = PySequence_Size(argv);
5224 if (argc < 1) {
5225 PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005226 return NULL;
5227 }
5228
5229 argvlist = parse_arglist(argv, &argc);
5230 if (argvlist == NULL) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02005231 return NULL;
5232 }
Steve Dowerbce26262016-11-19 19:17:26 -08005233 if (!argvlist[0][0]) {
5234 PyErr_SetString(PyExc_ValueError,
5235 "execv() arg 2 first element cannot be empty");
5236 free_string_array(argvlist, argc);
5237 return NULL;
5238 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005239
Steve Dowerbce26262016-11-19 19:17:26 -08005240 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005241#ifdef HAVE_WEXECV
5242 _wexecv(path->wide, argvlist);
5243#else
5244 execv(path->narrow, argvlist);
5245#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005246 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005247
5248 /* If we get here it's definitely an error */
5249
5250 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005251 return posix_error();
5252}
5253
Larry Hastings2f936352014-08-05 14:04:04 +10005254
5255/*[clinic input]
5256os.execve
5257
5258 path: path_t(allow_fd='PATH_HAVE_FEXECVE')
5259 Path of executable file.
5260 argv: object
5261 Tuple or list of strings.
5262 env: object
5263 Dictionary of strings mapping to strings.
5264
5265Execute an executable path with arguments, replacing current process.
5266[clinic start generated code]*/
5267
Larry Hastings2f936352014-08-05 14:04:04 +10005268static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005269os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
5270/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005271{
Steve Dowercc16be82016-09-08 10:35:16 -07005272 EXECV_CHAR **argvlist = NULL;
5273 EXECV_CHAR **envlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005274 Py_ssize_t argc, envc;
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005275
Victor Stinner8c62be82010-05-06 00:08:46 +00005276 /* execve has three arguments: (path, argv, env), where
5277 argv is a list or tuple of strings and env is a dictionary
5278 like posix.environ. */
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005279
Ross Lagerwall7807c352011-03-17 20:20:30 +02005280 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005281 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005282 "execve: argv must be a tuple or list");
5283 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005284 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005285 argc = PySequence_Size(argv);
Steve Dowerbce26262016-11-19 19:17:26 -08005286 if (argc < 1) {
5287 PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
5288 return NULL;
5289 }
5290
Victor Stinner8c62be82010-05-06 00:08:46 +00005291 if (!PyMapping_Check(env)) {
5292 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005293 "execve: environment must be a mapping object");
5294 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005295 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005296
Ross Lagerwall7807c352011-03-17 20:20:30 +02005297 argvlist = parse_arglist(argv, &argc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005298 if (argvlist == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07005299 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005300 }
Steve Dowerbce26262016-11-19 19:17:26 -08005301 if (!argvlist[0][0]) {
5302 PyErr_SetString(PyExc_ValueError,
5303 "execve: argv first element cannot be empty");
5304 goto fail;
5305 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005306
Victor Stinner8c62be82010-05-06 00:08:46 +00005307 envlist = parse_envlist(env, &envc);
5308 if (envlist == NULL)
Ross Lagerwall7807c352011-03-17 20:20:30 +02005309 goto fail;
5310
Steve Dowerbce26262016-11-19 19:17:26 -08005311 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07005312#ifdef HAVE_FEXECVE
Larry Hastings2f936352014-08-05 14:04:04 +10005313 if (path->fd > -1)
5314 fexecve(path->fd, argvlist, envlist);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005315 else
5316#endif
Steve Dowercc16be82016-09-08 10:35:16 -07005317#ifdef HAVE_WEXECV
5318 _wexecve(path->wide, argvlist, envlist);
5319#else
Larry Hastings2f936352014-08-05 14:04:04 +10005320 execve(path->narrow, argvlist, envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07005321#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005322 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005323
5324 /* If we get here it's definitely an error */
5325
Alexey Izbyshev83460312018-10-20 03:28:22 +03005326 posix_path_error(path);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005327
Steve Dowercc16be82016-09-08 10:35:16 -07005328 free_string_array(envlist, envc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005329 fail:
Larry Hastings9cf065c2012-06-22 16:30:09 -07005330 if (argvlist)
5331 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005332 return NULL;
5333}
Steve Dowercc16be82016-09-08 10:35:16 -07005334
Larry Hastings9cf065c2012-06-22 16:30:09 -07005335#endif /* HAVE_EXECV */
5336
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005337#ifdef HAVE_POSIX_SPAWN
5338
5339enum posix_spawn_file_actions_identifier {
5340 POSIX_SPAWN_OPEN,
5341 POSIX_SPAWN_CLOSE,
5342 POSIX_SPAWN_DUP2
5343};
5344
William Orr81574b82018-10-01 22:19:56 -07005345#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005346static int
Pablo Galindo254a4662018-09-07 16:44:24 +01005347convert_sched_param(PyObject *param, struct sched_param *res);
William Orr81574b82018-10-01 22:19:56 -07005348#endif
Pablo Galindo254a4662018-09-07 16:44:24 +01005349
5350static int
Victor Stinner325e4ba2019-02-01 15:47:24 +01005351parse_posix_spawn_flags(const char *func_name, PyObject *setpgroup,
5352 int resetids, int setsid, PyObject *setsigmask,
Pablo Galindo254a4662018-09-07 16:44:24 +01005353 PyObject *setsigdef, PyObject *scheduler,
5354 posix_spawnattr_t *attrp)
5355{
5356 long all_flags = 0;
5357
5358 errno = posix_spawnattr_init(attrp);
5359 if (errno) {
5360 posix_error();
5361 return -1;
5362 }
5363
5364 if (setpgroup) {
5365 pid_t pgid = PyLong_AsPid(setpgroup);
5366 if (pgid == (pid_t)-1 && PyErr_Occurred()) {
5367 goto fail;
5368 }
5369 errno = posix_spawnattr_setpgroup(attrp, pgid);
5370 if (errno) {
5371 posix_error();
5372 goto fail;
5373 }
5374 all_flags |= POSIX_SPAWN_SETPGROUP;
5375 }
5376
5377 if (resetids) {
5378 all_flags |= POSIX_SPAWN_RESETIDS;
5379 }
5380
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005381 if (setsid) {
5382#ifdef POSIX_SPAWN_SETSID
5383 all_flags |= POSIX_SPAWN_SETSID;
5384#elif defined(POSIX_SPAWN_SETSID_NP)
5385 all_flags |= POSIX_SPAWN_SETSID_NP;
5386#else
5387 argument_unavailable_error(func_name, "setsid");
5388 return -1;
5389#endif
5390 }
5391
Pablo Galindo254a4662018-09-07 16:44:24 +01005392 if (setsigmask) {
5393 sigset_t set;
5394 if (!_Py_Sigset_Converter(setsigmask, &set)) {
5395 goto fail;
5396 }
5397 errno = posix_spawnattr_setsigmask(attrp, &set);
5398 if (errno) {
5399 posix_error();
5400 goto fail;
5401 }
5402 all_flags |= POSIX_SPAWN_SETSIGMASK;
5403 }
5404
5405 if (setsigdef) {
5406 sigset_t set;
5407 if (!_Py_Sigset_Converter(setsigdef, &set)) {
5408 goto fail;
5409 }
5410 errno = posix_spawnattr_setsigdefault(attrp, &set);
5411 if (errno) {
5412 posix_error();
5413 goto fail;
5414 }
5415 all_flags |= POSIX_SPAWN_SETSIGDEF;
5416 }
5417
5418 if (scheduler) {
5419#ifdef POSIX_SPAWN_SETSCHEDULER
5420 PyObject *py_schedpolicy;
5421 struct sched_param schedparam;
5422
5423 if (!PyArg_ParseTuple(scheduler, "OO&"
5424 ";A scheduler tuple must have two elements",
5425 &py_schedpolicy, convert_sched_param, &schedparam)) {
5426 goto fail;
5427 }
5428 if (py_schedpolicy != Py_None) {
5429 int schedpolicy = _PyLong_AsInt(py_schedpolicy);
5430
5431 if (schedpolicy == -1 && PyErr_Occurred()) {
5432 goto fail;
5433 }
5434 errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
5435 if (errno) {
5436 posix_error();
5437 goto fail;
5438 }
5439 all_flags |= POSIX_SPAWN_SETSCHEDULER;
5440 }
5441 errno = posix_spawnattr_setschedparam(attrp, &schedparam);
5442 if (errno) {
5443 posix_error();
5444 goto fail;
5445 }
5446 all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
5447#else
5448 PyErr_SetString(PyExc_NotImplementedError,
5449 "The scheduler option is not supported in this system.");
5450 goto fail;
5451#endif
5452 }
5453
5454 errno = posix_spawnattr_setflags(attrp, all_flags);
5455 if (errno) {
5456 posix_error();
5457 goto fail;
5458 }
5459
5460 return 0;
5461
5462fail:
5463 (void)posix_spawnattr_destroy(attrp);
5464 return -1;
5465}
5466
5467static int
Serhiy Storchakaef347532018-05-01 16:45:04 +03005468parse_file_actions(PyObject *file_actions,
Pablo Galindocb970732018-06-19 09:19:50 +01005469 posix_spawn_file_actions_t *file_actionsp,
5470 PyObject *temp_buffer)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005471{
5472 PyObject *seq;
5473 PyObject *file_action = NULL;
5474 PyObject *tag_obj;
5475
5476 seq = PySequence_Fast(file_actions,
5477 "file_actions must be a sequence or None");
5478 if (seq == NULL) {
5479 return -1;
5480 }
5481
5482 errno = posix_spawn_file_actions_init(file_actionsp);
5483 if (errno) {
5484 posix_error();
5485 Py_DECREF(seq);
5486 return -1;
5487 }
5488
Zackery Spytzd52a83a2019-06-26 14:54:20 -06005489 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
Serhiy Storchakaef347532018-05-01 16:45:04 +03005490 file_action = PySequence_Fast_GET_ITEM(seq, i);
5491 Py_INCREF(file_action);
5492 if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
5493 PyErr_SetString(PyExc_TypeError,
5494 "Each file_actions element must be a non-empty tuple");
5495 goto fail;
5496 }
5497 long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
5498 if (tag == -1 && PyErr_Occurred()) {
5499 goto fail;
5500 }
5501
5502 /* Populate the file_actions object */
5503 switch (tag) {
5504 case POSIX_SPAWN_OPEN: {
5505 int fd, oflag;
5506 PyObject *path;
5507 unsigned long mode;
5508 if (!PyArg_ParseTuple(file_action, "OiO&ik"
5509 ";A open file_action tuple must have 5 elements",
5510 &tag_obj, &fd, PyUnicode_FSConverter, &path,
5511 &oflag, &mode))
5512 {
5513 goto fail;
5514 }
Pablo Galindocb970732018-06-19 09:19:50 +01005515 if (PyList_Append(temp_buffer, path)) {
5516 Py_DECREF(path);
5517 goto fail;
5518 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005519 errno = posix_spawn_file_actions_addopen(file_actionsp,
5520 fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
Pablo Galindocb970732018-06-19 09:19:50 +01005521 Py_DECREF(path);
Serhiy Storchakaef347532018-05-01 16:45:04 +03005522 if (errno) {
5523 posix_error();
5524 goto fail;
5525 }
5526 break;
5527 }
5528 case POSIX_SPAWN_CLOSE: {
5529 int fd;
5530 if (!PyArg_ParseTuple(file_action, "Oi"
5531 ";A close file_action tuple must have 2 elements",
5532 &tag_obj, &fd))
5533 {
5534 goto fail;
5535 }
5536 errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
5537 if (errno) {
5538 posix_error();
5539 goto fail;
5540 }
5541 break;
5542 }
5543 case POSIX_SPAWN_DUP2: {
5544 int fd1, fd2;
5545 if (!PyArg_ParseTuple(file_action, "Oii"
5546 ";A dup2 file_action tuple must have 3 elements",
5547 &tag_obj, &fd1, &fd2))
5548 {
5549 goto fail;
5550 }
5551 errno = posix_spawn_file_actions_adddup2(file_actionsp,
5552 fd1, fd2);
5553 if (errno) {
5554 posix_error();
5555 goto fail;
5556 }
5557 break;
5558 }
5559 default: {
5560 PyErr_SetString(PyExc_TypeError,
5561 "Unknown file_actions identifier");
5562 goto fail;
5563 }
5564 }
5565 Py_DECREF(file_action);
5566 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005567
Serhiy Storchakaef347532018-05-01 16:45:04 +03005568 Py_DECREF(seq);
5569 return 0;
5570
5571fail:
5572 Py_DECREF(seq);
5573 Py_DECREF(file_action);
5574 (void)posix_spawn_file_actions_destroy(file_actionsp);
5575 return -1;
5576}
5577
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005578
5579static PyObject *
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005580py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
5581 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005582 PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005583 PyObject *setsigdef, PyObject *scheduler)
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005584{
Victor Stinner325e4ba2019-02-01 15:47:24 +01005585 const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005586 EXECV_CHAR **argvlist = NULL;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005587 EXECV_CHAR **envlist = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005588 posix_spawn_file_actions_t file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005589 posix_spawn_file_actions_t *file_actionsp = NULL;
Pablo Galindo254a4662018-09-07 16:44:24 +01005590 posix_spawnattr_t attr;
5591 posix_spawnattr_t *attrp = NULL;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005592 Py_ssize_t argc, envc;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005593 PyObject *result = NULL;
Pablo Galindocb970732018-06-19 09:19:50 +01005594 PyObject *temp_buffer = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005595 pid_t pid;
5596 int err_code;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005597
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005598 /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
Serhiy Storchakaef347532018-05-01 16:45:04 +03005599 argv is a list or tuple of strings and env is a dictionary
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005600 like posix.environ. */
5601
Serhiy Storchakaef347532018-05-01 16:45:04 +03005602 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005603 PyErr_Format(PyExc_TypeError,
5604 "%s: argv must be a tuple or list", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005605 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005606 }
5607 argc = PySequence_Size(argv);
5608 if (argc < 1) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005609 PyErr_Format(PyExc_ValueError,
5610 "%s: argv must not be empty", func_name);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005611 return NULL;
5612 }
5613
5614 if (!PyMapping_Check(env)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005615 PyErr_Format(PyExc_TypeError,
5616 "%s: environment must be a mapping object", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005617 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005618 }
5619
5620 argvlist = parse_arglist(argv, &argc);
5621 if (argvlist == NULL) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005622 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005623 }
5624 if (!argvlist[0][0]) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005625 PyErr_Format(PyExc_ValueError,
5626 "%s: argv first element cannot be empty", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005627 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005628 }
5629
5630 envlist = parse_envlist(env, &envc);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005631 if (envlist == NULL) {
5632 goto exit;
5633 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005634
Anthony Shaw948ed8c2019-05-10 12:00:06 +10005635 if (file_actions != NULL && file_actions != Py_None) {
Pablo Galindocb970732018-06-19 09:19:50 +01005636 /* There is a bug in old versions of glibc that makes some of the
5637 * helper functions for manipulating file actions not copy the provided
5638 * buffers. The problem is that posix_spawn_file_actions_addopen does not
5639 * copy the value of path for some old versions of glibc (<2.20).
5640 * The use of temp_buffer here is a workaround that keeps the
5641 * python objects that own the buffers alive until posix_spawn gets called.
5642 * Check https://bugs.python.org/issue33630 and
5643 * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
5644 temp_buffer = PyList_New(0);
5645 if (!temp_buffer) {
5646 goto exit;
5647 }
5648 if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005649 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005650 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005651 file_actionsp = &file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005652 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005653
Victor Stinner325e4ba2019-02-01 15:47:24 +01005654 if (parse_posix_spawn_flags(func_name, setpgroup, resetids, setsid,
5655 setsigmask, setsigdef, scheduler, &attr)) {
Pablo Galindo254a4662018-09-07 16:44:24 +01005656 goto exit;
5657 }
5658 attrp = &attr;
5659
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005660 _Py_BEGIN_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005661#ifdef HAVE_POSIX_SPAWNP
5662 if (use_posix_spawnp) {
5663 err_code = posix_spawnp(&pid, path->narrow,
5664 file_actionsp, attrp, argvlist, envlist);
5665 }
5666 else
5667#endif /* HAVE_POSIX_SPAWNP */
5668 {
5669 err_code = posix_spawn(&pid, path->narrow,
5670 file_actionsp, attrp, argvlist, envlist);
5671 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005672 _Py_END_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005673
Serhiy Storchakaef347532018-05-01 16:45:04 +03005674 if (err_code) {
5675 errno = err_code;
5676 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005677 goto exit;
5678 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08005679#ifdef _Py_MEMORY_SANITIZER
5680 __msan_unpoison(&pid, sizeof(pid));
5681#endif
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005682 result = PyLong_FromPid(pid);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005683
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005684exit:
Serhiy Storchakaef347532018-05-01 16:45:04 +03005685 if (file_actionsp) {
5686 (void)posix_spawn_file_actions_destroy(file_actionsp);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005687 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005688 if (attrp) {
5689 (void)posix_spawnattr_destroy(attrp);
5690 }
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005691 if (envlist) {
5692 free_string_array(envlist, envc);
5693 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005694 if (argvlist) {
5695 free_string_array(argvlist, argc);
5696 }
Pablo Galindocb970732018-06-19 09:19:50 +01005697 Py_XDECREF(temp_buffer);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005698 return result;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005699}
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005700
5701
5702/*[clinic input]
5703
5704os.posix_spawn
5705 path: path_t
5706 Path of executable file.
5707 argv: object
5708 Tuple or list of strings.
5709 env: object
5710 Dictionary of strings mapping to strings.
5711 /
5712 *
5713 file_actions: object(c_default='NULL') = ()
5714 A sequence of file action tuples.
5715 setpgroup: object = NULL
5716 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5717 resetids: bool(accept={int}) = False
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005718 If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
5719 setsid: bool(accept={int}) = False
5720 If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005721 setsigmask: object(c_default='NULL') = ()
5722 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5723 setsigdef: object(c_default='NULL') = ()
5724 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5725 scheduler: object = NULL
5726 A tuple with the scheduler policy (optional) and parameters.
5727
5728Execute the program specified by path in a new process.
5729[clinic start generated code]*/
5730
5731static PyObject *
5732os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
5733 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005734 PyObject *setpgroup, int resetids, int setsid,
5735 PyObject *setsigmask, PyObject *setsigdef,
5736 PyObject *scheduler)
5737/*[clinic end generated code: output=14a1098c566bc675 input=8c6305619a00ad04]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005738{
5739 return py_posix_spawn(0, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005740 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005741 scheduler);
5742}
5743 #endif /* HAVE_POSIX_SPAWN */
5744
5745
5746
5747#ifdef HAVE_POSIX_SPAWNP
5748/*[clinic input]
5749
5750os.posix_spawnp
5751 path: path_t
5752 Path of executable file.
5753 argv: object
5754 Tuple or list of strings.
5755 env: object
5756 Dictionary of strings mapping to strings.
5757 /
5758 *
5759 file_actions: object(c_default='NULL') = ()
5760 A sequence of file action tuples.
5761 setpgroup: object = NULL
5762 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5763 resetids: bool(accept={int}) = False
5764 If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005765 setsid: bool(accept={int}) = False
5766 If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005767 setsigmask: object(c_default='NULL') = ()
5768 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5769 setsigdef: object(c_default='NULL') = ()
5770 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5771 scheduler: object = NULL
5772 A tuple with the scheduler policy (optional) and parameters.
5773
5774Execute the program specified by path in a new process.
5775[clinic start generated code]*/
5776
5777static PyObject *
5778os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
5779 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005780 PyObject *setpgroup, int resetids, int setsid,
5781 PyObject *setsigmask, PyObject *setsigdef,
5782 PyObject *scheduler)
5783/*[clinic end generated code: output=7b9aaefe3031238d input=c1911043a22028da]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005784{
5785 return py_posix_spawn(1, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005786 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005787 scheduler);
5788}
5789#endif /* HAVE_POSIX_SPAWNP */
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005790
pxinwrf2d7ac72019-05-21 18:46:37 +08005791#ifdef HAVE_RTPSPAWN
5792static intptr_t
5793_rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
5794 const char *envp[])
5795{
5796 RTP_ID rtpid;
5797 int status;
5798 pid_t res;
5799 int async_err = 0;
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005800
pxinwrf2d7ac72019-05-21 18:46:37 +08005801 /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
5802 uStackSize=0 cannot be used, the default stack size is too small for
5803 Python. */
5804 if (envp) {
5805 rtpid = rtpSpawn(rtpFileName, argv, envp,
5806 100, 0x1000000, 0, VX_FP_TASK);
5807 }
5808 else {
5809 rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
5810 100, 0x1000000, 0, VX_FP_TASK);
5811 }
5812 if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
5813 do {
5814 res = waitpid((pid_t)rtpid, &status, 0);
5815 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
5816
5817 if (res < 0)
5818 return RTP_ID_ERROR;
5819 return ((intptr_t)status);
5820 }
5821 return ((intptr_t)rtpid);
5822}
5823#endif
5824
5825#if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
Larry Hastings2f936352014-08-05 14:04:04 +10005826/*[clinic input]
5827os.spawnv
5828
5829 mode: int
5830 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005831 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005832 Path of executable file.
5833 argv: object
5834 Tuple or list of strings.
5835 /
5836
5837Execute the program specified by path in a new process.
5838[clinic start generated code]*/
5839
Larry Hastings2f936352014-08-05 14:04:04 +10005840static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005841os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
5842/*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005843{
Steve Dowercc16be82016-09-08 10:35:16 -07005844 EXECV_CHAR **argvlist;
Larry Hastings2f936352014-08-05 14:04:04 +10005845 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00005846 Py_ssize_t argc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005847 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005848 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Guido van Rossuma1065681999-01-25 23:20:23 +00005849
Victor Stinner8c62be82010-05-06 00:08:46 +00005850 /* spawnv has three arguments: (mode, path, argv), where
5851 argv is a list or tuple of strings. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005852
Victor Stinner8c62be82010-05-06 00:08:46 +00005853 if (PyList_Check(argv)) {
5854 argc = PyList_Size(argv);
5855 getitem = PyList_GetItem;
5856 }
5857 else if (PyTuple_Check(argv)) {
5858 argc = PyTuple_Size(argv);
5859 getitem = PyTuple_GetItem;
5860 }
5861 else {
5862 PyErr_SetString(PyExc_TypeError,
5863 "spawnv() arg 2 must be a tuple or list");
Victor Stinner8c62be82010-05-06 00:08:46 +00005864 return NULL;
5865 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005866 if (argc == 0) {
5867 PyErr_SetString(PyExc_ValueError,
5868 "spawnv() arg 2 cannot be empty");
5869 return NULL;
5870 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005871
Steve Dowercc16be82016-09-08 10:35:16 -07005872 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005873 if (argvlist == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005874 return PyErr_NoMemory();
5875 }
5876 for (i = 0; i < argc; i++) {
5877 if (!fsconvert_strdup((*getitem)(argv, i),
5878 &argvlist[i])) {
5879 free_string_array(argvlist, i);
5880 PyErr_SetString(
5881 PyExc_TypeError,
5882 "spawnv() arg 2 must contain only strings");
Victor Stinner8c62be82010-05-06 00:08:46 +00005883 return NULL;
5884 }
Steve Dower93ff8722016-11-19 19:03:54 -08005885 if (i == 0 && !argvlist[0][0]) {
Victor Stinner8acb4cf2017-06-15 15:30:40 +02005886 free_string_array(argvlist, i + 1);
Steve Dower93ff8722016-11-19 19:03:54 -08005887 PyErr_SetString(
5888 PyExc_ValueError,
5889 "spawnv() arg 2 first element cannot be empty");
5890 return NULL;
5891 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005892 }
5893 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005894
pxinwrf2d7ac72019-05-21 18:46:37 +08005895#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00005896 if (mode == _OLD_P_OVERLAY)
5897 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08005898#endif
Tim Peters5aa91602002-01-30 05:46:57 +00005899
Victor Stinner8c62be82010-05-06 00:08:46 +00005900 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07005901 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005902#ifdef HAVE_WSPAWNV
5903 spawnval = _wspawnv(mode, path->wide, argvlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08005904#elif defined(HAVE_RTPSPAWN)
5905 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
Steve Dowercc16be82016-09-08 10:35:16 -07005906#else
5907 spawnval = _spawnv(mode, path->narrow, argvlist);
5908#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07005909 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00005910 Py_END_ALLOW_THREADS
Tim Peters5aa91602002-01-30 05:46:57 +00005911
Victor Stinner8c62be82010-05-06 00:08:46 +00005912 free_string_array(argvlist, argc);
Guido van Rossuma1065681999-01-25 23:20:23 +00005913
Victor Stinner8c62be82010-05-06 00:08:46 +00005914 if (spawnval == -1)
5915 return posix_error();
5916 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01005917 return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00005918}
5919
Larry Hastings2f936352014-08-05 14:04:04 +10005920/*[clinic input]
5921os.spawnve
5922
5923 mode: int
5924 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005925 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005926 Path of executable file.
5927 argv: object
5928 Tuple or list of strings.
5929 env: object
5930 Dictionary of strings mapping to strings.
5931 /
5932
5933Execute the program specified by path in a new process.
5934[clinic start generated code]*/
5935
Larry Hastings2f936352014-08-05 14:04:04 +10005936static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005937os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005938 PyObject *env)
Steve Dowercc16be82016-09-08 10:35:16 -07005939/*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005940{
Steve Dowercc16be82016-09-08 10:35:16 -07005941 EXECV_CHAR **argvlist;
5942 EXECV_CHAR **envlist;
Victor Stinner8c62be82010-05-06 00:08:46 +00005943 PyObject *res = NULL;
Antoine Pitrou22e41552010-08-15 18:07:50 +00005944 Py_ssize_t argc, i, envc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005945 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005946 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005947 Py_ssize_t lastarg = 0;
Guido van Rossuma1065681999-01-25 23:20:23 +00005948
Victor Stinner8c62be82010-05-06 00:08:46 +00005949 /* spawnve has four arguments: (mode, path, argv, env), where
5950 argv is a list or tuple of strings and env is a dictionary
5951 like posix.environ. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005952
Victor Stinner8c62be82010-05-06 00:08:46 +00005953 if (PyList_Check(argv)) {
5954 argc = PyList_Size(argv);
5955 getitem = PyList_GetItem;
5956 }
5957 else if (PyTuple_Check(argv)) {
5958 argc = PyTuple_Size(argv);
5959 getitem = PyTuple_GetItem;
5960 }
5961 else {
5962 PyErr_SetString(PyExc_TypeError,
5963 "spawnve() arg 2 must be a tuple or list");
5964 goto fail_0;
5965 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005966 if (argc == 0) {
5967 PyErr_SetString(PyExc_ValueError,
5968 "spawnve() arg 2 cannot be empty");
5969 goto fail_0;
5970 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005971 if (!PyMapping_Check(env)) {
5972 PyErr_SetString(PyExc_TypeError,
5973 "spawnve() arg 3 must be a mapping object");
5974 goto fail_0;
5975 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005976
Steve Dowercc16be82016-09-08 10:35:16 -07005977 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005978 if (argvlist == NULL) {
5979 PyErr_NoMemory();
5980 goto fail_0;
5981 }
5982 for (i = 0; i < argc; i++) {
5983 if (!fsconvert_strdup((*getitem)(argv, i),
5984 &argvlist[i]))
5985 {
5986 lastarg = i;
5987 goto fail_1;
5988 }
Steve Dowerbce26262016-11-19 19:17:26 -08005989 if (i == 0 && !argvlist[0][0]) {
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005990 lastarg = i + 1;
Steve Dowerbce26262016-11-19 19:17:26 -08005991 PyErr_SetString(
5992 PyExc_ValueError,
5993 "spawnv() arg 2 first element cannot be empty");
5994 goto fail_1;
5995 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005996 }
5997 lastarg = argc;
5998 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005999
Victor Stinner8c62be82010-05-06 00:08:46 +00006000 envlist = parse_envlist(env, &envc);
6001 if (envlist == NULL)
6002 goto fail_1;
Guido van Rossuma1065681999-01-25 23:20:23 +00006003
pxinwrf2d7ac72019-05-21 18:46:37 +08006004#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00006005 if (mode == _OLD_P_OVERLAY)
6006 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08006007#endif
Tim Peters25059d32001-12-07 20:35:43 +00006008
Victor Stinner8c62be82010-05-06 00:08:46 +00006009 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07006010 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07006011#ifdef HAVE_WSPAWNV
6012 spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08006013#elif defined(HAVE_RTPSPAWN)
6014 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
6015 (const char **)envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07006016#else
6017 spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
6018#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07006019 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00006020 Py_END_ALLOW_THREADS
Tim Peters25059d32001-12-07 20:35:43 +00006021
Victor Stinner8c62be82010-05-06 00:08:46 +00006022 if (spawnval == -1)
6023 (void) posix_error();
6024 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01006025 res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00006026
Victor Stinner8c62be82010-05-06 00:08:46 +00006027 while (--envc >= 0)
6028 PyMem_DEL(envlist[envc]);
6029 PyMem_DEL(envlist);
Guido van Rossum0847c5c2002-12-13 18:36:22 +00006030 fail_1:
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006031 free_string_array(argvlist, lastarg);
Martin v. Löwis114619e2002-10-07 06:44:21 +00006032 fail_0:
Victor Stinner8c62be82010-05-06 00:08:46 +00006033 return res;
Guido van Rossuma1065681999-01-25 23:20:23 +00006034}
Andrew MacIntyre69e18c92004-04-04 07:11:43 +00006035
Guido van Rossuma1065681999-01-25 23:20:23 +00006036#endif /* HAVE_SPAWNV */
6037
6038
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006039#ifdef HAVE_FORK
Gregory P. Smith163468a2017-05-29 10:03:41 -07006040
6041/* Helper function to validate arguments.
6042 Returns 0 on success. non-zero on failure with a TypeError raised.
6043 If obj is non-NULL it must be callable. */
6044static int
6045check_null_or_callable(PyObject *obj, const char* obj_name)
6046{
6047 if (obj && !PyCallable_Check(obj)) {
6048 PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
Eddie Elizondob3966632019-11-05 07:16:14 -08006049 obj_name, _PyType_Name(Py_TYPE(obj)));
Gregory P. Smith163468a2017-05-29 10:03:41 -07006050 return -1;
6051 }
6052 return 0;
6053}
6054
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006055/*[clinic input]
6056os.register_at_fork
6057
Gregory P. Smith163468a2017-05-29 10:03:41 -07006058 *
6059 before: object=NULL
6060 A callable to be called in the parent before the fork() syscall.
6061 after_in_child: object=NULL
6062 A callable to be called in the child after fork().
6063 after_in_parent: object=NULL
6064 A callable to be called in the parent after fork().
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006065
Gregory P. Smith163468a2017-05-29 10:03:41 -07006066Register callables to be called when forking a new process.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006067
Gregory P. Smith163468a2017-05-29 10:03:41 -07006068'before' callbacks are called in reverse order.
6069'after_in_child' and 'after_in_parent' callbacks are called in order.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006070
6071[clinic start generated code]*/
6072
6073static PyObject *
Gregory P. Smith163468a2017-05-29 10:03:41 -07006074os_register_at_fork_impl(PyObject *module, PyObject *before,
6075 PyObject *after_in_child, PyObject *after_in_parent)
6076/*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006077{
6078 PyInterpreterState *interp;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006079
Gregory P. Smith163468a2017-05-29 10:03:41 -07006080 if (!before && !after_in_child && !after_in_parent) {
6081 PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
6082 return NULL;
6083 }
6084 if (check_null_or_callable(before, "before") ||
6085 check_null_or_callable(after_in_child, "after_in_child") ||
6086 check_null_or_callable(after_in_parent, "after_in_parent")) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006087 return NULL;
6088 }
Victor Stinnercaba55b2018-08-03 15:33:52 +02006089 interp = _PyInterpreterState_Get();
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006090
Gregory P. Smith163468a2017-05-29 10:03:41 -07006091 if (register_at_forker(&interp->before_forkers, before)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006092 return NULL;
6093 }
Gregory P. Smith163468a2017-05-29 10:03:41 -07006094 if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006095 return NULL;
Gregory P. Smith163468a2017-05-29 10:03:41 -07006096 }
6097 if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
6098 return NULL;
6099 }
6100 Py_RETURN_NONE;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006101}
6102#endif /* HAVE_FORK */
6103
6104
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006105#ifdef HAVE_FORK1
Larry Hastings2f936352014-08-05 14:04:04 +10006106/*[clinic input]
6107os.fork1
6108
6109Fork a child process with a single multiplexed (i.e., not bound) thread.
6110
6111Return 0 to child process and PID of child to parent process.
6112[clinic start generated code]*/
6113
Larry Hastings2f936352014-08-05 14:04:04 +10006114static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006115os_fork1_impl(PyObject *module)
6116/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006117{
Victor Stinner8c62be82010-05-06 00:08:46 +00006118 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006119
Eric Snow59032962018-09-14 14:17:20 -07006120 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6121 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6122 return NULL;
6123 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006124 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006125 pid = fork1();
6126 if (pid == 0) {
6127 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006128 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006129 } else {
6130 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006131 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006132 }
6133 if (pid == -1)
6134 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006135 return PyLong_FromPid(pid);
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006136}
Larry Hastings2f936352014-08-05 14:04:04 +10006137#endif /* HAVE_FORK1 */
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006138
6139
Guido van Rossumad0ee831995-03-01 10:34:45 +00006140#ifdef HAVE_FORK
Larry Hastings2f936352014-08-05 14:04:04 +10006141/*[clinic input]
6142os.fork
6143
6144Fork a child process.
6145
6146Return 0 to child process and PID of child to parent process.
6147[clinic start generated code]*/
6148
Larry Hastings2f936352014-08-05 14:04:04 +10006149static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006150os_fork_impl(PyObject *module)
6151/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006152{
Victor Stinner8c62be82010-05-06 00:08:46 +00006153 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006154
Eric Snow59032962018-09-14 14:17:20 -07006155 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6156 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6157 return NULL;
6158 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006159 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006160 pid = fork();
6161 if (pid == 0) {
6162 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006163 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006164 } else {
6165 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006166 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006167 }
6168 if (pid == -1)
6169 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006170 return PyLong_FromPid(pid);
Guido van Rossum85e3b011991-06-03 12:42:10 +00006171}
Larry Hastings2f936352014-08-05 14:04:04 +10006172#endif /* HAVE_FORK */
6173
Guido van Rossum85e3b011991-06-03 12:42:10 +00006174
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006175#ifdef HAVE_SCHED_H
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006176#ifdef HAVE_SCHED_GET_PRIORITY_MAX
Larry Hastings2f936352014-08-05 14:04:04 +10006177/*[clinic input]
6178os.sched_get_priority_max
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006179
Larry Hastings2f936352014-08-05 14:04:04 +10006180 policy: int
6181
6182Get the maximum scheduling priority for policy.
6183[clinic start generated code]*/
6184
Larry Hastings2f936352014-08-05 14:04:04 +10006185static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006186os_sched_get_priority_max_impl(PyObject *module, int policy)
6187/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006188{
6189 int max;
6190
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006191 max = sched_get_priority_max(policy);
6192 if (max < 0)
6193 return posix_error();
6194 return PyLong_FromLong(max);
6195}
6196
Larry Hastings2f936352014-08-05 14:04:04 +10006197
6198/*[clinic input]
6199os.sched_get_priority_min
6200
6201 policy: int
6202
6203Get the minimum scheduling priority for policy.
6204[clinic start generated code]*/
6205
Larry Hastings2f936352014-08-05 14:04:04 +10006206static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006207os_sched_get_priority_min_impl(PyObject *module, int policy)
6208/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006209{
6210 int min = sched_get_priority_min(policy);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006211 if (min < 0)
6212 return posix_error();
6213 return PyLong_FromLong(min);
6214}
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006215#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
6216
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006217
Larry Hastings2f936352014-08-05 14:04:04 +10006218#ifdef HAVE_SCHED_SETSCHEDULER
6219/*[clinic input]
6220os.sched_getscheduler
6221 pid: pid_t
6222 /
6223
Min ho Kimc4cacc82019-07-31 08:16:13 +10006224Get the scheduling policy for the process identified by pid.
Larry Hastings2f936352014-08-05 14:04:04 +10006225
6226Passing 0 for pid returns the scheduling policy for the calling process.
6227[clinic start generated code]*/
6228
Larry Hastings2f936352014-08-05 14:04:04 +10006229static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006230os_sched_getscheduler_impl(PyObject *module, pid_t pid)
Min ho Kimc4cacc82019-07-31 08:16:13 +10006231/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=8d99dac505485ac8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006232{
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006233 int policy;
6234
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006235 policy = sched_getscheduler(pid);
6236 if (policy < 0)
6237 return posix_error();
6238 return PyLong_FromLong(policy);
6239}
Larry Hastings2f936352014-08-05 14:04:04 +10006240#endif /* HAVE_SCHED_SETSCHEDULER */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006241
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006242
William Orr81574b82018-10-01 22:19:56 -07006243#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Larry Hastings2f936352014-08-05 14:04:04 +10006244/*[clinic input]
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006245class os.sched_param "PyObject *" "SchedParamType"
Larry Hastings2f936352014-08-05 14:04:04 +10006246
6247@classmethod
6248os.sched_param.__new__
6249
6250 sched_priority: object
6251 A scheduling parameter.
6252
Eddie Elizondob3966632019-11-05 07:16:14 -08006253Currently has only one field: sched_priority
Larry Hastings2f936352014-08-05 14:04:04 +10006254[clinic start generated code]*/
6255
Larry Hastings2f936352014-08-05 14:04:04 +10006256static PyObject *
6257os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
Eddie Elizondob3966632019-11-05 07:16:14 -08006258/*[clinic end generated code: output=48f4067d60f48c13 input=eb42909a2c0e3e6c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006259{
6260 PyObject *res;
6261
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006262 res = PyStructSequence_New(type);
6263 if (!res)
6264 return NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10006265 Py_INCREF(sched_priority);
6266 PyStructSequence_SET_ITEM(res, 0, sched_priority);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006267 return res;
6268}
6269
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03006270PyDoc_VAR(os_sched_param__doc__);
6271
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006272static PyStructSequence_Field sched_param_fields[] = {
6273 {"sched_priority", "the scheduling priority"},
6274 {0}
6275};
6276
6277static PyStructSequence_Desc sched_param_desc = {
6278 "sched_param", /* name */
Larry Hastings2f936352014-08-05 14:04:04 +10006279 os_sched_param__doc__, /* doc */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006280 sched_param_fields,
6281 1
6282};
6283
6284static int
6285convert_sched_param(PyObject *param, struct sched_param *res)
6286{
6287 long priority;
6288
Eddie Elizondob3966632019-11-05 07:16:14 -08006289 PyObject *SchedParamType = _posixstate_global->SchedParamType;
6290 if (Py_TYPE(param) != (PyTypeObject *)SchedParamType) {
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006291 PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
6292 return 0;
6293 }
6294 priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
6295 if (priority == -1 && PyErr_Occurred())
6296 return 0;
6297 if (priority > INT_MAX || priority < INT_MIN) {
6298 PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
6299 return 0;
6300 }
6301 res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
6302 return 1;
6303}
William Orr81574b82018-10-01 22:19:56 -07006304#endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006305
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006306
6307#ifdef HAVE_SCHED_SETSCHEDULER
Larry Hastings2f936352014-08-05 14:04:04 +10006308/*[clinic input]
6309os.sched_setscheduler
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006310
Larry Hastings2f936352014-08-05 14:04:04 +10006311 pid: pid_t
6312 policy: int
6313 param: sched_param
6314 /
6315
6316Set the scheduling policy for the process identified by pid.
6317
6318If pid is 0, the calling process is changed.
6319param is an instance of sched_param.
6320[clinic start generated code]*/
6321
Larry Hastings2f936352014-08-05 14:04:04 +10006322static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006323os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
Larry Hastings89964c42015-04-14 18:07:59 -04006324 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006325/*[clinic end generated code: output=b0ac0a70d3b1d705 input=c581f9469a5327dd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006326{
Jesus Cea9c822272011-09-10 01:40:52 +02006327 /*
Jesus Cea54b01492011-09-10 01:53:19 +02006328 ** sched_setscheduler() returns 0 in Linux, but the previous
6329 ** scheduling policy under Solaris/Illumos, and others.
6330 ** On error, -1 is returned in all Operating Systems.
Jesus Cea9c822272011-09-10 01:40:52 +02006331 */
Larry Hastings2f936352014-08-05 14:04:04 +10006332 if (sched_setscheduler(pid, policy, param) == -1)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006333 return posix_error();
6334 Py_RETURN_NONE;
6335}
Larry Hastings2f936352014-08-05 14:04:04 +10006336#endif /* HAVE_SCHED_SETSCHEDULER*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006337
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006338
6339#ifdef HAVE_SCHED_SETPARAM
Larry Hastings2f936352014-08-05 14:04:04 +10006340/*[clinic input]
6341os.sched_getparam
6342 pid: pid_t
6343 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006344
Larry Hastings2f936352014-08-05 14:04:04 +10006345Returns scheduling parameters for the process identified by pid.
6346
6347If pid is 0, returns parameters for the calling process.
6348Return value is an instance of sched_param.
6349[clinic start generated code]*/
6350
Larry Hastings2f936352014-08-05 14:04:04 +10006351static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006352os_sched_getparam_impl(PyObject *module, pid_t pid)
6353/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006354{
6355 struct sched_param param;
6356 PyObject *result;
6357 PyObject *priority;
6358
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006359 if (sched_getparam(pid, &param))
6360 return posix_error();
Eddie Elizondob3966632019-11-05 07:16:14 -08006361 PyObject *SchedParamType = _posixstate_global->SchedParamType;
6362 result = PyStructSequence_New((PyTypeObject *)SchedParamType);
Larry Hastings2f936352014-08-05 14:04:04 +10006363 if (!result)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006364 return NULL;
6365 priority = PyLong_FromLong(param.sched_priority);
6366 if (!priority) {
Larry Hastings2f936352014-08-05 14:04:04 +10006367 Py_DECREF(result);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006368 return NULL;
6369 }
Larry Hastings2f936352014-08-05 14:04:04 +10006370 PyStructSequence_SET_ITEM(result, 0, priority);
6371 return result;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006372}
6373
Larry Hastings2f936352014-08-05 14:04:04 +10006374
6375/*[clinic input]
6376os.sched_setparam
6377 pid: pid_t
6378 param: sched_param
6379 /
6380
6381Set scheduling parameters for the process identified by pid.
6382
6383If pid is 0, sets parameters for the calling process.
6384param should be an instance of sched_param.
6385[clinic start generated code]*/
6386
Larry Hastings2f936352014-08-05 14:04:04 +10006387static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006388os_sched_setparam_impl(PyObject *module, pid_t pid,
Larry Hastings89964c42015-04-14 18:07:59 -04006389 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006390/*[clinic end generated code: output=8af013f78a32b591 input=6b8d6dfcecdc21bd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006391{
6392 if (sched_setparam(pid, param))
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006393 return posix_error();
6394 Py_RETURN_NONE;
6395}
Larry Hastings2f936352014-08-05 14:04:04 +10006396#endif /* HAVE_SCHED_SETPARAM */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006397
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006398
6399#ifdef HAVE_SCHED_RR_GET_INTERVAL
Larry Hastings2f936352014-08-05 14:04:04 +10006400/*[clinic input]
6401os.sched_rr_get_interval -> double
6402 pid: pid_t
6403 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006404
Larry Hastings2f936352014-08-05 14:04:04 +10006405Return the round-robin quantum for the process identified by pid, in seconds.
6406
6407Value returned is a float.
6408[clinic start generated code]*/
6409
Larry Hastings2f936352014-08-05 14:04:04 +10006410static double
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006411os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
6412/*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006413{
6414 struct timespec interval;
6415 if (sched_rr_get_interval(pid, &interval)) {
6416 posix_error();
6417 return -1.0;
6418 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006419#ifdef _Py_MEMORY_SANITIZER
6420 __msan_unpoison(&interval, sizeof(interval));
6421#endif
Larry Hastings2f936352014-08-05 14:04:04 +10006422 return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
6423}
6424#endif /* HAVE_SCHED_RR_GET_INTERVAL */
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006425
Larry Hastings2f936352014-08-05 14:04:04 +10006426
6427/*[clinic input]
6428os.sched_yield
6429
6430Voluntarily relinquish the CPU.
6431[clinic start generated code]*/
6432
Larry Hastings2f936352014-08-05 14:04:04 +10006433static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006434os_sched_yield_impl(PyObject *module)
6435/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006436{
6437 if (sched_yield())
6438 return posix_error();
6439 Py_RETURN_NONE;
6440}
6441
Benjamin Peterson2740af82011-08-02 17:41:34 -05006442#ifdef HAVE_SCHED_SETAFFINITY
Antoine Pitrou84869872012-08-04 16:16:35 +02006443/* The minimum number of CPUs allocated in a cpu_set_t */
6444static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006445
Larry Hastings2f936352014-08-05 14:04:04 +10006446/*[clinic input]
6447os.sched_setaffinity
6448 pid: pid_t
6449 mask : object
6450 /
6451
6452Set the CPU affinity of the process identified by pid to mask.
6453
6454mask should be an iterable of integers identifying CPUs.
6455[clinic start generated code]*/
6456
Larry Hastings2f936352014-08-05 14:04:04 +10006457static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006458os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
6459/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006460{
Antoine Pitrou84869872012-08-04 16:16:35 +02006461 int ncpus;
6462 size_t setsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006463 cpu_set_t *cpu_set = NULL;
6464 PyObject *iterator = NULL, *item;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006465
Larry Hastings2f936352014-08-05 14:04:04 +10006466 iterator = PyObject_GetIter(mask);
Antoine Pitrou84869872012-08-04 16:16:35 +02006467 if (iterator == NULL)
6468 return NULL;
6469
6470 ncpus = NCPUS_START;
6471 setsize = CPU_ALLOC_SIZE(ncpus);
Larry Hastings2f936352014-08-05 14:04:04 +10006472 cpu_set = CPU_ALLOC(ncpus);
6473 if (cpu_set == NULL) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006474 PyErr_NoMemory();
6475 goto error;
6476 }
Larry Hastings2f936352014-08-05 14:04:04 +10006477 CPU_ZERO_S(setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006478
6479 while ((item = PyIter_Next(iterator))) {
6480 long cpu;
6481 if (!PyLong_Check(item)) {
6482 PyErr_Format(PyExc_TypeError,
6483 "expected an iterator of ints, "
6484 "but iterator yielded %R",
6485 Py_TYPE(item));
6486 Py_DECREF(item);
6487 goto error;
6488 }
6489 cpu = PyLong_AsLong(item);
6490 Py_DECREF(item);
6491 if (cpu < 0) {
6492 if (!PyErr_Occurred())
6493 PyErr_SetString(PyExc_ValueError, "negative CPU number");
6494 goto error;
6495 }
6496 if (cpu > INT_MAX - 1) {
6497 PyErr_SetString(PyExc_OverflowError, "CPU number too large");
6498 goto error;
6499 }
6500 if (cpu >= ncpus) {
6501 /* Grow CPU mask to fit the CPU number */
6502 int newncpus = ncpus;
6503 cpu_set_t *newmask;
6504 size_t newsetsize;
6505 while (newncpus <= cpu) {
6506 if (newncpus > INT_MAX / 2)
6507 newncpus = cpu + 1;
6508 else
6509 newncpus = newncpus * 2;
6510 }
6511 newmask = CPU_ALLOC(newncpus);
6512 if (newmask == NULL) {
6513 PyErr_NoMemory();
6514 goto error;
6515 }
6516 newsetsize = CPU_ALLOC_SIZE(newncpus);
6517 CPU_ZERO_S(newsetsize, newmask);
Larry Hastings2f936352014-08-05 14:04:04 +10006518 memcpy(newmask, cpu_set, setsize);
6519 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006520 setsize = newsetsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006521 cpu_set = newmask;
Antoine Pitrou84869872012-08-04 16:16:35 +02006522 ncpus = newncpus;
6523 }
Larry Hastings2f936352014-08-05 14:04:04 +10006524 CPU_SET_S(cpu, setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006525 }
Brandt Bucher45a30af2019-06-27 09:10:57 -07006526 if (PyErr_Occurred()) {
6527 goto error;
6528 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006529 Py_CLEAR(iterator);
6530
Larry Hastings2f936352014-08-05 14:04:04 +10006531 if (sched_setaffinity(pid, setsize, cpu_set)) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006532 posix_error();
6533 goto error;
6534 }
Larry Hastings2f936352014-08-05 14:04:04 +10006535 CPU_FREE(cpu_set);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006536 Py_RETURN_NONE;
Antoine Pitrou84869872012-08-04 16:16:35 +02006537
6538error:
Larry Hastings2f936352014-08-05 14:04:04 +10006539 if (cpu_set)
6540 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006541 Py_XDECREF(iterator);
6542 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006543}
6544
Larry Hastings2f936352014-08-05 14:04:04 +10006545
6546/*[clinic input]
6547os.sched_getaffinity
6548 pid: pid_t
6549 /
6550
Charles-François Natalidc87e4b2015-07-13 21:01:39 +01006551Return the affinity of the process identified by pid (or the current process if zero).
Larry Hastings2f936352014-08-05 14:04:04 +10006552
6553The affinity is returned as a set of CPU identifiers.
6554[clinic start generated code]*/
6555
Larry Hastings2f936352014-08-05 14:04:04 +10006556static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006557os_sched_getaffinity_impl(PyObject *module, pid_t pid)
Serhiy Storchaka2954f832016-07-07 18:20:03 +03006558/*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006559{
Antoine Pitrou84869872012-08-04 16:16:35 +02006560 int cpu, ncpus, count;
6561 size_t setsize;
6562 cpu_set_t *mask = NULL;
6563 PyObject *res = NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006564
Antoine Pitrou84869872012-08-04 16:16:35 +02006565 ncpus = NCPUS_START;
6566 while (1) {
6567 setsize = CPU_ALLOC_SIZE(ncpus);
6568 mask = CPU_ALLOC(ncpus);
6569 if (mask == NULL)
6570 return PyErr_NoMemory();
6571 if (sched_getaffinity(pid, setsize, mask) == 0)
6572 break;
6573 CPU_FREE(mask);
6574 if (errno != EINVAL)
6575 return posix_error();
6576 if (ncpus > INT_MAX / 2) {
6577 PyErr_SetString(PyExc_OverflowError, "could not allocate "
6578 "a large enough CPU set");
6579 return NULL;
6580 }
6581 ncpus = ncpus * 2;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006582 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006583
6584 res = PySet_New(NULL);
6585 if (res == NULL)
6586 goto error;
6587 for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
6588 if (CPU_ISSET_S(cpu, setsize, mask)) {
6589 PyObject *cpu_num = PyLong_FromLong(cpu);
6590 --count;
6591 if (cpu_num == NULL)
6592 goto error;
6593 if (PySet_Add(res, cpu_num)) {
6594 Py_DECREF(cpu_num);
6595 goto error;
6596 }
6597 Py_DECREF(cpu_num);
6598 }
6599 }
6600 CPU_FREE(mask);
6601 return res;
6602
6603error:
6604 if (mask)
6605 CPU_FREE(mask);
6606 Py_XDECREF(res);
6607 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006608}
6609
Benjamin Peterson2740af82011-08-02 17:41:34 -05006610#endif /* HAVE_SCHED_SETAFFINITY */
6611
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006612#endif /* HAVE_SCHED_H */
6613
Larry Hastings2f936352014-08-05 14:04:04 +10006614
Neal Norwitzb59798b2003-03-21 01:43:31 +00006615/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
Neal Norwitz2deaddb2003-03-21 03:08:31 +00006616/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
6617#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
Neal Norwitzb59798b2003-03-21 01:43:31 +00006618#define DEV_PTY_FILE "/dev/ptc"
6619#define HAVE_DEV_PTMX
6620#else
6621#define DEV_PTY_FILE "/dev/ptmx"
6622#endif
6623
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006624#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
Fred Drake8cef4cf2000-06-28 16:40:38 +00006625#ifdef HAVE_PTY_H
6626#include <pty.h>
6627#else
6628#ifdef HAVE_LIBUTIL_H
6629#include <libutil.h>
Ronald Oussoren755740f2010-02-07 19:56:39 +00006630#else
6631#ifdef HAVE_UTIL_H
6632#include <util.h>
6633#endif /* HAVE_UTIL_H */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006634#endif /* HAVE_LIBUTIL_H */
6635#endif /* HAVE_PTY_H */
Martin v. Löwis14e73b12003-01-01 09:51:12 +00006636#ifdef HAVE_STROPTS_H
6637#include <stropts.h>
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006638#endif
ngie-eign7745ec42018-02-14 11:54:28 -08006639#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006640
Larry Hastings2f936352014-08-05 14:04:04 +10006641
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006642#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
Larry Hastings2f936352014-08-05 14:04:04 +10006643/*[clinic input]
6644os.openpty
6645
6646Open a pseudo-terminal.
6647
6648Return a tuple of (master_fd, slave_fd) containing open file descriptors
6649for both the master and slave ends.
6650[clinic start generated code]*/
6651
Larry Hastings2f936352014-08-05 14:04:04 +10006652static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006653os_openpty_impl(PyObject *module)
6654/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006655{
Victor Stinnerdaf45552013-08-28 00:53:59 +02006656 int master_fd = -1, slave_fd = -1;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006657#ifndef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006658 char * slave_name;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006659#endif
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006660#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006661 PyOS_sighandler_t sig_saved;
Jakub Kulík6f9bc722018-12-31 03:16:40 +01006662#if defined(__sun) && defined(__SVR4)
Victor Stinner8c62be82010-05-06 00:08:46 +00006663 extern char *ptsname(int fildes);
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006664#endif
6665#endif
Thomas Wouters70c21a12000-07-14 14:28:33 +00006666
Thomas Wouters70c21a12000-07-14 14:28:33 +00006667#ifdef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006668 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006669 goto posix_error;
6670
6671 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6672 goto error;
6673 if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
6674 goto error;
6675
Neal Norwitzb59798b2003-03-21 01:43:31 +00006676#elif defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006677 slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
6678 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006679 goto posix_error;
6680 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6681 goto error;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006682
Victor Stinnerdaf45552013-08-28 00:53:59 +02006683 slave_fd = _Py_open(slave_name, O_RDWR);
Victor Stinner8c62be82010-05-06 00:08:46 +00006684 if (slave_fd < 0)
Victor Stinnera555cfc2015-03-18 00:22:14 +01006685 goto error;
Victor Stinnerdaf45552013-08-28 00:53:59 +02006686
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006687#else
Victor Stinner000de532013-11-25 23:19:58 +01006688 master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
Victor Stinner8c62be82010-05-06 00:08:46 +00006689 if (master_fd < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006690 goto posix_error;
6691
Victor Stinner8c62be82010-05-06 00:08:46 +00006692 sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006693
Victor Stinner8c62be82010-05-06 00:08:46 +00006694 /* change permission of slave */
6695 if (grantpt(master_fd) < 0) {
6696 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006697 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006698 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006699
Victor Stinner8c62be82010-05-06 00:08:46 +00006700 /* unlock slave */
6701 if (unlockpt(master_fd) < 0) {
6702 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006703 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006704 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006705
Victor Stinner8c62be82010-05-06 00:08:46 +00006706 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006707
Victor Stinner8c62be82010-05-06 00:08:46 +00006708 slave_name = ptsname(master_fd); /* get name of slave */
6709 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006710 goto posix_error;
6711
6712 slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
Victor Stinnera555cfc2015-03-18 00:22:14 +01006713 if (slave_fd == -1)
6714 goto error;
Victor Stinner000de532013-11-25 23:19:58 +01006715
6716 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6717 goto posix_error;
6718
Stefan Krahfb7c8ae2016-04-26 17:04:18 +02006719#if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
Victor Stinner8c62be82010-05-06 00:08:46 +00006720 ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
6721 ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
Neal Norwitz6700e472002-12-31 16:16:07 +00006722#ifndef __hpux
Victor Stinner8c62be82010-05-06 00:08:46 +00006723 ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
Neal Norwitz6700e472002-12-31 16:16:07 +00006724#endif /* __hpux */
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006725#endif /* HAVE_CYGWIN */
Thomas Wouters1e0c2f42000-07-24 16:06:23 +00006726#endif /* HAVE_OPENPTY */
Thomas Wouters70c21a12000-07-14 14:28:33 +00006727
Victor Stinner8c62be82010-05-06 00:08:46 +00006728 return Py_BuildValue("(ii)", master_fd, slave_fd);
Thomas Wouters70c21a12000-07-14 14:28:33 +00006729
Victor Stinnerdaf45552013-08-28 00:53:59 +02006730posix_error:
6731 posix_error();
6732error:
6733 if (master_fd != -1)
6734 close(master_fd);
6735 if (slave_fd != -1)
6736 close(slave_fd);
6737 return NULL;
Fred Drake8cef4cf2000-06-28 16:40:38 +00006738}
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006739#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006740
Larry Hastings2f936352014-08-05 14:04:04 +10006741
Fred Drake8cef4cf2000-06-28 16:40:38 +00006742#ifdef HAVE_FORKPTY
Larry Hastings2f936352014-08-05 14:04:04 +10006743/*[clinic input]
6744os.forkpty
6745
6746Fork a new process with a new pseudo-terminal as controlling tty.
6747
6748Returns a tuple of (pid, master_fd).
6749Like fork(), return pid of 0 to the child process,
6750and pid of child to the parent process.
6751To both, return fd of newly opened pseudo-terminal.
6752[clinic start generated code]*/
6753
Larry Hastings2f936352014-08-05 14:04:04 +10006754static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006755os_forkpty_impl(PyObject *module)
6756/*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006757{
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006758 int master_fd = -1;
Victor Stinner8c62be82010-05-06 00:08:46 +00006759 pid_t pid;
Tim Peters5aa91602002-01-30 05:46:57 +00006760
Eric Snow59032962018-09-14 14:17:20 -07006761 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6762 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6763 return NULL;
6764 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006765 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006766 pid = forkpty(&master_fd, NULL, NULL, NULL);
6767 if (pid == 0) {
6768 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006769 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006770 } else {
6771 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006772 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006773 }
6774 if (pid == -1)
6775 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006776 return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
Fred Drake8cef4cf2000-06-28 16:40:38 +00006777}
Larry Hastings2f936352014-08-05 14:04:04 +10006778#endif /* HAVE_FORKPTY */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006779
Ross Lagerwall7807c352011-03-17 20:20:30 +02006780
Guido van Rossumad0ee831995-03-01 10:34:45 +00006781#ifdef HAVE_GETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10006782/*[clinic input]
6783os.getegid
6784
6785Return the current process's effective group id.
6786[clinic start generated code]*/
6787
Larry Hastings2f936352014-08-05 14:04:04 +10006788static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006789os_getegid_impl(PyObject *module)
6790/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006791{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006792 return _PyLong_FromGid(getegid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006793}
Larry Hastings2f936352014-08-05 14:04:04 +10006794#endif /* HAVE_GETEGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006795
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006796
Guido van Rossumad0ee831995-03-01 10:34:45 +00006797#ifdef HAVE_GETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10006798/*[clinic input]
6799os.geteuid
6800
6801Return the current process's effective user id.
6802[clinic start generated code]*/
6803
Larry Hastings2f936352014-08-05 14:04:04 +10006804static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006805os_geteuid_impl(PyObject *module)
6806/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006807{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006808 return _PyLong_FromUid(geteuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006809}
Larry Hastings2f936352014-08-05 14:04:04 +10006810#endif /* HAVE_GETEUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006811
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006812
Guido van Rossumad0ee831995-03-01 10:34:45 +00006813#ifdef HAVE_GETGID
Larry Hastings2f936352014-08-05 14:04:04 +10006814/*[clinic input]
6815os.getgid
6816
6817Return the current process's group id.
6818[clinic start generated code]*/
6819
Larry Hastings2f936352014-08-05 14:04:04 +10006820static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006821os_getgid_impl(PyObject *module)
6822/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006823{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006824 return _PyLong_FromGid(getgid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006825}
Larry Hastings2f936352014-08-05 14:04:04 +10006826#endif /* HAVE_GETGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006827
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006828
Berker Peksag39404992016-09-15 20:45:16 +03006829#ifdef HAVE_GETPID
Larry Hastings2f936352014-08-05 14:04:04 +10006830/*[clinic input]
6831os.getpid
6832
6833Return the current process id.
6834[clinic start generated code]*/
6835
Larry Hastings2f936352014-08-05 14:04:04 +10006836static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006837os_getpid_impl(PyObject *module)
6838/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006839{
Victor Stinner8c62be82010-05-06 00:08:46 +00006840 return PyLong_FromPid(getpid());
Guido van Rossum85e3b011991-06-03 12:42:10 +00006841}
Berker Peksag39404992016-09-15 20:45:16 +03006842#endif /* HAVE_GETPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00006843
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07006844#ifdef NGROUPS_MAX
6845#define MAX_GROUPS NGROUPS_MAX
6846#else
6847 /* defined to be 16 on Solaris7, so this should be a small number */
6848#define MAX_GROUPS 64
6849#endif
6850
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006851#ifdef HAVE_GETGROUPLIST
Larry Hastings2f936352014-08-05 14:04:04 +10006852
6853/* AC 3.5: funny apple logic below */
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006854PyDoc_STRVAR(posix_getgrouplist__doc__,
6855"getgrouplist(user, group) -> list of groups to which a user belongs\n\n\
6856Returns a list of groups to which a user belongs.\n\n\
6857 user: username to lookup\n\
6858 group: base group id of the user");
6859
6860static PyObject *
6861posix_getgrouplist(PyObject *self, PyObject *args)
6862{
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006863 const char *user;
6864 int i, ngroups;
6865 PyObject *list;
6866#ifdef __APPLE__
6867 int *groups, basegid;
6868#else
6869 gid_t *groups, basegid;
6870#endif
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07006871
6872 /*
6873 * NGROUPS_MAX is defined by POSIX.1 as the maximum
6874 * number of supplimental groups a users can belong to.
6875 * We have to increment it by one because
6876 * getgrouplist() returns both the supplemental groups
6877 * and the primary group, i.e. all of the groups the
6878 * user belongs to.
6879 */
6880 ngroups = 1 + MAX_GROUPS;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006881
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006882#ifdef __APPLE__
6883 if (!PyArg_ParseTuple(args, "si:getgrouplist", &user, &basegid))
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006884 return NULL;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006885#else
6886 if (!PyArg_ParseTuple(args, "sO&:getgrouplist", &user,
6887 _Py_Gid_Converter, &basegid))
6888 return NULL;
6889#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006890
6891#ifdef __APPLE__
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006892 groups = PyMem_New(int, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006893#else
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006894 groups = PyMem_New(gid_t, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006895#endif
6896 if (groups == NULL)
6897 return PyErr_NoMemory();
6898
6899 if (getgrouplist(user, basegid, groups, &ngroups) == -1) {
6900 PyMem_Del(groups);
6901 return posix_error();
6902 }
6903
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006904#ifdef _Py_MEMORY_SANITIZER
6905 /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
6906 __msan_unpoison(&ngroups, sizeof(ngroups));
6907 __msan_unpoison(groups, ngroups*sizeof(*groups));
6908#endif
6909
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006910 list = PyList_New(ngroups);
6911 if (list == NULL) {
6912 PyMem_Del(groups);
6913 return NULL;
6914 }
6915
6916 for (i = 0; i < ngroups; i++) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006917#ifdef __APPLE__
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006918 PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006919#else
6920 PyObject *o = _PyLong_FromGid(groups[i]);
6921#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006922 if (o == NULL) {
6923 Py_DECREF(list);
6924 PyMem_Del(groups);
6925 return NULL;
6926 }
6927 PyList_SET_ITEM(list, i, o);
6928 }
6929
6930 PyMem_Del(groups);
6931
6932 return list;
6933}
Larry Hastings2f936352014-08-05 14:04:04 +10006934#endif /* HAVE_GETGROUPLIST */
6935
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006936
Fred Drakec9680921999-12-13 16:37:25 +00006937#ifdef HAVE_GETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10006938/*[clinic input]
6939os.getgroups
6940
6941Return list of supplemental group IDs for the process.
6942[clinic start generated code]*/
6943
Larry Hastings2f936352014-08-05 14:04:04 +10006944static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006945os_getgroups_impl(PyObject *module)
6946/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
Fred Drakec9680921999-12-13 16:37:25 +00006947{
6948 PyObject *result = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00006949 gid_t grouplist[MAX_GROUPS];
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006950
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00006951 /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006952 * This is a helper variable to store the intermediate result when
6953 * that happens.
6954 *
6955 * To keep the code readable the OSX behaviour is unconditional,
6956 * according to the POSIX spec this should be safe on all unix-y
6957 * systems.
6958 */
6959 gid_t* alt_grouplist = grouplist;
Victor Stinner8c62be82010-05-06 00:08:46 +00006960 int n;
Fred Drakec9680921999-12-13 16:37:25 +00006961
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006962#ifdef __APPLE__
6963 /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
6964 * there are more groups than can fit in grouplist. Therefore, on OS X
6965 * always first call getgroups with length 0 to get the actual number
6966 * of groups.
6967 */
6968 n = getgroups(0, NULL);
6969 if (n < 0) {
6970 return posix_error();
6971 } else if (n <= MAX_GROUPS) {
6972 /* groups will fit in existing array */
6973 alt_grouplist = grouplist;
6974 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006975 alt_grouplist = PyMem_New(gid_t, n);
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006976 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07006977 return PyErr_NoMemory();
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006978 }
6979 }
6980
6981 n = getgroups(n, alt_grouplist);
6982 if (n == -1) {
6983 if (alt_grouplist != grouplist) {
6984 PyMem_Free(alt_grouplist);
6985 }
6986 return posix_error();
6987 }
6988#else
Victor Stinner8c62be82010-05-06 00:08:46 +00006989 n = getgroups(MAX_GROUPS, grouplist);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006990 if (n < 0) {
6991 if (errno == EINVAL) {
6992 n = getgroups(0, NULL);
6993 if (n == -1) {
6994 return posix_error();
6995 }
6996 if (n == 0) {
6997 /* Avoid malloc(0) */
6998 alt_grouplist = grouplist;
6999 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02007000 alt_grouplist = PyMem_New(gid_t, n);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007001 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07007002 return PyErr_NoMemory();
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007003 }
7004 n = getgroups(n, alt_grouplist);
7005 if (n == -1) {
7006 PyMem_Free(alt_grouplist);
7007 return posix_error();
7008 }
7009 }
7010 } else {
7011 return posix_error();
7012 }
7013 }
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007014#endif
7015
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007016 result = PyList_New(n);
7017 if (result != NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007018 int i;
7019 for (i = 0; i < n; ++i) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007020 PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
Victor Stinner8c62be82010-05-06 00:08:46 +00007021 if (o == NULL) {
Stefan Krah0e803b32010-11-26 16:16:47 +00007022 Py_DECREF(result);
7023 result = NULL;
7024 break;
Fred Drakec9680921999-12-13 16:37:25 +00007025 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007026 PyList_SET_ITEM(result, i, o);
Fred Drakec9680921999-12-13 16:37:25 +00007027 }
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007028 }
7029
7030 if (alt_grouplist != grouplist) {
7031 PyMem_Free(alt_grouplist);
Victor Stinner8c62be82010-05-06 00:08:46 +00007032 }
Neal Norwitze241ce82003-02-17 18:17:05 +00007033
Fred Drakec9680921999-12-13 16:37:25 +00007034 return result;
7035}
Larry Hastings2f936352014-08-05 14:04:04 +10007036#endif /* HAVE_GETGROUPS */
Fred Drakec9680921999-12-13 16:37:25 +00007037
Antoine Pitroub7572f02009-12-02 20:46:48 +00007038#ifdef HAVE_INITGROUPS
7039PyDoc_STRVAR(posix_initgroups__doc__,
7040"initgroups(username, gid) -> None\n\n\
7041Call the system initgroups() to initialize the group access list with all of\n\
7042the groups of which the specified username is a member, plus the specified\n\
7043group id.");
7044
Larry Hastings2f936352014-08-05 14:04:04 +10007045/* AC 3.5: funny apple logic */
Antoine Pitroub7572f02009-12-02 20:46:48 +00007046static PyObject *
7047posix_initgroups(PyObject *self, PyObject *args)
7048{
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007049 PyObject *oname;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03007050 const char *username;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007051 int res;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007052#ifdef __APPLE__
7053 int gid;
7054#else
7055 gid_t gid;
7056#endif
Antoine Pitroub7572f02009-12-02 20:46:48 +00007057
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007058#ifdef __APPLE__
7059 if (!PyArg_ParseTuple(args, "O&i:initgroups",
7060 PyUnicode_FSConverter, &oname,
7061 &gid))
7062#else
7063 if (!PyArg_ParseTuple(args, "O&O&:initgroups",
7064 PyUnicode_FSConverter, &oname,
7065 _Py_Gid_Converter, &gid))
7066#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00007067 return NULL;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007068 username = PyBytes_AS_STRING(oname);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007069
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007070 res = initgroups(username, gid);
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007071 Py_DECREF(oname);
7072 if (res == -1)
Victor Stinner8c62be82010-05-06 00:08:46 +00007073 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007074
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007075 Py_RETURN_NONE;
Antoine Pitroub7572f02009-12-02 20:46:48 +00007076}
Larry Hastings2f936352014-08-05 14:04:04 +10007077#endif /* HAVE_INITGROUPS */
7078
Antoine Pitroub7572f02009-12-02 20:46:48 +00007079
Martin v. Löwis606edc12002-06-13 21:09:11 +00007080#ifdef HAVE_GETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10007081/*[clinic input]
7082os.getpgid
7083
7084 pid: pid_t
7085
7086Call the system call getpgid(), and return the result.
7087[clinic start generated code]*/
7088
Larry Hastings2f936352014-08-05 14:04:04 +10007089static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007090os_getpgid_impl(PyObject *module, pid_t pid)
7091/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007092{
7093 pid_t pgid = getpgid(pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007094 if (pgid < 0)
7095 return posix_error();
7096 return PyLong_FromPid(pgid);
Martin v. Löwis606edc12002-06-13 21:09:11 +00007097}
7098#endif /* HAVE_GETPGID */
7099
7100
Guido van Rossumb6775db1994-08-01 11:34:53 +00007101#ifdef HAVE_GETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007102/*[clinic input]
7103os.getpgrp
7104
7105Return the current process group id.
7106[clinic start generated code]*/
7107
Larry Hastings2f936352014-08-05 14:04:04 +10007108static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007109os_getpgrp_impl(PyObject *module)
7110/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
Guido van Rossum04814471991-06-04 20:23:49 +00007111{
Guido van Rossumb6775db1994-08-01 11:34:53 +00007112#ifdef GETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007113 return PyLong_FromPid(getpgrp(0));
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007114#else /* GETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007115 return PyLong_FromPid(getpgrp());
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007116#endif /* GETPGRP_HAVE_ARG */
Guido van Rossum04814471991-06-04 20:23:49 +00007117}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007118#endif /* HAVE_GETPGRP */
Guido van Rossum04814471991-06-04 20:23:49 +00007119
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007120
Guido van Rossumb6775db1994-08-01 11:34:53 +00007121#ifdef HAVE_SETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007122/*[clinic input]
7123os.setpgrp
7124
7125Make the current process the leader of its process group.
7126[clinic start generated code]*/
7127
Larry Hastings2f936352014-08-05 14:04:04 +10007128static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007129os_setpgrp_impl(PyObject *module)
7130/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00007131{
Guido van Rossum64933891994-10-20 21:56:42 +00007132#ifdef SETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007133 if (setpgrp(0, 0) < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007134#else /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007135 if (setpgrp() < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007136#endif /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007137 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007138 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00007139}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007140#endif /* HAVE_SETPGRP */
7141
Guido van Rossumad0ee831995-03-01 10:34:45 +00007142#ifdef HAVE_GETPPID
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007143
7144#ifdef MS_WINDOWS
7145#include <tlhelp32.h>
7146
7147static PyObject*
7148win32_getppid()
7149{
7150 HANDLE snapshot;
7151 pid_t mypid;
7152 PyObject* result = NULL;
7153 BOOL have_record;
7154 PROCESSENTRY32 pe;
7155
7156 mypid = getpid(); /* This function never fails */
7157
7158 snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
7159 if (snapshot == INVALID_HANDLE_VALUE)
7160 return PyErr_SetFromWindowsErr(GetLastError());
7161
7162 pe.dwSize = sizeof(pe);
7163 have_record = Process32First(snapshot, &pe);
7164 while (have_record) {
7165 if (mypid == (pid_t)pe.th32ProcessID) {
7166 /* We could cache the ulong value in a static variable. */
7167 result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
7168 break;
7169 }
7170
7171 have_record = Process32Next(snapshot, &pe);
7172 }
7173
7174 /* If our loop exits and our pid was not found (result will be NULL)
7175 * then GetLastError will return ERROR_NO_MORE_FILES. This is an
7176 * error anyway, so let's raise it. */
7177 if (!result)
7178 result = PyErr_SetFromWindowsErr(GetLastError());
7179
7180 CloseHandle(snapshot);
7181
7182 return result;
7183}
7184#endif /*MS_WINDOWS*/
7185
Larry Hastings2f936352014-08-05 14:04:04 +10007186
7187/*[clinic input]
7188os.getppid
7189
7190Return the parent's process id.
7191
7192If the parent process has already exited, Windows machines will still
7193return its id; others systems will return the id of the 'init' process (1).
7194[clinic start generated code]*/
7195
Larry Hastings2f936352014-08-05 14:04:04 +10007196static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007197os_getppid_impl(PyObject *module)
7198/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00007199{
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007200#ifdef MS_WINDOWS
7201 return win32_getppid();
7202#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007203 return PyLong_FromPid(getppid());
Guido van Rossumad0ee831995-03-01 10:34:45 +00007204#endif
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007205}
7206#endif /* HAVE_GETPPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007207
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007208
Fred Drake12c6e2d1999-12-14 21:25:03 +00007209#ifdef HAVE_GETLOGIN
Larry Hastings2f936352014-08-05 14:04:04 +10007210/*[clinic input]
7211os.getlogin
7212
7213Return the actual login name.
7214[clinic start generated code]*/
7215
Larry Hastings2f936352014-08-05 14:04:04 +10007216static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007217os_getlogin_impl(PyObject *module)
7218/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
Fred Drake12c6e2d1999-12-14 21:25:03 +00007219{
Victor Stinner8c62be82010-05-06 00:08:46 +00007220 PyObject *result = NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007221#ifdef MS_WINDOWS
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007222 wchar_t user_name[UNLEN + 1];
Victor Stinner63941882011-09-29 00:42:28 +02007223 DWORD num_chars = Py_ARRAY_LENGTH(user_name);
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007224
7225 if (GetUserNameW(user_name, &num_chars)) {
7226 /* num_chars is the number of unicode chars plus null terminator */
7227 result = PyUnicode_FromWideChar(user_name, num_chars - 1);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007228 }
7229 else
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007230 result = PyErr_SetFromWindowsErr(GetLastError());
7231#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007232 char *name;
7233 int old_errno = errno;
Fred Drake12c6e2d1999-12-14 21:25:03 +00007234
Victor Stinner8c62be82010-05-06 00:08:46 +00007235 errno = 0;
7236 name = getlogin();
7237 if (name == NULL) {
7238 if (errno)
Victor Stinnere039ffe2010-08-15 09:33:08 +00007239 posix_error();
Fred Drake12c6e2d1999-12-14 21:25:03 +00007240 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007241 PyErr_SetString(PyExc_OSError, "unable to determine login name");
Victor Stinner8c62be82010-05-06 00:08:46 +00007242 }
7243 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007244 result = PyUnicode_DecodeFSDefault(name);
Victor Stinner8c62be82010-05-06 00:08:46 +00007245 errno = old_errno;
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007246#endif
Fred Drake12c6e2d1999-12-14 21:25:03 +00007247 return result;
7248}
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007249#endif /* HAVE_GETLOGIN */
Fred Drake12c6e2d1999-12-14 21:25:03 +00007250
Larry Hastings2f936352014-08-05 14:04:04 +10007251
Guido van Rossumad0ee831995-03-01 10:34:45 +00007252#ifdef HAVE_GETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007253/*[clinic input]
7254os.getuid
7255
7256Return the current process's user id.
7257[clinic start generated code]*/
7258
Larry Hastings2f936352014-08-05 14:04:04 +10007259static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007260os_getuid_impl(PyObject *module)
7261/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00007262{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007263 return _PyLong_FromUid(getuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00007264}
Larry Hastings2f936352014-08-05 14:04:04 +10007265#endif /* HAVE_GETUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00007266
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007267
Brian Curtineb24d742010-04-12 17:16:38 +00007268#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007269#define HAVE_KILL
7270#endif /* MS_WINDOWS */
7271
7272#ifdef HAVE_KILL
7273/*[clinic input]
7274os.kill
7275
7276 pid: pid_t
7277 signal: Py_ssize_t
7278 /
7279
7280Kill a process with a signal.
7281[clinic start generated code]*/
7282
Larry Hastings2f936352014-08-05 14:04:04 +10007283static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007284os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
7285/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007286#ifndef MS_WINDOWS
7287{
7288 if (kill(pid, (int)signal) == -1)
7289 return posix_error();
7290 Py_RETURN_NONE;
7291}
7292#else /* !MS_WINDOWS */
Brian Curtineb24d742010-04-12 17:16:38 +00007293{
Amaury Forgeot d'Arc0a589c92010-05-15 20:35:12 +00007294 PyObject *result;
Larry Hastings2f936352014-08-05 14:04:04 +10007295 DWORD sig = (DWORD)signal;
7296 DWORD err;
Victor Stinner8c62be82010-05-06 00:08:46 +00007297 HANDLE handle;
Brian Curtineb24d742010-04-12 17:16:38 +00007298
Victor Stinner8c62be82010-05-06 00:08:46 +00007299 /* Console processes which share a common console can be sent CTRL+C or
7300 CTRL+BREAK events, provided they handle said events. */
7301 if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007302 if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007303 err = GetLastError();
7304 PyErr_SetFromWindowsErr(err);
7305 }
7306 else
7307 Py_RETURN_NONE;
7308 }
Brian Curtineb24d742010-04-12 17:16:38 +00007309
Victor Stinner8c62be82010-05-06 00:08:46 +00007310 /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
7311 attempt to open and terminate the process. */
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007312 handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007313 if (handle == NULL) {
7314 err = GetLastError();
7315 return PyErr_SetFromWindowsErr(err);
7316 }
Brian Curtineb24d742010-04-12 17:16:38 +00007317
Victor Stinner8c62be82010-05-06 00:08:46 +00007318 if (TerminateProcess(handle, sig) == 0) {
7319 err = GetLastError();
7320 result = PyErr_SetFromWindowsErr(err);
7321 } else {
7322 Py_INCREF(Py_None);
7323 result = Py_None;
7324 }
Brian Curtineb24d742010-04-12 17:16:38 +00007325
Victor Stinner8c62be82010-05-06 00:08:46 +00007326 CloseHandle(handle);
7327 return result;
Brian Curtineb24d742010-04-12 17:16:38 +00007328}
Larry Hastings2f936352014-08-05 14:04:04 +10007329#endif /* !MS_WINDOWS */
7330#endif /* HAVE_KILL */
7331
7332
7333#ifdef HAVE_KILLPG
7334/*[clinic input]
7335os.killpg
7336
7337 pgid: pid_t
7338 signal: int
7339 /
7340
7341Kill a process group with a signal.
7342[clinic start generated code]*/
7343
Larry Hastings2f936352014-08-05 14:04:04 +10007344static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007345os_killpg_impl(PyObject *module, pid_t pgid, int signal)
7346/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007347{
7348 /* XXX some man pages make the `pgid` parameter an int, others
7349 a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
7350 take the same type. Moreover, pid_t is always at least as wide as
7351 int (else compilation of this module fails), which is safe. */
7352 if (killpg(pgid, signal) == -1)
7353 return posix_error();
7354 Py_RETURN_NONE;
7355}
7356#endif /* HAVE_KILLPG */
7357
Brian Curtineb24d742010-04-12 17:16:38 +00007358
Guido van Rossumc0125471996-06-28 18:55:32 +00007359#ifdef HAVE_PLOCK
Guido van Rossumc0125471996-06-28 18:55:32 +00007360#ifdef HAVE_SYS_LOCK_H
7361#include <sys/lock.h>
7362#endif
7363
Larry Hastings2f936352014-08-05 14:04:04 +10007364/*[clinic input]
7365os.plock
7366 op: int
7367 /
7368
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007369Lock program segments into memory.");
Larry Hastings2f936352014-08-05 14:04:04 +10007370[clinic start generated code]*/
7371
Larry Hastings2f936352014-08-05 14:04:04 +10007372static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007373os_plock_impl(PyObject *module, int op)
7374/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007375{
Victor Stinner8c62be82010-05-06 00:08:46 +00007376 if (plock(op) == -1)
7377 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007378 Py_RETURN_NONE;
Guido van Rossumc0125471996-06-28 18:55:32 +00007379}
Larry Hastings2f936352014-08-05 14:04:04 +10007380#endif /* HAVE_PLOCK */
7381
Guido van Rossumc0125471996-06-28 18:55:32 +00007382
Guido van Rossumb6775db1994-08-01 11:34:53 +00007383#ifdef HAVE_SETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007384/*[clinic input]
7385os.setuid
7386
7387 uid: uid_t
7388 /
7389
7390Set the current process's user id.
7391[clinic start generated code]*/
7392
Larry Hastings2f936352014-08-05 14:04:04 +10007393static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007394os_setuid_impl(PyObject *module, uid_t uid)
7395/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007396{
Victor Stinner8c62be82010-05-06 00:08:46 +00007397 if (setuid(uid) < 0)
7398 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007399 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007400}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007401#endif /* HAVE_SETUID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007402
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007403
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007404#ifdef HAVE_SETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10007405/*[clinic input]
7406os.seteuid
7407
7408 euid: uid_t
7409 /
7410
7411Set the current process's effective user id.
7412[clinic start generated code]*/
7413
Larry Hastings2f936352014-08-05 14:04:04 +10007414static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007415os_seteuid_impl(PyObject *module, uid_t euid)
7416/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007417{
7418 if (seteuid(euid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007419 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007420 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007421}
7422#endif /* HAVE_SETEUID */
7423
Larry Hastings2f936352014-08-05 14:04:04 +10007424
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007425#ifdef HAVE_SETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10007426/*[clinic input]
7427os.setegid
7428
7429 egid: gid_t
7430 /
7431
7432Set the current process's effective group id.
7433[clinic start generated code]*/
7434
Larry Hastings2f936352014-08-05 14:04:04 +10007435static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007436os_setegid_impl(PyObject *module, gid_t egid)
7437/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007438{
7439 if (setegid(egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007440 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007441 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007442}
7443#endif /* HAVE_SETEGID */
7444
Larry Hastings2f936352014-08-05 14:04:04 +10007445
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007446#ifdef HAVE_SETREUID
Larry Hastings2f936352014-08-05 14:04:04 +10007447/*[clinic input]
7448os.setreuid
7449
7450 ruid: uid_t
7451 euid: uid_t
7452 /
7453
7454Set the current process's real and effective user ids.
7455[clinic start generated code]*/
7456
Larry Hastings2f936352014-08-05 14:04:04 +10007457static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007458os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
7459/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007460{
Victor Stinner8c62be82010-05-06 00:08:46 +00007461 if (setreuid(ruid, euid) < 0) {
7462 return posix_error();
7463 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007464 Py_RETURN_NONE;
Victor Stinner8c62be82010-05-06 00:08:46 +00007465 }
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007466}
7467#endif /* HAVE_SETREUID */
7468
Larry Hastings2f936352014-08-05 14:04:04 +10007469
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007470#ifdef HAVE_SETREGID
Larry Hastings2f936352014-08-05 14:04:04 +10007471/*[clinic input]
7472os.setregid
7473
7474 rgid: gid_t
7475 egid: gid_t
7476 /
7477
7478Set the current process's real and effective group ids.
7479[clinic start generated code]*/
7480
Larry Hastings2f936352014-08-05 14:04:04 +10007481static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007482os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
7483/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007484{
7485 if (setregid(rgid, egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007486 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007487 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007488}
7489#endif /* HAVE_SETREGID */
7490
Larry Hastings2f936352014-08-05 14:04:04 +10007491
Guido van Rossumb6775db1994-08-01 11:34:53 +00007492#ifdef HAVE_SETGID
Larry Hastings2f936352014-08-05 14:04:04 +10007493/*[clinic input]
7494os.setgid
7495 gid: gid_t
7496 /
7497
7498Set the current process's group id.
7499[clinic start generated code]*/
7500
Larry Hastings2f936352014-08-05 14:04:04 +10007501static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007502os_setgid_impl(PyObject *module, gid_t gid)
7503/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007504{
Victor Stinner8c62be82010-05-06 00:08:46 +00007505 if (setgid(gid) < 0)
7506 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007507 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007508}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007509#endif /* HAVE_SETGID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007510
Larry Hastings2f936352014-08-05 14:04:04 +10007511
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007512#ifdef HAVE_SETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007513/*[clinic input]
7514os.setgroups
7515
7516 groups: object
7517 /
7518
7519Set the groups of the current process to list.
7520[clinic start generated code]*/
7521
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007522static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007523os_setgroups(PyObject *module, PyObject *groups)
7524/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007525{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007526 Py_ssize_t i, len;
Victor Stinner8c62be82010-05-06 00:08:46 +00007527 gid_t grouplist[MAX_GROUPS];
Tim Peters5aa91602002-01-30 05:46:57 +00007528
Victor Stinner8c62be82010-05-06 00:08:46 +00007529 if (!PySequence_Check(groups)) {
7530 PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
7531 return NULL;
7532 }
7533 len = PySequence_Size(groups);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007534 if (len < 0) {
7535 return NULL;
7536 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007537 if (len > MAX_GROUPS) {
7538 PyErr_SetString(PyExc_ValueError, "too many groups");
7539 return NULL;
7540 }
7541 for(i = 0; i < len; i++) {
7542 PyObject *elem;
7543 elem = PySequence_GetItem(groups, i);
7544 if (!elem)
7545 return NULL;
7546 if (!PyLong_Check(elem)) {
7547 PyErr_SetString(PyExc_TypeError,
7548 "groups must be integers");
7549 Py_DECREF(elem);
7550 return NULL;
7551 } else {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007552 if (!_Py_Gid_Converter(elem, &grouplist[i])) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007553 Py_DECREF(elem);
7554 return NULL;
7555 }
7556 }
7557 Py_DECREF(elem);
7558 }
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007559
Victor Stinner8c62be82010-05-06 00:08:46 +00007560 if (setgroups(len, grouplist) < 0)
7561 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007562 Py_RETURN_NONE;
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007563}
7564#endif /* HAVE_SETGROUPS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007565
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007566#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
7567static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +01007568wait_helper(pid_t pid, int status, struct rusage *ru)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007569{
Victor Stinner8c62be82010-05-06 00:08:46 +00007570 PyObject *result;
Eddie Elizondob3966632019-11-05 07:16:14 -08007571 PyObject *struct_rusage;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007572
Victor Stinner8c62be82010-05-06 00:08:46 +00007573 if (pid == -1)
7574 return posix_error();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007575
Zackery Spytz682107c2019-09-09 09:48:32 -06007576 // If wait succeeded but no child was ready to report status, ru will not
7577 // have been populated.
7578 if (pid == 0) {
7579 memset(ru, 0, sizeof(*ru));
7580 }
7581
Eddie Elizondob3966632019-11-05 07:16:14 -08007582 PyObject *m = PyImport_ImportModuleNoBlock("resource");
7583 if (m == NULL)
7584 return NULL;
7585 struct_rusage = PyObject_GetAttr(m, _posixstate_global->struct_rusage);
7586 Py_DECREF(m);
7587 if (struct_rusage == NULL)
7588 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007589
Victor Stinner8c62be82010-05-06 00:08:46 +00007590 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
7591 result = PyStructSequence_New((PyTypeObject*) struct_rusage);
7592 if (!result)
7593 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007594
7595#ifndef doubletime
7596#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
7597#endif
7598
Victor Stinner8c62be82010-05-06 00:08:46 +00007599 PyStructSequence_SET_ITEM(result, 0,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007600 PyFloat_FromDouble(doubletime(ru->ru_utime)));
Victor Stinner8c62be82010-05-06 00:08:46 +00007601 PyStructSequence_SET_ITEM(result, 1,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007602 PyFloat_FromDouble(doubletime(ru->ru_stime)));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007603#define SET_INT(result, index, value)\
Victor Stinner8c62be82010-05-06 00:08:46 +00007604 PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
7605 SET_INT(result, 2, ru->ru_maxrss);
7606 SET_INT(result, 3, ru->ru_ixrss);
7607 SET_INT(result, 4, ru->ru_idrss);
7608 SET_INT(result, 5, ru->ru_isrss);
7609 SET_INT(result, 6, ru->ru_minflt);
7610 SET_INT(result, 7, ru->ru_majflt);
7611 SET_INT(result, 8, ru->ru_nswap);
7612 SET_INT(result, 9, ru->ru_inblock);
7613 SET_INT(result, 10, ru->ru_oublock);
7614 SET_INT(result, 11, ru->ru_msgsnd);
7615 SET_INT(result, 12, ru->ru_msgrcv);
7616 SET_INT(result, 13, ru->ru_nsignals);
7617 SET_INT(result, 14, ru->ru_nvcsw);
7618 SET_INT(result, 15, ru->ru_nivcsw);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007619#undef SET_INT
7620
Victor Stinner8c62be82010-05-06 00:08:46 +00007621 if (PyErr_Occurred()) {
7622 Py_DECREF(result);
7623 return NULL;
7624 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007625
Victor Stinner8c62be82010-05-06 00:08:46 +00007626 return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007627}
7628#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
7629
Larry Hastings2f936352014-08-05 14:04:04 +10007630
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007631#ifdef HAVE_WAIT3
Larry Hastings2f936352014-08-05 14:04:04 +10007632/*[clinic input]
7633os.wait3
7634
7635 options: int
7636Wait for completion of a child process.
7637
7638Returns a tuple of information about the child process:
7639 (pid, status, rusage)
7640[clinic start generated code]*/
7641
Larry Hastings2f936352014-08-05 14:04:04 +10007642static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007643os_wait3_impl(PyObject *module, int options)
7644/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007645{
Victor Stinner8c62be82010-05-06 00:08:46 +00007646 pid_t pid;
Victor Stinner8c62be82010-05-06 00:08:46 +00007647 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007648 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007649 WAIT_TYPE status;
7650 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007651
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007652 do {
7653 Py_BEGIN_ALLOW_THREADS
7654 pid = wait3(&status, options, &ru);
7655 Py_END_ALLOW_THREADS
7656 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7657 if (pid < 0)
7658 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007659
Victor Stinner4195b5c2012-02-08 23:03:19 +01007660 return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007661}
7662#endif /* HAVE_WAIT3 */
7663
Larry Hastings2f936352014-08-05 14:04:04 +10007664
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007665#ifdef HAVE_WAIT4
Larry Hastings2f936352014-08-05 14:04:04 +10007666/*[clinic input]
7667
7668os.wait4
7669
7670 pid: pid_t
7671 options: int
7672
7673Wait for completion of a specific child process.
7674
7675Returns a tuple of information about the child process:
7676 (pid, status, rusage)
7677[clinic start generated code]*/
7678
Larry Hastings2f936352014-08-05 14:04:04 +10007679static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007680os_wait4_impl(PyObject *module, pid_t pid, int options)
7681/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007682{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007683 pid_t res;
Victor Stinner8c62be82010-05-06 00:08:46 +00007684 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007685 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007686 WAIT_TYPE status;
7687 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007688
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007689 do {
7690 Py_BEGIN_ALLOW_THREADS
7691 res = wait4(pid, &status, options, &ru);
7692 Py_END_ALLOW_THREADS
7693 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7694 if (res < 0)
7695 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007696
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007697 return wait_helper(res, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007698}
7699#endif /* HAVE_WAIT4 */
7700
Larry Hastings2f936352014-08-05 14:04:04 +10007701
Ross Lagerwall7807c352011-03-17 20:20:30 +02007702#if defined(HAVE_WAITID) && !defined(__APPLE__)
Larry Hastings2f936352014-08-05 14:04:04 +10007703/*[clinic input]
7704os.waitid
7705
7706 idtype: idtype_t
7707 Must be one of be P_PID, P_PGID or P_ALL.
7708 id: id_t
7709 The id to wait on.
7710 options: int
7711 Constructed from the ORing of one or more of WEXITED, WSTOPPED
7712 or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
7713 /
7714
7715Returns the result of waiting for a process or processes.
7716
7717Returns either waitid_result or None if WNOHANG is specified and there are
7718no children in a waitable state.
7719[clinic start generated code]*/
7720
Larry Hastings2f936352014-08-05 14:04:04 +10007721static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007722os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
7723/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007724{
7725 PyObject *result;
7726 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007727 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007728 siginfo_t si;
7729 si.si_pid = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007730
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007731 do {
7732 Py_BEGIN_ALLOW_THREADS
7733 res = waitid(idtype, id, &si, options);
7734 Py_END_ALLOW_THREADS
7735 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7736 if (res < 0)
7737 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007738
7739 if (si.si_pid == 0)
7740 Py_RETURN_NONE;
7741
Eddie Elizondob3966632019-11-05 07:16:14 -08007742 PyObject *WaitidResultType = _posixstate(module)->WaitidResultType;
7743 result = PyStructSequence_New((PyTypeObject *)WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +02007744 if (!result)
7745 return NULL;
7746
7747 PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007748 PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
Ross Lagerwall7807c352011-03-17 20:20:30 +02007749 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
7750 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
7751 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
7752 if (PyErr_Occurred()) {
7753 Py_DECREF(result);
7754 return NULL;
7755 }
7756
7757 return result;
7758}
Larry Hastings2f936352014-08-05 14:04:04 +10007759#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
Ross Lagerwall7807c352011-03-17 20:20:30 +02007760
Larry Hastings2f936352014-08-05 14:04:04 +10007761
7762#if defined(HAVE_WAITPID)
7763/*[clinic input]
7764os.waitpid
7765 pid: pid_t
7766 options: int
7767 /
7768
7769Wait for completion of a given child process.
7770
7771Returns a tuple of information regarding the child process:
7772 (pid, status)
7773
7774The options argument is ignored on Windows.
7775[clinic start generated code]*/
7776
Larry Hastings2f936352014-08-05 14:04:04 +10007777static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007778os_waitpid_impl(PyObject *module, pid_t pid, int options)
7779/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007780{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007781 pid_t res;
7782 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007783 WAIT_TYPE status;
7784 WAIT_STATUS_INT(status) = 0;
Guido van Rossum54ecc3d1999-01-27 17:53:11 +00007785
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007786 do {
7787 Py_BEGIN_ALLOW_THREADS
7788 res = waitpid(pid, &status, options);
7789 Py_END_ALLOW_THREADS
7790 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7791 if (res < 0)
7792 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007793
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007794 return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
Guido van Rossum21803b81992-08-09 12:55:27 +00007795}
Tim Petersab034fa2002-02-01 11:27:43 +00007796#elif defined(HAVE_CWAIT)
Tim Petersab034fa2002-02-01 11:27:43 +00007797/* MS C has a variant of waitpid() that's usable for most purposes. */
Larry Hastings2f936352014-08-05 14:04:04 +10007798/*[clinic input]
7799os.waitpid
Benjamin Petersonca470632016-09-06 13:47:26 -07007800 pid: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +10007801 options: int
7802 /
7803
7804Wait for completion of a given process.
7805
7806Returns a tuple of information regarding the process:
7807 (pid, status << 8)
7808
7809The options argument is ignored on Windows.
7810[clinic start generated code]*/
7811
Larry Hastings2f936352014-08-05 14:04:04 +10007812static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -07007813os_waitpid_impl(PyObject *module, intptr_t pid, int options)
Victor Stinner581139c2016-09-06 15:54:20 -07007814/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007815{
7816 int status;
Benjamin Petersonca470632016-09-06 13:47:26 -07007817 intptr_t res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007818 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007819
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007820 do {
7821 Py_BEGIN_ALLOW_THREADS
Steve Dower11f43262016-11-19 18:33:39 -08007822 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007823 res = _cwait(&status, pid, options);
Steve Dower11f43262016-11-19 18:33:39 -08007824 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007825 Py_END_ALLOW_THREADS
7826 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinnerd3ffd322015-09-15 10:11:03 +02007827 if (res < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007828 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007829
Victor Stinner8c62be82010-05-06 00:08:46 +00007830 /* shift the status left a byte so this is more like the POSIX waitpid */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007831 return Py_BuildValue(_Py_PARSE_INTPTR "i", res, status << 8);
Tim Petersab034fa2002-02-01 11:27:43 +00007832}
Larry Hastings2f936352014-08-05 14:04:04 +10007833#endif
7834
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007835
Guido van Rossumad0ee831995-03-01 10:34:45 +00007836#ifdef HAVE_WAIT
Larry Hastings2f936352014-08-05 14:04:04 +10007837/*[clinic input]
7838os.wait
7839
7840Wait for completion of a child process.
7841
7842Returns a tuple of information about the child process:
7843 (pid, status)
7844[clinic start generated code]*/
7845
Larry Hastings2f936352014-08-05 14:04:04 +10007846static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007847os_wait_impl(PyObject *module)
7848/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
Guido van Rossum21803b81992-08-09 12:55:27 +00007849{
Victor Stinner8c62be82010-05-06 00:08:46 +00007850 pid_t pid;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007851 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007852 WAIT_TYPE status;
7853 WAIT_STATUS_INT(status) = 0;
Neal Norwitze241ce82003-02-17 18:17:05 +00007854
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007855 do {
7856 Py_BEGIN_ALLOW_THREADS
7857 pid = wait(&status);
7858 Py_END_ALLOW_THREADS
7859 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7860 if (pid < 0)
7861 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007862
Victor Stinner8c62be82010-05-06 00:08:46 +00007863 return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
Guido van Rossum85e3b011991-06-03 12:42:10 +00007864}
Larry Hastings2f936352014-08-05 14:04:04 +10007865#endif /* HAVE_WAIT */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007866
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -08007867#if defined(__linux__) && defined(__NR_pidfd_open)
7868/*[clinic input]
7869os.pidfd_open
7870 pid: pid_t
7871 flags: unsigned_int = 0
7872
7873Return a file descriptor referring to the process *pid*.
7874
7875The descriptor can be used to perform process management without races and
7876signals.
7877[clinic start generated code]*/
7878
7879static PyObject *
7880os_pidfd_open_impl(PyObject *module, pid_t pid, unsigned int flags)
7881/*[clinic end generated code: output=5c7252698947dc41 input=c3fd99ce947ccfef]*/
7882{
7883 int fd = syscall(__NR_pidfd_open, pid, flags);
7884 if (fd < 0) {
7885 return posix_error();
7886 }
7887 return PyLong_FromLong(fd);
7888}
7889#endif
7890
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007891
Larry Hastings9cf065c2012-06-22 16:30:09 -07007892#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007893/*[clinic input]
7894os.readlink
7895
7896 path: path_t
7897 *
7898 dir_fd: dir_fd(requires='readlinkat') = None
7899
7900Return a string representing the path to which the symbolic link points.
7901
7902If dir_fd is not None, it should be a file descriptor open to a directory,
7903and path should be relative; path will then be relative to that directory.
7904
7905dir_fd may not be implemented on your platform. If it is unavailable,
7906using it will raise a NotImplementedError.
7907[clinic start generated code]*/
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007908
Barry Warsaw53699e91996-12-10 23:23:01 +00007909static PyObject *
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007910os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
7911/*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00007912{
Berker Peksage0b5b202018-08-15 13:03:41 +03007913#if defined(HAVE_READLINK)
Christian Heimes3cb091e2016-09-23 20:24:28 +02007914 char buffer[MAXPATHLEN+1];
Larry Hastings9cf065c2012-06-22 16:30:09 -07007915 ssize_t length;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007916
7917 Py_BEGIN_ALLOW_THREADS
7918#ifdef HAVE_READLINKAT
7919 if (dir_fd != DEFAULT_DIR_FD)
7920 length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
7921 else
7922#endif
7923 length = readlink(path->narrow, buffer, MAXPATHLEN);
7924 Py_END_ALLOW_THREADS
7925
7926 if (length < 0) {
7927 return path_error(path);
7928 }
7929 buffer[length] = '\0';
7930
7931 if (PyUnicode_Check(path->object))
7932 return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
7933 else
7934 return PyBytes_FromStringAndSize(buffer, length);
Berker Peksage0b5b202018-08-15 13:03:41 +03007935#elif defined(MS_WINDOWS)
7936 DWORD n_bytes_returned;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007937 DWORD io_result = 0;
Berker Peksage0b5b202018-08-15 13:03:41 +03007938 HANDLE reparse_point_handle;
Berker Peksage0b5b202018-08-15 13:03:41 +03007939 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
7940 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Steve Dower993ac922019-09-03 12:50:51 -07007941 PyObject *result = NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00007942
Larry Hastings2f936352014-08-05 14:04:04 +10007943 /* First get a handle to the reparse point */
7944 Py_BEGIN_ALLOW_THREADS
7945 reparse_point_handle = CreateFileW(
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007946 path->wide,
Larry Hastings2f936352014-08-05 14:04:04 +10007947 0,
7948 0,
7949 0,
7950 OPEN_EXISTING,
7951 FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
7952 0);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007953 if (reparse_point_handle != INVALID_HANDLE_VALUE) {
7954 /* New call DeviceIoControl to read the reparse point */
7955 io_result = DeviceIoControl(
7956 reparse_point_handle,
7957 FSCTL_GET_REPARSE_POINT,
7958 0, 0, /* in buffer */
7959 target_buffer, sizeof(target_buffer),
7960 &n_bytes_returned,
7961 0 /* we're not using OVERLAPPED_IO */
7962 );
7963 CloseHandle(reparse_point_handle);
Berker Peksage0b5b202018-08-15 13:03:41 +03007964 }
Larry Hastings2f936352014-08-05 14:04:04 +10007965 Py_END_ALLOW_THREADS
7966
Berker Peksage0b5b202018-08-15 13:03:41 +03007967 if (io_result == 0) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007968 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03007969 }
Larry Hastings2f936352014-08-05 14:04:04 +10007970
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007971 wchar_t *name = NULL;
7972 Py_ssize_t nameLen = 0;
7973 if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
Larry Hastings2f936352014-08-05 14:04:04 +10007974 {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007975 name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
7976 rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
7977 nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
Larry Hastings2f936352014-08-05 14:04:04 +10007978 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007979 else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
7980 {
7981 name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
7982 rdb->MountPointReparseBuffer.SubstituteNameOffset);
7983 nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
7984 }
7985 else
7986 {
7987 PyErr_SetString(PyExc_ValueError, "not a symbolic link");
7988 }
7989 if (name) {
7990 if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
7991 /* Our buffer is mutable, so this is okay */
7992 name[1] = L'\\';
7993 }
7994 result = PyUnicode_FromWideChar(name, nameLen);
Steve Dower993ac922019-09-03 12:50:51 -07007995 if (result && path->narrow) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007996 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
7997 }
Berker Peksage0b5b202018-08-15 13:03:41 +03007998 }
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007999 return result;
Berker Peksage0b5b202018-08-15 13:03:41 +03008000#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008001}
Berker Peksage0b5b202018-08-15 13:03:41 +03008002#endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008003
Larry Hastings9cf065c2012-06-22 16:30:09 -07008004#ifdef HAVE_SYMLINK
Larry Hastings9cf065c2012-06-22 16:30:09 -07008005
8006#if defined(MS_WINDOWS)
8007
Steve Dower6921e732018-03-05 14:26:08 -08008008/* Remove the last portion of the path - return 0 on success */
8009static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008010_dirnameW(WCHAR *path)
8011{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008012 WCHAR *ptr;
Steve Dower6921e732018-03-05 14:26:08 -08008013 size_t length = wcsnlen_s(path, MAX_PATH);
8014 if (length == MAX_PATH) {
8015 return -1;
8016 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008017
8018 /* walk the path from the end until a backslash is encountered */
Steve Dower6921e732018-03-05 14:26:08 -08008019 for(ptr = path + length; ptr != path; ptr--) {
8020 if (*ptr == L'\\' || *ptr == L'/') {
Jason R. Coombs3a092862013-05-27 23:21:28 -04008021 break;
Steve Dower6921e732018-03-05 14:26:08 -08008022 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008023 }
8024 *ptr = 0;
Steve Dower6921e732018-03-05 14:26:08 -08008025 return 0;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008026}
8027
Victor Stinner31b3b922013-06-05 01:49:17 +02008028/* Is this path absolute? */
8029static int
8030_is_absW(const WCHAR *path)
8031{
Steve Dower6921e732018-03-05 14:26:08 -08008032 return path[0] == L'\\' || path[0] == L'/' ||
8033 (path[0] && path[1] == L':');
Jason R. Coombs3a092862013-05-27 23:21:28 -04008034}
8035
Steve Dower6921e732018-03-05 14:26:08 -08008036/* join root and rest with a backslash - return 0 on success */
8037static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008038_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
8039{
Victor Stinner31b3b922013-06-05 01:49:17 +02008040 if (_is_absW(rest)) {
Steve Dower6921e732018-03-05 14:26:08 -08008041 return wcscpy_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008042 }
8043
Steve Dower6921e732018-03-05 14:26:08 -08008044 if (wcscpy_s(dest_path, MAX_PATH, root)) {
8045 return -1;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008046 }
Steve Dower6921e732018-03-05 14:26:08 -08008047
8048 if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
8049 return -1;
8050 }
8051
8052 return wcscat_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008053}
8054
Victor Stinner31b3b922013-06-05 01:49:17 +02008055/* Return True if the path at src relative to dest is a directory */
8056static int
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03008057_check_dirW(LPCWSTR src, LPCWSTR dest)
Jason R. Coombs3a092862013-05-27 23:21:28 -04008058{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008059 WIN32_FILE_ATTRIBUTE_DATA src_info;
8060 WCHAR dest_parent[MAX_PATH];
8061 WCHAR src_resolved[MAX_PATH] = L"";
8062
8063 /* dest_parent = os.path.dirname(dest) */
Steve Dower6921e732018-03-05 14:26:08 -08008064 if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
8065 _dirnameW(dest_parent)) {
8066 return 0;
8067 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008068 /* src_resolved = os.path.join(dest_parent, src) */
Steve Dower6921e732018-03-05 14:26:08 -08008069 if (_joinW(src_resolved, dest_parent, src)) {
8070 return 0;
8071 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008072 return (
8073 GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
8074 && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
8075 );
8076}
Larry Hastings9cf065c2012-06-22 16:30:09 -07008077#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008078
Larry Hastings2f936352014-08-05 14:04:04 +10008079
8080/*[clinic input]
8081os.symlink
8082 src: path_t
8083 dst: path_t
8084 target_is_directory: bool = False
8085 *
8086 dir_fd: dir_fd(requires='symlinkat')=None
8087
8088# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
8089
8090Create a symbolic link pointing to src named dst.
8091
8092target_is_directory is required on Windows if the target is to be
8093 interpreted as a directory. (On Windows, symlink requires
8094 Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
8095 target_is_directory is ignored on non-Windows platforms.
8096
8097If dir_fd is not None, it should be a file descriptor open to a directory,
8098 and path should be relative; path will then be relative to that directory.
8099dir_fd may not be implemented on your platform.
8100 If it is unavailable, using it will raise a NotImplementedError.
8101
8102[clinic start generated code]*/
8103
Larry Hastings2f936352014-08-05 14:04:04 +10008104static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008105os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
Larry Hastings89964c42015-04-14 18:07:59 -04008106 int target_is_directory, int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008107/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008108{
Larry Hastings9cf065c2012-06-22 16:30:09 -07008109#ifdef MS_WINDOWS
8110 DWORD result;
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008111 DWORD flags = 0;
8112
8113 /* Assumed true, set to false if detected to not be available. */
8114 static int windows_has_symlink_unprivileged_flag = TRUE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008115#else
8116 int result;
8117#endif
8118
Larry Hastings9cf065c2012-06-22 16:30:09 -07008119#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008120
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008121 if (windows_has_symlink_unprivileged_flag) {
8122 /* Allow non-admin symlinks if system allows it. */
8123 flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
8124 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008125
Larry Hastings9cf065c2012-06-22 16:30:09 -07008126 Py_BEGIN_ALLOW_THREADS
Steve Dower6921e732018-03-05 14:26:08 -08008127 _Py_BEGIN_SUPPRESS_IPH
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008128 /* if src is a directory, ensure flags==1 (target_is_directory bit) */
8129 if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
8130 flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
8131 }
8132
8133 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
Steve Dower6921e732018-03-05 14:26:08 -08008134 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07008135 Py_END_ALLOW_THREADS
8136
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008137 if (windows_has_symlink_unprivileged_flag && !result &&
8138 ERROR_INVALID_PARAMETER == GetLastError()) {
8139
8140 Py_BEGIN_ALLOW_THREADS
8141 _Py_BEGIN_SUPPRESS_IPH
8142 /* This error might be caused by
8143 SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
8144 Try again, and update windows_has_symlink_unprivileged_flag if we
8145 are successful this time.
8146
8147 NOTE: There is a risk of a race condition here if there are other
8148 conditions than the flag causing ERROR_INVALID_PARAMETER, and
8149 another process (or thread) changes that condition in between our
8150 calls to CreateSymbolicLink.
8151 */
8152 flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
8153 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
8154 _Py_END_SUPPRESS_IPH
8155 Py_END_ALLOW_THREADS
8156
8157 if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
8158 windows_has_symlink_unprivileged_flag = FALSE;
8159 }
8160 }
8161
Larry Hastings2f936352014-08-05 14:04:04 +10008162 if (!result)
8163 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008164
8165#else
8166
Steve Dower6921e732018-03-05 14:26:08 -08008167 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
8168 PyErr_SetString(PyExc_ValueError,
8169 "symlink: src and dst must be the same type");
8170 return NULL;
8171 }
8172
Larry Hastings9cf065c2012-06-22 16:30:09 -07008173 Py_BEGIN_ALLOW_THREADS
8174#if HAVE_SYMLINKAT
8175 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10008176 result = symlinkat(src->narrow, dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008177 else
8178#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008179 result = symlink(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008180 Py_END_ALLOW_THREADS
8181
Larry Hastings2f936352014-08-05 14:04:04 +10008182 if (result)
8183 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008184#endif
8185
Larry Hastings2f936352014-08-05 14:04:04 +10008186 Py_RETURN_NONE;
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008187}
8188#endif /* HAVE_SYMLINK */
8189
Larry Hastings9cf065c2012-06-22 16:30:09 -07008190
Brian Curtind40e6f72010-07-08 21:39:08 +00008191
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008192
Larry Hastings605a62d2012-06-24 04:33:36 -07008193static PyStructSequence_Field times_result_fields[] = {
8194 {"user", "user time"},
8195 {"system", "system time"},
8196 {"children_user", "user time of children"},
8197 {"children_system", "system time of children"},
8198 {"elapsed", "elapsed time since an arbitrary point in the past"},
8199 {NULL}
8200};
8201
8202PyDoc_STRVAR(times_result__doc__,
8203"times_result: Result from os.times().\n\n\
8204This object may be accessed either as a tuple of\n\
8205 (user, system, children_user, children_system, elapsed),\n\
8206or via the attributes user, system, children_user, children_system,\n\
8207and elapsed.\n\
8208\n\
8209See os.times for more information.");
8210
8211static PyStructSequence_Desc times_result_desc = {
8212 "times_result", /* name */
8213 times_result__doc__, /* doc */
8214 times_result_fields,
8215 5
8216};
8217
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008218#ifdef MS_WINDOWS
8219#define HAVE_TIMES /* mandatory, for the method table */
8220#endif
Larry Hastings605a62d2012-06-24 04:33:36 -07008221
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008222#ifdef HAVE_TIMES
Larry Hastings605a62d2012-06-24 04:33:36 -07008223
8224static PyObject *
8225build_times_result(double user, double system,
8226 double children_user, double children_system,
8227 double elapsed)
8228{
Eddie Elizondob3966632019-11-05 07:16:14 -08008229 PyObject *TimesResultType = _posixstate_global->TimesResultType;
8230 PyObject *value = PyStructSequence_New((PyTypeObject *)TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07008231 if (value == NULL)
8232 return NULL;
8233
8234#define SET(i, field) \
8235 { \
8236 PyObject *o = PyFloat_FromDouble(field); \
8237 if (!o) { \
8238 Py_DECREF(value); \
8239 return NULL; \
8240 } \
8241 PyStructSequence_SET_ITEM(value, i, o); \
8242 } \
8243
8244 SET(0, user);
8245 SET(1, system);
8246 SET(2, children_user);
8247 SET(3, children_system);
8248 SET(4, elapsed);
8249
8250#undef SET
8251
8252 return value;
8253}
8254
Larry Hastings605a62d2012-06-24 04:33:36 -07008255
Larry Hastings2f936352014-08-05 14:04:04 +10008256#ifndef MS_WINDOWS
8257#define NEED_TICKS_PER_SECOND
8258static long ticks_per_second = -1;
8259#endif /* MS_WINDOWS */
8260
8261/*[clinic input]
8262os.times
8263
8264Return a collection containing process timing information.
8265
8266The object returned behaves like a named tuple with these fields:
8267 (utime, stime, cutime, cstime, elapsed_time)
8268All fields are floating point numbers.
8269[clinic start generated code]*/
8270
Larry Hastings2f936352014-08-05 14:04:04 +10008271static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008272os_times_impl(PyObject *module)
8273/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008274#ifdef MS_WINDOWS
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008275{
Victor Stinner8c62be82010-05-06 00:08:46 +00008276 FILETIME create, exit, kernel, user;
8277 HANDLE hProc;
8278 hProc = GetCurrentProcess();
8279 GetProcessTimes(hProc, &create, &exit, &kernel, &user);
8280 /* The fields of a FILETIME structure are the hi and lo part
8281 of a 64-bit value expressed in 100 nanosecond units.
8282 1e7 is one second in such units; 1e-7 the inverse.
8283 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
8284 */
Larry Hastings605a62d2012-06-24 04:33:36 -07008285 return build_times_result(
Victor Stinner8c62be82010-05-06 00:08:46 +00008286 (double)(user.dwHighDateTime*429.4967296 +
8287 user.dwLowDateTime*1e-7),
8288 (double)(kernel.dwHighDateTime*429.4967296 +
8289 kernel.dwLowDateTime*1e-7),
8290 (double)0,
8291 (double)0,
8292 (double)0);
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008293}
Larry Hastings2f936352014-08-05 14:04:04 +10008294#else /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008295{
Larry Hastings2f936352014-08-05 14:04:04 +10008296
8297
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008298 struct tms t;
8299 clock_t c;
8300 errno = 0;
8301 c = times(&t);
8302 if (c == (clock_t) -1)
8303 return posix_error();
8304 return build_times_result(
8305 (double)t.tms_utime / ticks_per_second,
8306 (double)t.tms_stime / ticks_per_second,
8307 (double)t.tms_cutime / ticks_per_second,
8308 (double)t.tms_cstime / ticks_per_second,
8309 (double)c / ticks_per_second);
8310}
Larry Hastings2f936352014-08-05 14:04:04 +10008311#endif /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008312#endif /* HAVE_TIMES */
8313
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008314
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008315#ifdef HAVE_GETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008316/*[clinic input]
8317os.getsid
8318
8319 pid: pid_t
8320 /
8321
8322Call the system call getsid(pid) and return the result.
8323[clinic start generated code]*/
8324
Larry Hastings2f936352014-08-05 14:04:04 +10008325static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008326os_getsid_impl(PyObject *module, pid_t pid)
8327/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008328{
Victor Stinner8c62be82010-05-06 00:08:46 +00008329 int sid;
Victor Stinner8c62be82010-05-06 00:08:46 +00008330 sid = getsid(pid);
8331 if (sid < 0)
8332 return posix_error();
8333 return PyLong_FromLong((long)sid);
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008334}
8335#endif /* HAVE_GETSID */
8336
8337
Guido van Rossumb6775db1994-08-01 11:34:53 +00008338#ifdef HAVE_SETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008339/*[clinic input]
8340os.setsid
8341
8342Call the system call setsid().
8343[clinic start generated code]*/
8344
Larry Hastings2f936352014-08-05 14:04:04 +10008345static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008346os_setsid_impl(PyObject *module)
8347/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00008348{
Victor Stinner8c62be82010-05-06 00:08:46 +00008349 if (setsid() < 0)
8350 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008351 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008352}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008353#endif /* HAVE_SETSID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008354
Larry Hastings2f936352014-08-05 14:04:04 +10008355
Guido van Rossumb6775db1994-08-01 11:34:53 +00008356#ifdef HAVE_SETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10008357/*[clinic input]
8358os.setpgid
8359
8360 pid: pid_t
8361 pgrp: pid_t
8362 /
8363
8364Call the system call setpgid(pid, pgrp).
8365[clinic start generated code]*/
8366
Larry Hastings2f936352014-08-05 14:04:04 +10008367static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008368os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
8369/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008370{
Victor Stinner8c62be82010-05-06 00:08:46 +00008371 if (setpgid(pid, pgrp) < 0)
8372 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008373 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008374}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008375#endif /* HAVE_SETPGID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008376
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008377
Guido van Rossumb6775db1994-08-01 11:34:53 +00008378#ifdef HAVE_TCGETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008379/*[clinic input]
8380os.tcgetpgrp
8381
8382 fd: int
8383 /
8384
8385Return the process group associated with the terminal specified by fd.
8386[clinic start generated code]*/
8387
Larry Hastings2f936352014-08-05 14:04:04 +10008388static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008389os_tcgetpgrp_impl(PyObject *module, int fd)
8390/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008391{
8392 pid_t pgid = tcgetpgrp(fd);
Victor Stinner8c62be82010-05-06 00:08:46 +00008393 if (pgid < 0)
8394 return posix_error();
8395 return PyLong_FromPid(pgid);
Guido van Rossum7066dd71992-09-17 17:54:56 +00008396}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008397#endif /* HAVE_TCGETPGRP */
Guido van Rossum7066dd71992-09-17 17:54:56 +00008398
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008399
Guido van Rossumb6775db1994-08-01 11:34:53 +00008400#ifdef HAVE_TCSETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008401/*[clinic input]
8402os.tcsetpgrp
8403
8404 fd: int
8405 pgid: pid_t
8406 /
8407
8408Set the process group associated with the terminal specified by fd.
8409[clinic start generated code]*/
8410
Larry Hastings2f936352014-08-05 14:04:04 +10008411static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008412os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
8413/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008414{
Victor Stinner8c62be82010-05-06 00:08:46 +00008415 if (tcsetpgrp(fd, pgid) < 0)
8416 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008417 Py_RETURN_NONE;
Guido van Rossum7066dd71992-09-17 17:54:56 +00008418}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008419#endif /* HAVE_TCSETPGRP */
Guido van Rossum22db57e1992-04-05 14:25:30 +00008420
Guido van Rossum687dd131993-05-17 08:34:16 +00008421/* Functions acting on file descriptors */
8422
Victor Stinnerdaf45552013-08-28 00:53:59 +02008423#ifdef O_CLOEXEC
8424extern int _Py_open_cloexec_works;
8425#endif
8426
Larry Hastings2f936352014-08-05 14:04:04 +10008427
8428/*[clinic input]
8429os.open -> int
8430 path: path_t
8431 flags: int
8432 mode: int = 0o777
8433 *
8434 dir_fd: dir_fd(requires='openat') = None
8435
8436# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
8437
8438Open a file for low level IO. Returns a file descriptor (integer).
8439
8440If dir_fd is not None, it should be a file descriptor open to a directory,
8441 and path should be relative; path will then be relative to that directory.
8442dir_fd may not be implemented on your platform.
8443 If it is unavailable, using it will raise a NotImplementedError.
8444[clinic start generated code]*/
8445
Larry Hastings2f936352014-08-05 14:04:04 +10008446static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008447os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
8448/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008449{
8450 int fd;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008451 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008452
Victor Stinnerdaf45552013-08-28 00:53:59 +02008453#ifdef O_CLOEXEC
8454 int *atomic_flag_works = &_Py_open_cloexec_works;
8455#elif !defined(MS_WINDOWS)
8456 int *atomic_flag_works = NULL;
8457#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +00008458
Victor Stinnerdaf45552013-08-28 00:53:59 +02008459#ifdef MS_WINDOWS
8460 flags |= O_NOINHERIT;
8461#elif defined(O_CLOEXEC)
8462 flags |= O_CLOEXEC;
8463#endif
8464
Steve Dowerb82e17e2019-05-23 08:45:22 -07008465 if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
8466 return -1;
8467 }
8468
Steve Dower8fc89802015-04-12 00:26:27 -04008469 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008470 do {
8471 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008472#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07008473 fd = _wopen(path->wide, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008474#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07008475#ifdef HAVE_OPENAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008476 if (dir_fd != DEFAULT_DIR_FD)
8477 fd = openat(dir_fd, path->narrow, flags, mode);
8478 else
Steve Dower6230aaf2016-09-09 09:03:15 -07008479#endif /* HAVE_OPENAT */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008480 fd = open(path->narrow, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008481#endif /* !MS_WINDOWS */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008482 Py_END_ALLOW_THREADS
8483 } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04008484 _Py_END_SUPPRESS_IPH
Guido van Rossum687dd131993-05-17 08:34:16 +00008485
Victor Stinnerd3ffd322015-09-15 10:11:03 +02008486 if (fd < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008487 if (!async_err)
8488 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Larry Hastings2f936352014-08-05 14:04:04 +10008489 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008490 }
8491
Victor Stinnerdaf45552013-08-28 00:53:59 +02008492#ifndef MS_WINDOWS
8493 if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
8494 close(fd);
Larry Hastings2f936352014-08-05 14:04:04 +10008495 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008496 }
8497#endif
8498
Larry Hastings2f936352014-08-05 14:04:04 +10008499 return fd;
8500}
8501
8502
8503/*[clinic input]
8504os.close
8505
8506 fd: int
8507
8508Close a file descriptor.
8509[clinic start generated code]*/
8510
Barry Warsaw53699e91996-12-10 23:23:01 +00008511static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008512os_close_impl(PyObject *module, int fd)
8513/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00008514{
Larry Hastings2f936352014-08-05 14:04:04 +10008515 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008516 /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
8517 * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
8518 * for more details.
8519 */
Victor Stinner8c62be82010-05-06 00:08:46 +00008520 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008521 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008522 res = close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04008523 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008524 Py_END_ALLOW_THREADS
8525 if (res < 0)
8526 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008527 Py_RETURN_NONE;
Guido van Rossum687dd131993-05-17 08:34:16 +00008528}
8529
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008530
Jakub Kulíke20134f2019-09-11 17:11:57 +02008531#ifdef HAVE_FDWALK
8532static int
8533_fdwalk_close_func(void *lohi, int fd)
8534{
8535 int lo = ((int *)lohi)[0];
8536 int hi = ((int *)lohi)[1];
8537
8538 if (fd >= hi)
8539 return 1;
8540 else if (fd >= lo)
8541 close(fd);
8542 return 0;
8543}
8544#endif /* HAVE_FDWALK */
8545
Larry Hastings2f936352014-08-05 14:04:04 +10008546/*[clinic input]
8547os.closerange
8548
8549 fd_low: int
8550 fd_high: int
8551 /
8552
8553Closes all file descriptors in [fd_low, fd_high), ignoring errors.
8554[clinic start generated code]*/
8555
Larry Hastings2f936352014-08-05 14:04:04 +10008556static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008557os_closerange_impl(PyObject *module, int fd_low, int fd_high)
8558/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008559{
Jakub Kulíke20134f2019-09-11 17:11:57 +02008560#ifdef HAVE_FDWALK
8561 int lohi[2];
8562#else
Larry Hastings2f936352014-08-05 14:04:04 +10008563 int i;
Jakub Kulíke20134f2019-09-11 17:11:57 +02008564#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00008565 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008566 _Py_BEGIN_SUPPRESS_IPH
Jakub Kulíke20134f2019-09-11 17:11:57 +02008567#ifdef HAVE_FDWALK
8568 lohi[0] = Py_MAX(fd_low, 0);
8569 lohi[1] = fd_high;
8570 fdwalk(_fdwalk_close_func, lohi);
8571#else
Benjamin Peterson207116b2016-09-08 11:28:06 -07008572 for (i = Py_MAX(fd_low, 0); i < fd_high; i++)
Steve Dower940f33a2016-09-08 11:21:54 -07008573 close(i);
Jakub Kulíke20134f2019-09-11 17:11:57 +02008574#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008575 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008576 Py_END_ALLOW_THREADS
8577 Py_RETURN_NONE;
Christian Heimesfdab48e2008-01-20 09:06:41 +00008578}
8579
8580
Larry Hastings2f936352014-08-05 14:04:04 +10008581/*[clinic input]
8582os.dup -> int
8583
8584 fd: int
8585 /
8586
8587Return a duplicate of a file descriptor.
8588[clinic start generated code]*/
8589
Larry Hastings2f936352014-08-05 14:04:04 +10008590static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008591os_dup_impl(PyObject *module, int fd)
8592/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008593{
8594 return _Py_dup(fd);
Guido van Rossum687dd131993-05-17 08:34:16 +00008595}
8596
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008597
Larry Hastings2f936352014-08-05 14:04:04 +10008598/*[clinic input]
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008599os.dup2 -> int
Larry Hastings2f936352014-08-05 14:04:04 +10008600 fd: int
8601 fd2: int
8602 inheritable: bool=True
8603
8604Duplicate file descriptor.
8605[clinic start generated code]*/
8606
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008607static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008608os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008609/*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008610{
Stéphane Wirtel3d86e482018-01-30 07:04:36 +01008611 int res = 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008612#if defined(HAVE_DUP3) && \
8613 !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
8614 /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
Alexey Izbyshevb3caf382018-02-20 10:25:46 +03008615 static int dup3_works = -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008616#endif
8617
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008618 if (fd < 0 || fd2 < 0) {
8619 posix_error();
8620 return -1;
8621 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008622
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008623 /* dup2() can fail with EINTR if the target FD is already open, because it
8624 * then has to be closed. See os_close_impl() for why we don't handle EINTR
8625 * upon close(), and therefore below.
8626 */
Victor Stinnerdaf45552013-08-28 00:53:59 +02008627#ifdef MS_WINDOWS
8628 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008629 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008630 res = dup2(fd, fd2);
Steve Dower8fc89802015-04-12 00:26:27 -04008631 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02008632 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008633 if (res < 0) {
8634 posix_error();
8635 return -1;
8636 }
8637 res = fd2; // msvcrt dup2 returns 0 on success.
Victor Stinnerdaf45552013-08-28 00:53:59 +02008638
8639 /* Character files like console cannot be make non-inheritable */
8640 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8641 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008642 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008643 }
8644
8645#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
8646 Py_BEGIN_ALLOW_THREADS
8647 if (!inheritable)
8648 res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
8649 else
8650 res = dup2(fd, fd2);
8651 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008652 if (res < 0) {
8653 posix_error();
8654 return -1;
8655 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008656
8657#else
8658
8659#ifdef HAVE_DUP3
8660 if (!inheritable && dup3_works != 0) {
8661 Py_BEGIN_ALLOW_THREADS
8662 res = dup3(fd, fd2, O_CLOEXEC);
8663 Py_END_ALLOW_THREADS
8664 if (res < 0) {
8665 if (dup3_works == -1)
8666 dup3_works = (errno != ENOSYS);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008667 if (dup3_works) {
8668 posix_error();
8669 return -1;
8670 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008671 }
8672 }
8673
8674 if (inheritable || dup3_works == 0)
8675 {
8676#endif
8677 Py_BEGIN_ALLOW_THREADS
8678 res = dup2(fd, fd2);
8679 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008680 if (res < 0) {
8681 posix_error();
8682 return -1;
8683 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008684
8685 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8686 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008687 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008688 }
8689#ifdef HAVE_DUP3
8690 }
8691#endif
8692
8693#endif
8694
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008695 return res;
Guido van Rossum687dd131993-05-17 08:34:16 +00008696}
8697
Larry Hastings2f936352014-08-05 14:04:04 +10008698
Ross Lagerwall7807c352011-03-17 20:20:30 +02008699#ifdef HAVE_LOCKF
Larry Hastings2f936352014-08-05 14:04:04 +10008700/*[clinic input]
8701os.lockf
8702
8703 fd: int
8704 An open file descriptor.
8705 command: int
8706 One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
8707 length: Py_off_t
8708 The number of bytes to lock, starting at the current position.
8709 /
8710
8711Apply, test or remove a POSIX lock on an open file descriptor.
8712
8713[clinic start generated code]*/
8714
Larry Hastings2f936352014-08-05 14:04:04 +10008715static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008716os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
8717/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008718{
8719 int res;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008720
8721 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008722 res = lockf(fd, command, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008723 Py_END_ALLOW_THREADS
8724
8725 if (res < 0)
8726 return posix_error();
8727
8728 Py_RETURN_NONE;
8729}
Larry Hastings2f936352014-08-05 14:04:04 +10008730#endif /* HAVE_LOCKF */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008731
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008732
Larry Hastings2f936352014-08-05 14:04:04 +10008733/*[clinic input]
8734os.lseek -> Py_off_t
8735
8736 fd: int
8737 position: Py_off_t
8738 how: int
8739 /
8740
8741Set the position of a file descriptor. Return the new position.
8742
8743Return the new cursor position in number of bytes
8744relative to the beginning of the file.
8745[clinic start generated code]*/
8746
Larry Hastings2f936352014-08-05 14:04:04 +10008747static Py_off_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008748os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
8749/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008750{
8751 Py_off_t result;
8752
Guido van Rossum687dd131993-05-17 08:34:16 +00008753#ifdef SEEK_SET
Victor Stinner8c62be82010-05-06 00:08:46 +00008754 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
8755 switch (how) {
Larry Hastings2f936352014-08-05 14:04:04 +10008756 case 0: how = SEEK_SET; break;
8757 case 1: how = SEEK_CUR; break;
8758 case 2: how = SEEK_END; break;
Victor Stinner8c62be82010-05-06 00:08:46 +00008759 }
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00008760#endif /* SEEK_END */
Guido van Rossum94f6f721999-01-06 18:42:14 +00008761
Victor Stinner8c62be82010-05-06 00:08:46 +00008762 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008763 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner14b9b112013-06-25 00:37:25 +02008764#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10008765 result = _lseeki64(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008766#else
Larry Hastings2f936352014-08-05 14:04:04 +10008767 result = lseek(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008768#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008769 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008770 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008771 if (result < 0)
8772 posix_error();
Guido van Rossum94f6f721999-01-06 18:42:14 +00008773
Larry Hastings2f936352014-08-05 14:04:04 +10008774 return result;
Guido van Rossum687dd131993-05-17 08:34:16 +00008775}
8776
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008777
Larry Hastings2f936352014-08-05 14:04:04 +10008778/*[clinic input]
8779os.read
8780 fd: int
8781 length: Py_ssize_t
8782 /
8783
8784Read from a file descriptor. Returns a bytes object.
8785[clinic start generated code]*/
8786
Larry Hastings2f936352014-08-05 14:04:04 +10008787static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008788os_read_impl(PyObject *module, int fd, Py_ssize_t length)
8789/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008790{
Victor Stinner8c62be82010-05-06 00:08:46 +00008791 Py_ssize_t n;
8792 PyObject *buffer;
Larry Hastings2f936352014-08-05 14:04:04 +10008793
8794 if (length < 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008795 errno = EINVAL;
8796 return posix_error();
8797 }
Larry Hastings2f936352014-08-05 14:04:04 +10008798
Victor Stinner9a0d7a72018-11-22 15:03:40 +01008799 length = Py_MIN(length, _PY_READ_MAX);
Larry Hastings2f936352014-08-05 14:04:04 +10008800
8801 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Victor Stinner8c62be82010-05-06 00:08:46 +00008802 if (buffer == NULL)
8803 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008804
Victor Stinner66aab0c2015-03-19 22:53:20 +01008805 n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
8806 if (n == -1) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008807 Py_DECREF(buffer);
Victor Stinner66aab0c2015-03-19 22:53:20 +01008808 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00008809 }
Larry Hastings2f936352014-08-05 14:04:04 +10008810
8811 if (n != length)
Victor Stinner8c62be82010-05-06 00:08:46 +00008812 _PyBytes_Resize(&buffer, n);
Larry Hastings2f936352014-08-05 14:04:04 +10008813
Victor Stinner8c62be82010-05-06 00:08:46 +00008814 return buffer;
Guido van Rossum687dd131993-05-17 08:34:16 +00008815}
8816
Ross Lagerwall7807c352011-03-17 20:20:30 +02008817#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008818 || defined(__APPLE__))) \
8819 || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
8820 || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
8821static int
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008822iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008823{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008824 Py_ssize_t i, j;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008825
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008826 *iov = PyMem_New(struct iovec, cnt);
8827 if (*iov == NULL) {
8828 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008829 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008830 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008831
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008832 *buf = PyMem_New(Py_buffer, cnt);
8833 if (*buf == NULL) {
8834 PyMem_Del(*iov);
8835 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008836 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008837 }
8838
8839 for (i = 0; i < cnt; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008840 PyObject *item = PySequence_GetItem(seq, i);
8841 if (item == NULL)
8842 goto fail;
8843 if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
8844 Py_DECREF(item);
8845 goto fail;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008846 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008847 Py_DECREF(item);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008848 (*iov)[i].iov_base = (*buf)[i].buf;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008849 (*iov)[i].iov_len = (*buf)[i].len;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008850 }
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008851 return 0;
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008852
8853fail:
8854 PyMem_Del(*iov);
8855 for (j = 0; j < i; j++) {
8856 PyBuffer_Release(&(*buf)[j]);
8857 }
8858 PyMem_Del(*buf);
Victor Stinner57ddf782014-01-08 15:21:28 +01008859 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008860}
8861
8862static void
8863iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
8864{
8865 int i;
8866 PyMem_Del(iov);
8867 for (i = 0; i < cnt; i++) {
8868 PyBuffer_Release(&buf[i]);
8869 }
8870 PyMem_Del(buf);
8871}
8872#endif
8873
Larry Hastings2f936352014-08-05 14:04:04 +10008874
Ross Lagerwall7807c352011-03-17 20:20:30 +02008875#ifdef HAVE_READV
Larry Hastings2f936352014-08-05 14:04:04 +10008876/*[clinic input]
8877os.readv -> Py_ssize_t
8878
8879 fd: int
8880 buffers: object
8881 /
8882
8883Read from a file descriptor fd into an iterable of buffers.
8884
8885The buffers should be mutable buffers accepting bytes.
8886readv will transfer data into each buffer until it is full
8887and then move on to the next buffer in the sequence to hold
8888the rest of the data.
8889
8890readv returns the total number of bytes read,
8891which may be less than the total capacity of all the buffers.
8892[clinic start generated code]*/
8893
Larry Hastings2f936352014-08-05 14:04:04 +10008894static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008895os_readv_impl(PyObject *module, int fd, PyObject *buffers)
8896/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008897{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008898 Py_ssize_t cnt, n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008899 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008900 struct iovec *iov;
8901 Py_buffer *buf;
8902
Larry Hastings2f936352014-08-05 14:04:04 +10008903 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008904 PyErr_SetString(PyExc_TypeError,
8905 "readv() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10008906 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008907 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02008908
Larry Hastings2f936352014-08-05 14:04:04 +10008909 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008910 if (cnt < 0)
8911 return -1;
Larry Hastings2f936352014-08-05 14:04:04 +10008912
8913 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
8914 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008915
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008916 do {
8917 Py_BEGIN_ALLOW_THREADS
8918 n = readv(fd, iov, cnt);
8919 Py_END_ALLOW_THREADS
8920 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02008921
8922 iov_cleanup(iov, buf, cnt);
Larry Hastings2f936352014-08-05 14:04:04 +10008923 if (n < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008924 if (!async_err)
8925 posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008926 return -1;
8927 }
Victor Stinner57ddf782014-01-08 15:21:28 +01008928
Larry Hastings2f936352014-08-05 14:04:04 +10008929 return n;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008930}
Larry Hastings2f936352014-08-05 14:04:04 +10008931#endif /* HAVE_READV */
8932
Ross Lagerwall7807c352011-03-17 20:20:30 +02008933
8934#ifdef HAVE_PREAD
Larry Hastings2f936352014-08-05 14:04:04 +10008935/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10008936os.pread
8937
8938 fd: int
Dong-hee Naad7736f2019-09-25 14:47:04 +09008939 length: Py_ssize_t
Larry Hastings2f936352014-08-05 14:04:04 +10008940 offset: Py_off_t
8941 /
8942
8943Read a number of bytes from a file descriptor starting at a particular offset.
8944
8945Read length bytes from file descriptor fd, starting at offset bytes from
8946the beginning of the file. The file offset remains unchanged.
8947[clinic start generated code]*/
8948
Larry Hastings2f936352014-08-05 14:04:04 +10008949static PyObject *
Dong-hee Naad7736f2019-09-25 14:47:04 +09008950os_pread_impl(PyObject *module, int fd, Py_ssize_t length, Py_off_t offset)
8951/*[clinic end generated code: output=3f875c1eef82e32f input=85cb4a5589627144]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008952{
Ross Lagerwall7807c352011-03-17 20:20:30 +02008953 Py_ssize_t n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008954 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008955 PyObject *buffer;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008956
Larry Hastings2f936352014-08-05 14:04:04 +10008957 if (length < 0) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008958 errno = EINVAL;
8959 return posix_error();
8960 }
Larry Hastings2f936352014-08-05 14:04:04 +10008961 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008962 if (buffer == NULL)
8963 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008964
8965 do {
8966 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008967 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008968 n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04008969 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008970 Py_END_ALLOW_THREADS
8971 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8972
Ross Lagerwall7807c352011-03-17 20:20:30 +02008973 if (n < 0) {
8974 Py_DECREF(buffer);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008975 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008976 }
Larry Hastings2f936352014-08-05 14:04:04 +10008977 if (n != length)
Ross Lagerwall7807c352011-03-17 20:20:30 +02008978 _PyBytes_Resize(&buffer, n);
8979 return buffer;
8980}
Larry Hastings2f936352014-08-05 14:04:04 +10008981#endif /* HAVE_PREAD */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008982
Pablo Galindo4defba32018-01-27 16:16:37 +00008983#if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
8984/*[clinic input]
8985os.preadv -> Py_ssize_t
8986
8987 fd: int
8988 buffers: object
8989 offset: Py_off_t
8990 flags: int = 0
8991 /
8992
8993Reads from a file descriptor into a number of mutable bytes-like objects.
8994
8995Combines the functionality of readv() and pread(). As readv(), it will
8996transfer data into each buffer until it is full and then move on to the next
8997buffer in the sequence to hold the rest of the data. Its fourth argument,
8998specifies the file offset at which the input operation is to be performed. It
8999will return the total number of bytes read (which can be less than the total
9000capacity of all the objects).
9001
9002The flags argument contains a bitwise OR of zero or more of the following flags:
9003
9004- RWF_HIPRI
9005- RWF_NOWAIT
9006
9007Using non-zero flags requires Linux 4.6 or newer.
9008[clinic start generated code]*/
9009
9010static Py_ssize_t
9011os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9012 int flags)
9013/*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
9014{
9015 Py_ssize_t cnt, n;
9016 int async_err = 0;
9017 struct iovec *iov;
9018 Py_buffer *buf;
9019
9020 if (!PySequence_Check(buffers)) {
9021 PyErr_SetString(PyExc_TypeError,
9022 "preadv2() arg 2 must be a sequence");
9023 return -1;
9024 }
9025
9026 cnt = PySequence_Size(buffers);
9027 if (cnt < 0) {
9028 return -1;
9029 }
9030
9031#ifndef HAVE_PREADV2
9032 if(flags != 0) {
9033 argument_unavailable_error("preadv2", "flags");
9034 return -1;
9035 }
9036#endif
9037
9038 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
9039 return -1;
9040 }
9041#ifdef HAVE_PREADV2
9042 do {
9043 Py_BEGIN_ALLOW_THREADS
9044 _Py_BEGIN_SUPPRESS_IPH
9045 n = preadv2(fd, iov, cnt, offset, flags);
9046 _Py_END_SUPPRESS_IPH
9047 Py_END_ALLOW_THREADS
9048 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9049#else
9050 do {
9051 Py_BEGIN_ALLOW_THREADS
9052 _Py_BEGIN_SUPPRESS_IPH
9053 n = preadv(fd, iov, cnt, offset);
9054 _Py_END_SUPPRESS_IPH
9055 Py_END_ALLOW_THREADS
9056 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9057#endif
9058
9059 iov_cleanup(iov, buf, cnt);
9060 if (n < 0) {
9061 if (!async_err) {
9062 posix_error();
9063 }
9064 return -1;
9065 }
9066
9067 return n;
9068}
9069#endif /* HAVE_PREADV */
9070
Larry Hastings2f936352014-08-05 14:04:04 +10009071
9072/*[clinic input]
9073os.write -> Py_ssize_t
9074
9075 fd: int
9076 data: Py_buffer
9077 /
9078
9079Write a bytes object to a file descriptor.
9080[clinic start generated code]*/
9081
Larry Hastings2f936352014-08-05 14:04:04 +10009082static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009083os_write_impl(PyObject *module, int fd, Py_buffer *data)
9084/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009085{
Victor Stinner66aab0c2015-03-19 22:53:20 +01009086 return _Py_write(fd, data->buf, data->len);
Ross Lagerwall7807c352011-03-17 20:20:30 +02009087}
9088
9089#ifdef HAVE_SENDFILE
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009090PyDoc_STRVAR(posix_sendfile__doc__,
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009091"sendfile(out_fd, in_fd, offset, count) -> byteswritten\n\
9092sendfile(out_fd, in_fd, offset, count[, headers][, trailers], flags=0)\n\
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009093 -> byteswritten\n\
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009094Copy count bytes from file descriptor in_fd to file descriptor out_fd.");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009095
Larry Hastings2f936352014-08-05 14:04:04 +10009096/* AC 3.5: don't bother converting, has optional group*/
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009097static PyObject *
9098posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict)
9099{
9100 int in, out;
9101 Py_ssize_t ret;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009102 int async_err = 0;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009103 off_t offset;
9104
9105#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
9106#ifndef __APPLE__
9107 Py_ssize_t len;
9108#endif
9109 PyObject *headers = NULL, *trailers = NULL;
9110 Py_buffer *hbuf, *tbuf;
9111 off_t sbytes;
9112 struct sf_hdtr sf;
9113 int flags = 0;
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009114 static char *keywords[] = {"out_fd", "in_fd",
Benjamin Petersond8a43b42011-02-26 21:35:16 +00009115 "offset", "count",
9116 "headers", "trailers", "flags", NULL};
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009117
Victor Stinner6ce0dbf2013-07-07 16:32:36 +02009118 sf.headers = NULL;
9119 sf.trailers = NULL;
9120
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009121#ifdef __APPLE__
9122 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&O&|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10009123 keywords, &out, &in, Py_off_t_converter, &offset, Py_off_t_converter, &sbytes,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009124#else
9125 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&n|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10009126 keywords, &out, &in, Py_off_t_converter, &offset, &len,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009127#endif
9128 &headers, &trailers, &flags))
9129 return NULL;
9130 if (headers != NULL) {
9131 if (!PySequence_Check(headers)) {
9132 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009133 "sendfile() headers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009134 return NULL;
9135 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009136 Py_ssize_t i = PySequence_Size(headers);
9137 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009138 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009139 if (i > INT_MAX) {
9140 PyErr_SetString(PyExc_OverflowError,
9141 "sendfile() header is too large");
9142 return NULL;
9143 }
9144 if (i > 0) {
9145 sf.hdr_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009146 if (iov_setup(&(sf.headers), &hbuf,
9147 headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009148 return NULL;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009149#ifdef __APPLE__
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009150 for (i = 0; i < sf.hdr_cnt; i++) {
9151 Py_ssize_t blen = sf.headers[i].iov_len;
9152# define OFF_T_MAX 0x7fffffffffffffff
9153 if (sbytes >= OFF_T_MAX - blen) {
9154 PyErr_SetString(PyExc_OverflowError,
9155 "sendfile() header is too large");
9156 return NULL;
9157 }
9158 sbytes += blen;
9159 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009160#endif
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009161 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009162 }
9163 }
9164 if (trailers != NULL) {
9165 if (!PySequence_Check(trailers)) {
9166 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009167 "sendfile() trailers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009168 return NULL;
9169 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009170 Py_ssize_t i = PySequence_Size(trailers);
9171 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009172 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009173 if (i > INT_MAX) {
9174 PyErr_SetString(PyExc_OverflowError,
9175 "sendfile() trailer is too large");
9176 return NULL;
9177 }
9178 if (i > 0) {
9179 sf.trl_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009180 if (iov_setup(&(sf.trailers), &tbuf,
9181 trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009182 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009183 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009184 }
9185 }
9186
Steve Dower8fc89802015-04-12 00:26:27 -04009187 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009188 do {
9189 Py_BEGIN_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009190#ifdef __APPLE__
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009191 ret = sendfile(in, out, offset, &sbytes, &sf, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009192#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009193 ret = sendfile(in, out, offset, len, &sf, &sbytes, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009194#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009195 Py_END_ALLOW_THREADS
9196 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04009197 _Py_END_SUPPRESS_IPH
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009198
9199 if (sf.headers != NULL)
9200 iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
9201 if (sf.trailers != NULL)
9202 iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
9203
9204 if (ret < 0) {
9205 if ((errno == EAGAIN) || (errno == EBUSY)) {
9206 if (sbytes != 0) {
9207 // some data has been sent
9208 goto done;
9209 }
9210 else {
9211 // no data has been sent; upper application is supposed
9212 // to retry on EAGAIN or EBUSY
9213 return posix_error();
9214 }
9215 }
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009216 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009217 }
9218 goto done;
9219
9220done:
9221 #if !defined(HAVE_LARGEFILE_SUPPORT)
9222 return Py_BuildValue("l", sbytes);
9223 #else
9224 return Py_BuildValue("L", sbytes);
9225 #endif
9226
9227#else
9228 Py_ssize_t count;
9229 PyObject *offobj;
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009230 static char *keywords[] = {"out_fd", "in_fd",
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009231 "offset", "count", NULL};
9232 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiOn:sendfile",
9233 keywords, &out, &in, &offobj, &count))
9234 return NULL;
Benjamin Peterson840ef8f2016-09-07 14:45:10 -07009235#ifdef __linux__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009236 if (offobj == Py_None) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009237 do {
9238 Py_BEGIN_ALLOW_THREADS
9239 ret = sendfile(out, in, NULL, count);
9240 Py_END_ALLOW_THREADS
9241 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009242 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009243 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodola'ff1a7352011-04-19 09:47:16 +02009244 return Py_BuildValue("n", ret);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009245 }
9246#endif
Larry Hastings2f936352014-08-05 14:04:04 +10009247 if (!Py_off_t_converter(offobj, &offset))
Antoine Pitroudcc20b82011-02-26 13:38:35 +00009248 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009249
9250 do {
9251 Py_BEGIN_ALLOW_THREADS
9252 ret = sendfile(out, in, &offset, count);
9253 Py_END_ALLOW_THREADS
9254 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009255 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009256 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009257 return Py_BuildValue("n", ret);
9258#endif
9259}
Larry Hastings2f936352014-08-05 14:04:04 +10009260#endif /* HAVE_SENDFILE */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009261
Larry Hastings2f936352014-08-05 14:04:04 +10009262
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009263#if defined(__APPLE__)
9264/*[clinic input]
9265os._fcopyfile
9266
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009267 in_fd: int
9268 out_fd: int
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009269 flags: int
9270 /
9271
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009272Efficiently copy content or metadata of 2 regular file descriptors (macOS).
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009273[clinic start generated code]*/
9274
9275static PyObject *
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009276os__fcopyfile_impl(PyObject *module, int in_fd, int out_fd, int flags)
9277/*[clinic end generated code: output=c9d1a35a992e401b input=1e34638a86948795]*/
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009278{
9279 int ret;
9280
9281 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009282 ret = fcopyfile(in_fd, out_fd, NULL, flags);
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009283 Py_END_ALLOW_THREADS
9284 if (ret < 0)
9285 return posix_error();
9286 Py_RETURN_NONE;
9287}
9288#endif
9289
9290
Larry Hastings2f936352014-08-05 14:04:04 +10009291/*[clinic input]
9292os.fstat
9293
9294 fd : int
9295
9296Perform a stat system call on the given file descriptor.
9297
9298Like stat(), but for an open file descriptor.
9299Equivalent to os.stat(fd).
9300[clinic start generated code]*/
9301
Larry Hastings2f936352014-08-05 14:04:04 +10009302static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009303os_fstat_impl(PyObject *module, int fd)
9304/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009305{
Victor Stinner8c62be82010-05-06 00:08:46 +00009306 STRUCT_STAT st;
9307 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009308 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009309
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009310 do {
9311 Py_BEGIN_ALLOW_THREADS
9312 res = FSTAT(fd, &st);
9313 Py_END_ALLOW_THREADS
9314 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner8c62be82010-05-06 00:08:46 +00009315 if (res != 0) {
Martin v. Löwis14694662006-02-03 12:54:16 +00009316#ifdef MS_WINDOWS
Victor Stinnerb024e842012-10-31 22:24:06 +01009317 return PyErr_SetFromWindowsErr(0);
Martin v. Löwis14694662006-02-03 12:54:16 +00009318#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009319 return (!async_err) ? posix_error() : NULL;
Martin v. Löwis14694662006-02-03 12:54:16 +00009320#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00009321 }
Tim Peters5aa91602002-01-30 05:46:57 +00009322
Victor Stinner4195b5c2012-02-08 23:03:19 +01009323 return _pystat_fromstructstat(&st);
Guido van Rossum687dd131993-05-17 08:34:16 +00009324}
9325
Larry Hastings2f936352014-08-05 14:04:04 +10009326
9327/*[clinic input]
9328os.isatty -> bool
9329 fd: int
9330 /
9331
9332Return True if the fd is connected to a terminal.
9333
9334Return True if the file descriptor is an open file descriptor
9335connected to the slave end of a terminal.
9336[clinic start generated code]*/
9337
Larry Hastings2f936352014-08-05 14:04:04 +10009338static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009339os_isatty_impl(PyObject *module, int fd)
9340/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009341{
Steve Dower8fc89802015-04-12 00:26:27 -04009342 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -04009343 _Py_BEGIN_SUPPRESS_IPH
9344 return_value = isatty(fd);
9345 _Py_END_SUPPRESS_IPH
9346 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +10009347}
9348
9349
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009350#ifdef HAVE_PIPE
Larry Hastings2f936352014-08-05 14:04:04 +10009351/*[clinic input]
9352os.pipe
9353
9354Create a pipe.
9355
9356Returns a tuple of two file descriptors:
9357 (read_fd, write_fd)
9358[clinic start generated code]*/
9359
Larry Hastings2f936352014-08-05 14:04:04 +10009360static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009361os_pipe_impl(PyObject *module)
9362/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00009363{
Victor Stinner8c62be82010-05-06 00:08:46 +00009364 int fds[2];
Victor Stinnerdaf45552013-08-28 00:53:59 +02009365#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00009366 HANDLE read, write;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009367 SECURITY_ATTRIBUTES attr;
Victor Stinner8c62be82010-05-06 00:08:46 +00009368 BOOL ok;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009369#else
9370 int res;
9371#endif
9372
9373#ifdef MS_WINDOWS
9374 attr.nLength = sizeof(attr);
9375 attr.lpSecurityDescriptor = NULL;
9376 attr.bInheritHandle = FALSE;
9377
9378 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08009379 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009380 ok = CreatePipe(&read, &write, &attr, 0);
9381 if (ok) {
Benjamin Petersonca470632016-09-06 13:47:26 -07009382 fds[0] = _open_osfhandle((intptr_t)read, _O_RDONLY);
9383 fds[1] = _open_osfhandle((intptr_t)write, _O_WRONLY);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009384 if (fds[0] == -1 || fds[1] == -1) {
9385 CloseHandle(read);
9386 CloseHandle(write);
9387 ok = 0;
9388 }
9389 }
Steve Dowerc3630612016-11-19 18:41:16 -08009390 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009391 Py_END_ALLOW_THREADS
9392
Victor Stinner8c62be82010-05-06 00:08:46 +00009393 if (!ok)
Victor Stinnerb024e842012-10-31 22:24:06 +01009394 return PyErr_SetFromWindowsErr(0);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009395#else
9396
9397#ifdef HAVE_PIPE2
9398 Py_BEGIN_ALLOW_THREADS
9399 res = pipe2(fds, O_CLOEXEC);
9400 Py_END_ALLOW_THREADS
9401
9402 if (res != 0 && errno == ENOSYS)
9403 {
9404#endif
9405 Py_BEGIN_ALLOW_THREADS
9406 res = pipe(fds);
9407 Py_END_ALLOW_THREADS
9408
9409 if (res == 0) {
9410 if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
9411 close(fds[0]);
9412 close(fds[1]);
9413 return NULL;
9414 }
9415 if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
9416 close(fds[0]);
9417 close(fds[1]);
9418 return NULL;
9419 }
9420 }
9421#ifdef HAVE_PIPE2
9422 }
9423#endif
9424
9425 if (res != 0)
9426 return PyErr_SetFromErrno(PyExc_OSError);
9427#endif /* !MS_WINDOWS */
9428 return Py_BuildValue("(ii)", fds[0], fds[1]);
Guido van Rossum687dd131993-05-17 08:34:16 +00009429}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009430#endif /* HAVE_PIPE */
9431
Larry Hastings2f936352014-08-05 14:04:04 +10009432
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009433#ifdef HAVE_PIPE2
Larry Hastings2f936352014-08-05 14:04:04 +10009434/*[clinic input]
9435os.pipe2
9436
9437 flags: int
9438 /
9439
9440Create a pipe with flags set atomically.
9441
9442Returns a tuple of two file descriptors:
9443 (read_fd, write_fd)
9444
9445flags can be constructed by ORing together one or more of these values:
9446O_NONBLOCK, O_CLOEXEC.
9447[clinic start generated code]*/
9448
Larry Hastings2f936352014-08-05 14:04:04 +10009449static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009450os_pipe2_impl(PyObject *module, int flags)
9451/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009452{
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009453 int fds[2];
9454 int res;
9455
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009456 res = pipe2(fds, flags);
9457 if (res != 0)
9458 return posix_error();
9459 return Py_BuildValue("(ii)", fds[0], fds[1]);
9460}
9461#endif /* HAVE_PIPE2 */
9462
Larry Hastings2f936352014-08-05 14:04:04 +10009463
Ross Lagerwall7807c352011-03-17 20:20:30 +02009464#ifdef HAVE_WRITEV
Larry Hastings2f936352014-08-05 14:04:04 +10009465/*[clinic input]
9466os.writev -> Py_ssize_t
9467 fd: int
9468 buffers: object
9469 /
9470
9471Iterate over buffers, and write the contents of each to a file descriptor.
9472
9473Returns the total number of bytes written.
9474buffers must be a sequence of bytes-like objects.
9475[clinic start generated code]*/
9476
Larry Hastings2f936352014-08-05 14:04:04 +10009477static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009478os_writev_impl(PyObject *module, int fd, PyObject *buffers)
9479/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009480{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009481 Py_ssize_t cnt;
Larry Hastings2f936352014-08-05 14:04:04 +10009482 Py_ssize_t result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009483 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009484 struct iovec *iov;
9485 Py_buffer *buf;
Larry Hastings2f936352014-08-05 14:04:04 +10009486
9487 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009488 PyErr_SetString(PyExc_TypeError,
9489 "writev() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009490 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009491 }
Larry Hastings2f936352014-08-05 14:04:04 +10009492 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009493 if (cnt < 0)
9494 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009495
Larry Hastings2f936352014-08-05 14:04:04 +10009496 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9497 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009498 }
9499
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009500 do {
9501 Py_BEGIN_ALLOW_THREADS
9502 result = writev(fd, iov, cnt);
9503 Py_END_ALLOW_THREADS
9504 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009505
9506 iov_cleanup(iov, buf, cnt);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009507 if (result < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009508 posix_error();
Victor Stinner57ddf782014-01-08 15:21:28 +01009509
Georg Brandl306336b2012-06-24 12:55:33 +02009510 return result;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009511}
Larry Hastings2f936352014-08-05 14:04:04 +10009512#endif /* HAVE_WRITEV */
9513
9514
9515#ifdef HAVE_PWRITE
9516/*[clinic input]
9517os.pwrite -> Py_ssize_t
9518
9519 fd: int
9520 buffer: Py_buffer
9521 offset: Py_off_t
9522 /
9523
9524Write bytes to a file descriptor starting at a particular offset.
9525
9526Write buffer to fd, starting at offset bytes from the beginning of
9527the file. Returns the number of bytes writte. Does not change the
9528current file offset.
9529[clinic start generated code]*/
9530
Larry Hastings2f936352014-08-05 14:04:04 +10009531static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009532os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
9533/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009534{
9535 Py_ssize_t size;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009536 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009537
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009538 do {
9539 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009540 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009541 size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009542 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009543 Py_END_ALLOW_THREADS
9544 } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +10009545
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009546 if (size < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009547 posix_error();
9548 return size;
9549}
9550#endif /* HAVE_PWRITE */
9551
Pablo Galindo4defba32018-01-27 16:16:37 +00009552#if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
9553/*[clinic input]
9554os.pwritev -> Py_ssize_t
9555
9556 fd: int
9557 buffers: object
9558 offset: Py_off_t
9559 flags: int = 0
9560 /
9561
9562Writes the contents of bytes-like objects to a file descriptor at a given offset.
9563
9564Combines the functionality of writev() and pwrite(). All buffers must be a sequence
9565of bytes-like objects. Buffers are processed in array order. Entire contents of first
9566buffer is written before proceeding to second, and so on. The operating system may
9567set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
9568This function writes the contents of each object to the file descriptor and returns
9569the total number of bytes written.
9570
9571The flags argument contains a bitwise OR of zero or more of the following flags:
9572
9573- RWF_DSYNC
9574- RWF_SYNC
9575
9576Using non-zero flags requires Linux 4.7 or newer.
9577[clinic start generated code]*/
9578
9579static Py_ssize_t
9580os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9581 int flags)
9582/*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=803dc5ddbf0cfd3b]*/
9583{
9584 Py_ssize_t cnt;
9585 Py_ssize_t result;
9586 int async_err = 0;
9587 struct iovec *iov;
9588 Py_buffer *buf;
9589
9590 if (!PySequence_Check(buffers)) {
9591 PyErr_SetString(PyExc_TypeError,
9592 "pwritev() arg 2 must be a sequence");
9593 return -1;
9594 }
9595
9596 cnt = PySequence_Size(buffers);
9597 if (cnt < 0) {
9598 return -1;
9599 }
9600
9601#ifndef HAVE_PWRITEV2
9602 if(flags != 0) {
9603 argument_unavailable_error("pwritev2", "flags");
9604 return -1;
9605 }
9606#endif
9607
9608 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9609 return -1;
9610 }
9611#ifdef HAVE_PWRITEV2
9612 do {
9613 Py_BEGIN_ALLOW_THREADS
9614 _Py_BEGIN_SUPPRESS_IPH
9615 result = pwritev2(fd, iov, cnt, offset, flags);
9616 _Py_END_SUPPRESS_IPH
9617 Py_END_ALLOW_THREADS
9618 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9619#else
9620 do {
9621 Py_BEGIN_ALLOW_THREADS
9622 _Py_BEGIN_SUPPRESS_IPH
9623 result = pwritev(fd, iov, cnt, offset);
9624 _Py_END_SUPPRESS_IPH
9625 Py_END_ALLOW_THREADS
9626 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9627#endif
9628
9629 iov_cleanup(iov, buf, cnt);
9630 if (result < 0) {
9631 if (!async_err) {
9632 posix_error();
9633 }
9634 return -1;
9635 }
9636
9637 return result;
9638}
9639#endif /* HAVE_PWRITEV */
9640
Pablo Galindoaac4d032019-05-31 19:39:47 +01009641#ifdef HAVE_COPY_FILE_RANGE
9642/*[clinic input]
9643
9644os.copy_file_range
9645 src: int
9646 Source file descriptor.
9647 dst: int
9648 Destination file descriptor.
9649 count: Py_ssize_t
9650 Number of bytes to copy.
9651 offset_src: object = None
9652 Starting offset in src.
9653 offset_dst: object = None
9654 Starting offset in dst.
9655
9656Copy count bytes from one file descriptor to another.
9657
9658If offset_src is None, then src is read from the current position;
9659respectively for offset_dst.
9660[clinic start generated code]*/
9661
9662static PyObject *
9663os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
9664 PyObject *offset_src, PyObject *offset_dst)
9665/*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
9666{
9667 off_t offset_src_val, offset_dst_val;
9668 off_t *p_offset_src = NULL;
9669 off_t *p_offset_dst = NULL;
9670 Py_ssize_t ret;
9671 int async_err = 0;
9672 /* The flags argument is provided to allow
9673 * for future extensions and currently must be to 0. */
9674 int flags = 0;
Pablo Galindo4defba32018-01-27 16:16:37 +00009675
9676
Pablo Galindoaac4d032019-05-31 19:39:47 +01009677 if (count < 0) {
9678 PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
9679 return NULL;
9680 }
9681
9682 if (offset_src != Py_None) {
9683 if (!Py_off_t_converter(offset_src, &offset_src_val)) {
9684 return NULL;
9685 }
9686 p_offset_src = &offset_src_val;
9687 }
9688
9689 if (offset_dst != Py_None) {
9690 if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
9691 return NULL;
9692 }
9693 p_offset_dst = &offset_dst_val;
9694 }
9695
9696 do {
9697 Py_BEGIN_ALLOW_THREADS
9698 ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
9699 Py_END_ALLOW_THREADS
9700 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9701
9702 if (ret < 0) {
9703 return (!async_err) ? posix_error() : NULL;
9704 }
9705
9706 return PyLong_FromSsize_t(ret);
9707}
9708#endif /* HAVE_COPY_FILE_RANGE*/
Larry Hastings2f936352014-08-05 14:04:04 +10009709
9710#ifdef HAVE_MKFIFO
9711/*[clinic input]
9712os.mkfifo
9713
9714 path: path_t
9715 mode: int=0o666
9716 *
9717 dir_fd: dir_fd(requires='mkfifoat')=None
9718
9719Create a "fifo" (a POSIX named pipe).
9720
9721If dir_fd is not None, it should be a file descriptor open to a directory,
9722 and path should be relative; path will then be relative to that directory.
9723dir_fd may not be implemented on your platform.
9724 If it is unavailable, using it will raise a NotImplementedError.
9725[clinic start generated code]*/
9726
Larry Hastings2f936352014-08-05 14:04:04 +10009727static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009728os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
9729/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009730{
9731 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009732 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009733
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009734 do {
9735 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009736#ifdef HAVE_MKFIFOAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009737 if (dir_fd != DEFAULT_DIR_FD)
9738 result = mkfifoat(dir_fd, path->narrow, mode);
9739 else
Ross Lagerwall7807c352011-03-17 20:20:30 +02009740#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009741 result = mkfifo(path->narrow, mode);
9742 Py_END_ALLOW_THREADS
9743 } while (result != 0 && errno == EINTR &&
9744 !(async_err = PyErr_CheckSignals()));
9745 if (result != 0)
9746 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009747
9748 Py_RETURN_NONE;
9749}
9750#endif /* HAVE_MKFIFO */
9751
9752
9753#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
9754/*[clinic input]
9755os.mknod
9756
9757 path: path_t
9758 mode: int=0o600
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009759 device: dev_t=0
Larry Hastings2f936352014-08-05 14:04:04 +10009760 *
9761 dir_fd: dir_fd(requires='mknodat')=None
9762
9763Create a node in the file system.
9764
9765Create a node in the file system (file, device special file or named pipe)
9766at path. mode specifies both the permissions to use and the
9767type of node to be created, being combined (bitwise OR) with one of
9768S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
9769device defines the newly created device special file (probably using
9770os.makedev()). Otherwise device is ignored.
9771
9772If dir_fd is not None, it should be a file descriptor open to a directory,
9773 and path should be relative; path will then be relative to that directory.
9774dir_fd may not be implemented on your platform.
9775 If it is unavailable, using it will raise a NotImplementedError.
9776[clinic start generated code]*/
9777
Larry Hastings2f936352014-08-05 14:04:04 +10009778static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009779os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
Larry Hastings89964c42015-04-14 18:07:59 -04009780 int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009781/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009782{
9783 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009784 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009785
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009786 do {
9787 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009788#ifdef HAVE_MKNODAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009789 if (dir_fd != DEFAULT_DIR_FD)
9790 result = mknodat(dir_fd, path->narrow, mode, device);
9791 else
Larry Hastings2f936352014-08-05 14:04:04 +10009792#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009793 result = mknod(path->narrow, mode, device);
9794 Py_END_ALLOW_THREADS
9795 } while (result != 0 && errno == EINTR &&
9796 !(async_err = PyErr_CheckSignals()));
9797 if (result != 0)
9798 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009799
9800 Py_RETURN_NONE;
9801}
9802#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
9803
9804
9805#ifdef HAVE_DEVICE_MACROS
9806/*[clinic input]
9807os.major -> unsigned_int
9808
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009809 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009810 /
9811
9812Extracts a device major number from a raw device number.
9813[clinic start generated code]*/
9814
Larry Hastings2f936352014-08-05 14:04:04 +10009815static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009816os_major_impl(PyObject *module, dev_t device)
9817/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009818{
9819 return major(device);
9820}
9821
9822
9823/*[clinic input]
9824os.minor -> unsigned_int
9825
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009826 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009827 /
9828
9829Extracts a device minor number from a raw device number.
9830[clinic start generated code]*/
9831
Larry Hastings2f936352014-08-05 14:04:04 +10009832static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009833os_minor_impl(PyObject *module, dev_t device)
9834/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009835{
9836 return minor(device);
9837}
9838
9839
9840/*[clinic input]
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009841os.makedev -> dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009842
9843 major: int
9844 minor: int
9845 /
9846
9847Composes a raw device number from the major and minor device numbers.
9848[clinic start generated code]*/
9849
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009850static dev_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009851os_makedev_impl(PyObject *module, int major, int minor)
9852/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009853{
9854 return makedev(major, minor);
9855}
9856#endif /* HAVE_DEVICE_MACROS */
9857
9858
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009859#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009860/*[clinic input]
9861os.ftruncate
9862
9863 fd: int
9864 length: Py_off_t
9865 /
9866
9867Truncate a file, specified by file descriptor, to a specific length.
9868[clinic start generated code]*/
9869
Larry Hastings2f936352014-08-05 14:04:04 +10009870static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009871os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
9872/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009873{
9874 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009875 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009876
Steve Dowerb82e17e2019-05-23 08:45:22 -07009877 if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
9878 return NULL;
9879 }
9880
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009881 do {
9882 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009883 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009884#ifdef MS_WINDOWS
9885 result = _chsize_s(fd, length);
9886#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009887 result = ftruncate(fd, length);
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009888#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009889 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009890 Py_END_ALLOW_THREADS
9891 } while (result != 0 && errno == EINTR &&
9892 !(async_err = PyErr_CheckSignals()));
9893 if (result != 0)
9894 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009895 Py_RETURN_NONE;
9896}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009897#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009898
9899
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009900#if defined HAVE_TRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009901/*[clinic input]
9902os.truncate
9903 path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
9904 length: Py_off_t
9905
9906Truncate a file, specified by path, to a specific length.
9907
9908On some platforms, path may also be specified as an open file descriptor.
9909 If this functionality is unavailable, using it raises an exception.
9910[clinic start generated code]*/
9911
Larry Hastings2f936352014-08-05 14:04:04 +10009912static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009913os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
9914/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009915{
9916 int result;
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009917#ifdef MS_WINDOWS
9918 int fd;
9919#endif
9920
9921 if (path->fd != -1)
9922 return os_ftruncate_impl(module, path->fd, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009923
Steve Dowerb82e17e2019-05-23 08:45:22 -07009924 if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
9925 return NULL;
9926 }
9927
Larry Hastings2f936352014-08-05 14:04:04 +10009928 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009929 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009930#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07009931 fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
Victor Stinnercc0bbbc2015-04-25 00:21:52 +02009932 if (fd < 0)
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009933 result = -1;
9934 else {
9935 result = _chsize_s(fd, length);
9936 close(fd);
9937 if (result < 0)
9938 errno = result;
9939 }
9940#else
9941 result = truncate(path->narrow, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009942#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009943 _Py_END_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10009944 Py_END_ALLOW_THREADS
9945 if (result < 0)
Alexey Izbyshev83460312018-10-20 03:28:22 +03009946 return posix_path_error(path);
Larry Hastings2f936352014-08-05 14:04:04 +10009947
9948 Py_RETURN_NONE;
9949}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009950#endif /* HAVE_TRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009951
Ross Lagerwall7807c352011-03-17 20:20:30 +02009952
Victor Stinnerd6b17692014-09-30 12:20:05 +02009953/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
9954 and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
9955 defined, which is the case in Python on AIX. AIX bug report:
9956 http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
9957#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
9958# define POSIX_FADVISE_AIX_BUG
9959#endif
9960
Victor Stinnerec39e262014-09-30 12:35:58 +02009961
Victor Stinnerd6b17692014-09-30 12:20:05 +02009962#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +10009963/*[clinic input]
9964os.posix_fallocate
9965
9966 fd: int
9967 offset: Py_off_t
9968 length: Py_off_t
9969 /
9970
9971Ensure a file has allocated at least a particular number of bytes on disk.
9972
9973Ensure that the file specified by fd encompasses a range of bytes
9974starting at offset bytes from the beginning and continuing for length bytes.
9975[clinic start generated code]*/
9976
Larry Hastings2f936352014-08-05 14:04:04 +10009977static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009978os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -04009979 Py_off_t length)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009980/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009981{
9982 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009983 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009984
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009985 do {
9986 Py_BEGIN_ALLOW_THREADS
9987 result = posix_fallocate(fd, offset, length);
9988 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +05009989 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
9990
9991 if (result == 0)
9992 Py_RETURN_NONE;
9993
9994 if (async_err)
9995 return NULL;
9996
9997 errno = result;
9998 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +02009999}
Victor Stinnerec39e262014-09-30 12:35:58 +020010000#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
Larry Hastings2f936352014-08-05 14:04:04 +100010001
Ross Lagerwall7807c352011-03-17 20:20:30 +020010002
Victor Stinnerd6b17692014-09-30 12:20:05 +020010003#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +100010004/*[clinic input]
10005os.posix_fadvise
10006
10007 fd: int
10008 offset: Py_off_t
10009 length: Py_off_t
10010 advice: int
10011 /
10012
10013Announce an intention to access data in a specific pattern.
10014
10015Announce an intention to access data in a specific pattern, thus allowing
10016the kernel to make optimizations.
10017The advice applies to the region of the file specified by fd starting at
10018offset and continuing for length bytes.
10019advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
10020POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
10021POSIX_FADV_DONTNEED.
10022[clinic start generated code]*/
10023
Larry Hastings2f936352014-08-05 14:04:04 +100010024static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010025os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -040010026 Py_off_t length, int advice)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010027/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010028{
10029 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010030 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010031
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010032 do {
10033 Py_BEGIN_ALLOW_THREADS
10034 result = posix_fadvise(fd, offset, length, advice);
10035 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010036 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10037
10038 if (result == 0)
10039 Py_RETURN_NONE;
10040
10041 if (async_err)
10042 return NULL;
10043
10044 errno = result;
10045 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010046}
Victor Stinnerec39e262014-09-30 12:35:58 +020010047#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
Ross Lagerwall7807c352011-03-17 20:20:30 +020010048
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010049#ifdef HAVE_PUTENV
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000010050
Larry Hastings2f936352014-08-05 14:04:04 +100010051static void
10052posix_putenv_garbage_setitem(PyObject *name, PyObject *value)
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010053{
Larry Hastings2f936352014-08-05 14:04:04 +100010054 /* Install the first arg and newstr in posix_putenv_garbage;
10055 * this will cause previous value to be collected. This has to
10056 * happen after the real putenv() call because the old value
10057 * was still accessible until then. */
Eddie Elizondob3966632019-11-05 07:16:14 -080010058 if (PyDict_SetItem(_posixstate_global->posix_putenv_garbage, name, value))
Larry Hastings2f936352014-08-05 14:04:04 +100010059 /* really not much we can do; just leak */
10060 PyErr_Clear();
10061 else
10062 Py_DECREF(value);
10063}
10064
10065
Thomas Hellerf78f12a2007-11-08 19:33:05 +000010066#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010067/*[clinic input]
10068os.putenv
10069
10070 name: unicode
10071 value: unicode
10072 /
10073
10074Change or add an environment variable.
10075[clinic start generated code]*/
10076
Larry Hastings2f936352014-08-05 14:04:04 +100010077static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010078os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10079/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010080{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030010081 const wchar_t *env;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +030010082 Py_ssize_t size;
Larry Hastings2f936352014-08-05 14:04:04 +100010083
Serhiy Storchaka77703942017-06-25 07:33:01 +030010084 /* Search from index 1 because on Windows starting '=' is allowed for
10085 defining hidden environment variables. */
10086 if (PyUnicode_GET_LENGTH(name) == 0 ||
10087 PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
10088 {
10089 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10090 return NULL;
10091 }
Larry Hastings2f936352014-08-05 14:04:04 +100010092 PyObject *unicode = PyUnicode_FromFormat("%U=%U", name, value);
10093 if (unicode == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010094 return NULL;
Victor Stinner84ae1182010-05-06 22:05:07 +000010095 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +030010096
10097 env = PyUnicode_AsUnicodeAndSize(unicode, &size);
10098 if (env == NULL)
10099 goto error;
10100 if (size > _MAX_ENV) {
Victor Stinner65170952011-11-22 22:16:17 +010010101 PyErr_Format(PyExc_ValueError,
10102 "the environment variable is longer than %u characters",
10103 _MAX_ENV);
10104 goto error;
10105 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +030010106 if (wcslen(env) != (size_t)size) {
10107 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnereb5657a2011-09-30 01:44:27 +020010108 goto error;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +030010109 }
10110
Larry Hastings2f936352014-08-05 14:04:04 +100010111 if (_wputenv(env)) {
Victor Stinner8c62be82010-05-06 00:08:46 +000010112 posix_error();
Victor Stinner84ae1182010-05-06 22:05:07 +000010113 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +000010114 }
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010115
Larry Hastings2f936352014-08-05 14:04:04 +100010116 posix_putenv_garbage_setitem(name, unicode);
Victor Stinner84ae1182010-05-06 22:05:07 +000010117 Py_RETURN_NONE;
10118
10119error:
Larry Hastings2f936352014-08-05 14:04:04 +100010120 Py_DECREF(unicode);
Victor Stinner84ae1182010-05-06 22:05:07 +000010121 return NULL;
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010122}
Larry Hastings2f936352014-08-05 14:04:04 +100010123#else /* MS_WINDOWS */
10124/*[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{
10138 PyObject *bytes = NULL;
10139 char *env;
Serhiy Storchaka77703942017-06-25 07:33:01 +030010140 const char *name_string = PyBytes_AS_STRING(name);
10141 const char *value_string = PyBytes_AS_STRING(value);
Larry Hastings2f936352014-08-05 14:04:04 +100010142
Serhiy Storchaka77703942017-06-25 07:33:01 +030010143 if (strchr(name_string, '=') != NULL) {
10144 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10145 return NULL;
10146 }
Larry Hastings2f936352014-08-05 14:04:04 +100010147 bytes = PyBytes_FromFormat("%s=%s", name_string, value_string);
10148 if (bytes == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010149 return NULL;
10150 }
10151
10152 env = PyBytes_AS_STRING(bytes);
10153 if (putenv(env)) {
10154 Py_DECREF(bytes);
10155 return posix_error();
10156 }
10157
10158 posix_putenv_garbage_setitem(name, bytes);
10159 Py_RETURN_NONE;
10160}
10161#endif /* MS_WINDOWS */
10162#endif /* HAVE_PUTENV */
10163
10164
10165#ifdef HAVE_UNSETENV
10166/*[clinic input]
10167os.unsetenv
10168 name: FSConverter
10169 /
10170
10171Delete an environment variable.
10172[clinic start generated code]*/
10173
Larry Hastings2f936352014-08-05 14:04:04 +100010174static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010175os_unsetenv_impl(PyObject *module, PyObject *name)
10176/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010177{
Victor Stinner984890f2011-11-24 13:53:38 +010010178#ifndef HAVE_BROKEN_UNSETENV
Victor Stinner60b385e2011-11-22 22:01:28 +010010179 int err;
Victor Stinner984890f2011-11-24 13:53:38 +010010180#endif
Victor Stinner84ae1182010-05-06 22:05:07 +000010181
Victor Stinner984890f2011-11-24 13:53:38 +010010182#ifdef HAVE_BROKEN_UNSETENV
10183 unsetenv(PyBytes_AS_STRING(name));
10184#else
Victor Stinner65170952011-11-22 22:16:17 +010010185 err = unsetenv(PyBytes_AS_STRING(name));
Larry Hastings2f936352014-08-05 14:04:04 +100010186 if (err)
Victor Stinner60b385e2011-11-22 22:01:28 +010010187 return posix_error();
Victor Stinner984890f2011-11-24 13:53:38 +010010188#endif
Guido van Rossumc524d952001-10-19 01:31:59 +000010189
Victor Stinner8c62be82010-05-06 00:08:46 +000010190 /* Remove the key from posix_putenv_garbage;
10191 * this will cause it to be collected. This has to
10192 * happen after the real unsetenv() call because the
10193 * old value was still accessible until then.
10194 */
Eddie Elizondob3966632019-11-05 07:16:14 -080010195 if (PyDict_DelItem(_posixstate(module)->posix_putenv_garbage, name)) {
Victor Stinner8c62be82010-05-06 00:08:46 +000010196 /* really not much we can do; just leak */
Serhiy Storchakaa24107b2019-02-25 17:59:46 +020010197 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
10198 return NULL;
10199 }
Victor Stinner8c62be82010-05-06 00:08:46 +000010200 PyErr_Clear();
10201 }
Victor Stinner84ae1182010-05-06 22:05:07 +000010202 Py_RETURN_NONE;
Guido van Rossumc524d952001-10-19 01:31:59 +000010203}
Larry Hastings2f936352014-08-05 14:04:04 +100010204#endif /* HAVE_UNSETENV */
Guido van Rossumc524d952001-10-19 01:31:59 +000010205
Larry Hastings2f936352014-08-05 14:04:04 +100010206
10207/*[clinic input]
10208os.strerror
10209
10210 code: int
10211 /
10212
10213Translate an error code to a message string.
10214[clinic start generated code]*/
10215
Larry Hastings2f936352014-08-05 14:04:04 +100010216static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010217os_strerror_impl(PyObject *module, int code)
10218/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010219{
10220 char *message = strerror(code);
Victor Stinner8c62be82010-05-06 00:08:46 +000010221 if (message == NULL) {
10222 PyErr_SetString(PyExc_ValueError,
10223 "strerror() argument out of range");
10224 return NULL;
10225 }
Victor Stinner1b579672011-12-17 05:47:23 +010010226 return PyUnicode_DecodeLocale(message, "surrogateescape");
Guido van Rossumb6a47161997-09-15 22:54:34 +000010227}
Guido van Rossumb6a47161997-09-15 22:54:34 +000010228
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010229
Guido van Rossumc9641791998-08-04 15:26:23 +000010230#ifdef HAVE_SYS_WAIT_H
Fred Drake106c1a02002-04-23 15:58:02 +000010231#ifdef WCOREDUMP
Larry Hastings2f936352014-08-05 14:04:04 +100010232/*[clinic input]
10233os.WCOREDUMP -> bool
10234
10235 status: int
10236 /
10237
10238Return True if the process returning status was dumped to a core file.
10239[clinic start generated code]*/
10240
Larry Hastings2f936352014-08-05 14:04:04 +100010241static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010242os_WCOREDUMP_impl(PyObject *module, int status)
10243/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010244{
10245 WAIT_TYPE wait_status;
10246 WAIT_STATUS_INT(wait_status) = status;
10247 return WCOREDUMP(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010248}
10249#endif /* WCOREDUMP */
10250
Larry Hastings2f936352014-08-05 14:04:04 +100010251
Fred Drake106c1a02002-04-23 15:58:02 +000010252#ifdef WIFCONTINUED
Larry Hastings2f936352014-08-05 14:04:04 +100010253/*[clinic input]
10254os.WIFCONTINUED -> bool
10255
10256 status: int
10257
10258Return True if a particular process was continued from a job control stop.
10259
10260Return True if the process returning status was continued from a
10261job control stop.
10262[clinic start generated code]*/
10263
Larry Hastings2f936352014-08-05 14:04:04 +100010264static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010265os_WIFCONTINUED_impl(PyObject *module, int status)
10266/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010267{
10268 WAIT_TYPE wait_status;
10269 WAIT_STATUS_INT(wait_status) = status;
10270 return WIFCONTINUED(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010271}
10272#endif /* WIFCONTINUED */
10273
Larry Hastings2f936352014-08-05 14:04:04 +100010274
Guido van Rossumc9641791998-08-04 15:26:23 +000010275#ifdef WIFSTOPPED
Larry Hastings2f936352014-08-05 14:04:04 +100010276/*[clinic input]
10277os.WIFSTOPPED -> bool
10278
10279 status: int
10280
10281Return True if the process returning status was stopped.
10282[clinic start generated code]*/
10283
Larry Hastings2f936352014-08-05 14:04:04 +100010284static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010285os_WIFSTOPPED_impl(PyObject *module, int status)
10286/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010287{
10288 WAIT_TYPE wait_status;
10289 WAIT_STATUS_INT(wait_status) = status;
10290 return WIFSTOPPED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010291}
10292#endif /* WIFSTOPPED */
10293
Larry Hastings2f936352014-08-05 14:04:04 +100010294
Guido van Rossumc9641791998-08-04 15:26:23 +000010295#ifdef WIFSIGNALED
Larry Hastings2f936352014-08-05 14:04:04 +100010296/*[clinic input]
10297os.WIFSIGNALED -> bool
10298
10299 status: int
10300
10301Return True if the process returning status was terminated by a signal.
10302[clinic start generated code]*/
10303
Larry Hastings2f936352014-08-05 14:04:04 +100010304static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010305os_WIFSIGNALED_impl(PyObject *module, int status)
10306/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010307{
10308 WAIT_TYPE wait_status;
10309 WAIT_STATUS_INT(wait_status) = status;
10310 return WIFSIGNALED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010311}
10312#endif /* WIFSIGNALED */
10313
Larry Hastings2f936352014-08-05 14:04:04 +100010314
Guido van Rossumc9641791998-08-04 15:26:23 +000010315#ifdef WIFEXITED
Larry Hastings2f936352014-08-05 14:04:04 +100010316/*[clinic input]
10317os.WIFEXITED -> bool
10318
10319 status: int
10320
10321Return True if the process returning status exited via the exit() system call.
10322[clinic start generated code]*/
10323
Larry Hastings2f936352014-08-05 14:04:04 +100010324static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010325os_WIFEXITED_impl(PyObject *module, int status)
10326/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010327{
10328 WAIT_TYPE wait_status;
10329 WAIT_STATUS_INT(wait_status) = status;
10330 return WIFEXITED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010331}
10332#endif /* WIFEXITED */
10333
Larry Hastings2f936352014-08-05 14:04:04 +100010334
Guido van Rossum54ecc3d1999-01-27 17:53:11 +000010335#ifdef WEXITSTATUS
Larry Hastings2f936352014-08-05 14:04:04 +100010336/*[clinic input]
10337os.WEXITSTATUS -> int
10338
10339 status: int
10340
10341Return the process return code from status.
10342[clinic start generated code]*/
10343
Larry Hastings2f936352014-08-05 14:04:04 +100010344static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010345os_WEXITSTATUS_impl(PyObject *module, int status)
10346/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010347{
10348 WAIT_TYPE wait_status;
10349 WAIT_STATUS_INT(wait_status) = status;
10350 return WEXITSTATUS(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010351}
10352#endif /* WEXITSTATUS */
10353
Larry Hastings2f936352014-08-05 14:04:04 +100010354
Guido van Rossumc9641791998-08-04 15:26:23 +000010355#ifdef WTERMSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010356/*[clinic input]
10357os.WTERMSIG -> int
10358
10359 status: int
10360
10361Return the signal that terminated the process that provided the status value.
10362[clinic start generated code]*/
10363
Larry Hastings2f936352014-08-05 14:04:04 +100010364static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010365os_WTERMSIG_impl(PyObject *module, int status)
10366/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010367{
10368 WAIT_TYPE wait_status;
10369 WAIT_STATUS_INT(wait_status) = status;
10370 return WTERMSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010371}
10372#endif /* WTERMSIG */
10373
Larry Hastings2f936352014-08-05 14:04:04 +100010374
Guido van Rossumc9641791998-08-04 15:26:23 +000010375#ifdef WSTOPSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010376/*[clinic input]
10377os.WSTOPSIG -> int
10378
10379 status: int
10380
10381Return the signal that stopped the process that provided the status value.
10382[clinic start generated code]*/
10383
Larry Hastings2f936352014-08-05 14:04:04 +100010384static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010385os_WSTOPSIG_impl(PyObject *module, int status)
10386/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010387{
10388 WAIT_TYPE wait_status;
10389 WAIT_STATUS_INT(wait_status) = status;
10390 return WSTOPSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010391}
10392#endif /* WSTOPSIG */
Guido van Rossumc9641791998-08-04 15:26:23 +000010393#endif /* HAVE_SYS_WAIT_H */
10394
10395
Thomas Wouters477c8d52006-05-27 19:21:47 +000010396#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossumd5753e11999-10-19 13:29:23 +000010397#ifdef _SCO_DS
10398/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
10399 needed definitions in sys/statvfs.h */
10400#define _SVID3
10401#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000010402#include <sys/statvfs.h>
10403
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010404static PyObject*
10405_pystatvfs_fromstructstatvfs(struct statvfs st) {
Eddie Elizondob3966632019-11-05 07:16:14 -080010406 PyObject *StatVFSResultType = _posixstate_global->StatVFSResultType;
10407 PyObject *v = PyStructSequence_New((PyTypeObject *)StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000010408 if (v == NULL)
10409 return NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010410
10411#if !defined(HAVE_LARGEFILE_SUPPORT)
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, PyLong_FromLong((long) st.f_blocks));
10415 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
10416 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
10417 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
10418 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
10419 PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
10420 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10421 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010422#else
Victor Stinner8c62be82010-05-06 00:08:46 +000010423 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10424 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10425 PyStructSequence_SET_ITEM(v, 2,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010426 PyLong_FromLongLong((long long) st.f_blocks));
Victor Stinner8c62be82010-05-06 00:08:46 +000010427 PyStructSequence_SET_ITEM(v, 3,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010428 PyLong_FromLongLong((long long) st.f_bfree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010429 PyStructSequence_SET_ITEM(v, 4,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010430 PyLong_FromLongLong((long long) st.f_bavail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010431 PyStructSequence_SET_ITEM(v, 5,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010432 PyLong_FromLongLong((long long) st.f_files));
Victor Stinner8c62be82010-05-06 00:08:46 +000010433 PyStructSequence_SET_ITEM(v, 6,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010434 PyLong_FromLongLong((long long) st.f_ffree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010435 PyStructSequence_SET_ITEM(v, 7,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010436 PyLong_FromLongLong((long long) st.f_favail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010437 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10438 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010439#endif
Michael Felt502d5512018-01-05 13:01:58 +010010440/* The _ALL_SOURCE feature test macro defines f_fsid as a structure
10441 * (issue #32390). */
10442#if defined(_AIX) && defined(_ALL_SOURCE)
10443 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
10444#else
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +010010445 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid));
Michael Felt502d5512018-01-05 13:01:58 +010010446#endif
Victor Stinnerf0a7bac2013-10-30 18:55:24 +010010447 if (PyErr_Occurred()) {
10448 Py_DECREF(v);
10449 return NULL;
10450 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010451
Victor Stinner8c62be82010-05-06 00:08:46 +000010452 return v;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010453}
10454
Larry Hastings2f936352014-08-05 14:04:04 +100010455
10456/*[clinic input]
10457os.fstatvfs
10458 fd: int
10459 /
10460
10461Perform an fstatvfs system call on the given fd.
10462
10463Equivalent to statvfs(fd).
10464[clinic start generated code]*/
10465
Larry Hastings2f936352014-08-05 14:04:04 +100010466static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010467os_fstatvfs_impl(PyObject *module, int fd)
10468/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010469{
10470 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010471 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010472 struct statvfs st;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010473
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010474 do {
10475 Py_BEGIN_ALLOW_THREADS
10476 result = fstatvfs(fd, &st);
10477 Py_END_ALLOW_THREADS
10478 } while (result != 0 && errno == EINTR &&
10479 !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +100010480 if (result != 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010481 return (!async_err) ? posix_error() : NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010482
Victor Stinner8c62be82010-05-06 00:08:46 +000010483 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010484}
Larry Hastings2f936352014-08-05 14:04:04 +100010485#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
Guido van Rossum94f6f721999-01-06 18:42:14 +000010486
10487
Thomas Wouters477c8d52006-05-27 19:21:47 +000010488#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossum94f6f721999-01-06 18:42:14 +000010489#include <sys/statvfs.h>
Larry Hastings2f936352014-08-05 14:04:04 +100010490/*[clinic input]
10491os.statvfs
Guido van Rossum94f6f721999-01-06 18:42:14 +000010492
Larry Hastings2f936352014-08-05 14:04:04 +100010493 path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
10494
10495Perform a statvfs system call on the given path.
10496
10497path may always be specified as a string.
10498On some platforms, path may also be specified as an open file descriptor.
10499 If this functionality is unavailable, using it raises an exception.
10500[clinic start generated code]*/
10501
Larry Hastings2f936352014-08-05 14:04:04 +100010502static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010503os_statvfs_impl(PyObject *module, path_t *path)
10504/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010505{
10506 int result;
10507 struct statvfs st;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010508
10509 Py_BEGIN_ALLOW_THREADS
10510#ifdef HAVE_FSTATVFS
Larry Hastings2f936352014-08-05 14:04:04 +100010511 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -070010512#ifdef __APPLE__
10513 /* handle weak-linking on Mac OS X 10.3 */
10514 if (fstatvfs == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010515 fd_specified("statvfs", path->fd);
10516 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010517 }
10518#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010519 result = fstatvfs(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010520 }
10521 else
10522#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010523 result = statvfs(path->narrow, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010524 Py_END_ALLOW_THREADS
10525
10526 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100010527 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010528 }
10529
Larry Hastings2f936352014-08-05 14:04:04 +100010530 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010531}
Larry Hastings2f936352014-08-05 14:04:04 +100010532#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
10533
Guido van Rossum94f6f721999-01-06 18:42:14 +000010534
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010535#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010536/*[clinic input]
10537os._getdiskusage
10538
Steve Dower23ad6d02018-02-22 10:39:10 -080010539 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +100010540
10541Return disk usage statistics about the given path as a (total, free) tuple.
10542[clinic start generated code]*/
10543
Larry Hastings2f936352014-08-05 14:04:04 +100010544static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -080010545os__getdiskusage_impl(PyObject *module, path_t *path)
10546/*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010547{
10548 BOOL retval;
10549 ULARGE_INTEGER _, total, free;
Joe Pamerc8c02492018-09-25 10:57:36 -040010550 DWORD err = 0;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010551
10552 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -080010553 retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010554 Py_END_ALLOW_THREADS
Joe Pamerc8c02492018-09-25 10:57:36 -040010555 if (retval == 0) {
10556 if (GetLastError() == ERROR_DIRECTORY) {
10557 wchar_t *dir_path = NULL;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010558
Joe Pamerc8c02492018-09-25 10:57:36 -040010559 dir_path = PyMem_New(wchar_t, path->length + 1);
10560 if (dir_path == NULL) {
10561 return PyErr_NoMemory();
10562 }
10563
10564 wcscpy_s(dir_path, path->length + 1, path->wide);
10565
10566 if (_dirnameW(dir_path) != -1) {
10567 Py_BEGIN_ALLOW_THREADS
10568 retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
10569 Py_END_ALLOW_THREADS
10570 }
10571 /* Record the last error in case it's modified by PyMem_Free. */
10572 err = GetLastError();
10573 PyMem_Free(dir_path);
10574 if (retval) {
10575 goto success;
10576 }
10577 }
10578 return PyErr_SetFromWindowsErr(err);
10579 }
10580
10581success:
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010582 return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
10583}
Larry Hastings2f936352014-08-05 14:04:04 +100010584#endif /* MS_WINDOWS */
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010585
10586
Fred Drakec9680921999-12-13 16:37:25 +000010587/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
10588 * It maps strings representing configuration variable names to
10589 * integer values, allowing those functions to be called with the
Thomas Wouters7e474022000-07-16 12:04:32 +000010590 * magic names instead of polluting the module's namespace with tons of
Fred Drake12c6e2d1999-12-14 21:25:03 +000010591 * rarely-used constants. There are three separate tables that use
10592 * these definitions.
Fred Drakebec628d1999-12-15 18:31:10 +000010593 *
10594 * This code is always included, even if none of the interfaces that
10595 * need it are included. The #if hackery needed to avoid it would be
10596 * sufficiently pervasive that it's not worth the loss of readability.
Fred Drakec9680921999-12-13 16:37:25 +000010597 */
10598struct constdef {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020010599 const char *name;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010600 int value;
Fred Drakec9680921999-12-13 16:37:25 +000010601};
10602
Fred Drake12c6e2d1999-12-14 21:25:03 +000010603static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010604conv_confname(PyObject *arg, int *valuep, struct constdef *table,
Guido van Rossum7d5baac2007-08-27 23:24:46 +000010605 size_t tablesize)
Fred Drake12c6e2d1999-12-14 21:25:03 +000010606{
Christian Heimes217cfd12007-12-02 14:31:20 +000010607 if (PyLong_Check(arg)) {
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010608 int value = _PyLong_AsInt(arg);
10609 if (value == -1 && PyErr_Occurred())
10610 return 0;
10611 *valuep = value;
Stefan Krah0e803b32010-11-26 16:16:47 +000010612 return 1;
Fred Drake12c6e2d1999-12-14 21:25:03 +000010613 }
Guido van Rossumbce56a62007-05-10 18:04:33 +000010614 else {
Stefan Krah0e803b32010-11-26 16:16:47 +000010615 /* look up the value in the table using a binary search */
10616 size_t lo = 0;
10617 size_t mid;
10618 size_t hi = tablesize;
10619 int cmp;
10620 const char *confname;
10621 if (!PyUnicode_Check(arg)) {
10622 PyErr_SetString(PyExc_TypeError,
10623 "configuration names must be strings or integers");
10624 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010625 }
Serhiy Storchaka06515832016-11-20 09:13:07 +020010626 confname = PyUnicode_AsUTF8(arg);
Stefan Krah0e803b32010-11-26 16:16:47 +000010627 if (confname == NULL)
10628 return 0;
10629 while (lo < hi) {
10630 mid = (lo + hi) / 2;
10631 cmp = strcmp(confname, table[mid].name);
10632 if (cmp < 0)
10633 hi = mid;
10634 else if (cmp > 0)
10635 lo = mid + 1;
10636 else {
10637 *valuep = table[mid].value;
10638 return 1;
10639 }
10640 }
10641 PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
10642 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010643 }
Fred Drake12c6e2d1999-12-14 21:25:03 +000010644}
10645
10646
10647#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
10648static struct constdef posix_constants_pathconf[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010649#ifdef _PC_ABI_AIO_XFER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010650 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000010651#endif
10652#ifdef _PC_ABI_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010653 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010654#endif
Fred Drakec9680921999-12-13 16:37:25 +000010655#ifdef _PC_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010656 {"PC_ASYNC_IO", _PC_ASYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010657#endif
10658#ifdef _PC_CHOWN_RESTRICTED
Victor Stinner8c62be82010-05-06 00:08:46 +000010659 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
Fred Drakec9680921999-12-13 16:37:25 +000010660#endif
10661#ifdef _PC_FILESIZEBITS
Victor Stinner8c62be82010-05-06 00:08:46 +000010662 {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
Fred Drakec9680921999-12-13 16:37:25 +000010663#endif
10664#ifdef _PC_LAST
Victor Stinner8c62be82010-05-06 00:08:46 +000010665 {"PC_LAST", _PC_LAST},
Fred Drakec9680921999-12-13 16:37:25 +000010666#endif
10667#ifdef _PC_LINK_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010668 {"PC_LINK_MAX", _PC_LINK_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010669#endif
10670#ifdef _PC_MAX_CANON
Victor Stinner8c62be82010-05-06 00:08:46 +000010671 {"PC_MAX_CANON", _PC_MAX_CANON},
Fred Drakec9680921999-12-13 16:37:25 +000010672#endif
10673#ifdef _PC_MAX_INPUT
Victor Stinner8c62be82010-05-06 00:08:46 +000010674 {"PC_MAX_INPUT", _PC_MAX_INPUT},
Fred Drakec9680921999-12-13 16:37:25 +000010675#endif
10676#ifdef _PC_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010677 {"PC_NAME_MAX", _PC_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010678#endif
10679#ifdef _PC_NO_TRUNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010680 {"PC_NO_TRUNC", _PC_NO_TRUNC},
Fred Drakec9680921999-12-13 16:37:25 +000010681#endif
10682#ifdef _PC_PATH_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010683 {"PC_PATH_MAX", _PC_PATH_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010684#endif
10685#ifdef _PC_PIPE_BUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010686 {"PC_PIPE_BUF", _PC_PIPE_BUF},
Fred Drakec9680921999-12-13 16:37:25 +000010687#endif
10688#ifdef _PC_PRIO_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010689 {"PC_PRIO_IO", _PC_PRIO_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010690#endif
10691#ifdef _PC_SOCK_MAXBUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010692 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
Fred Drakec9680921999-12-13 16:37:25 +000010693#endif
10694#ifdef _PC_SYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010695 {"PC_SYNC_IO", _PC_SYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010696#endif
10697#ifdef _PC_VDISABLE
Victor Stinner8c62be82010-05-06 00:08:46 +000010698 {"PC_VDISABLE", _PC_VDISABLE},
Fred Drakec9680921999-12-13 16:37:25 +000010699#endif
Jesus Cea7e9065c2010-10-25 13:02:04 +000010700#ifdef _PC_ACL_ENABLED
10701 {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
10702#endif
10703#ifdef _PC_MIN_HOLE_SIZE
10704 {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
10705#endif
10706#ifdef _PC_ALLOC_SIZE_MIN
10707 {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
10708#endif
10709#ifdef _PC_REC_INCR_XFER_SIZE
10710 {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
10711#endif
10712#ifdef _PC_REC_MAX_XFER_SIZE
10713 {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
10714#endif
10715#ifdef _PC_REC_MIN_XFER_SIZE
10716 {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
10717#endif
10718#ifdef _PC_REC_XFER_ALIGN
10719 {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
10720#endif
10721#ifdef _PC_SYMLINK_MAX
10722 {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
10723#endif
10724#ifdef _PC_XATTR_ENABLED
10725 {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
10726#endif
10727#ifdef _PC_XATTR_EXISTS
10728 {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
10729#endif
10730#ifdef _PC_TIMESTAMP_RESOLUTION
10731 {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
10732#endif
Fred Drakec9680921999-12-13 16:37:25 +000010733};
10734
Fred Drakec9680921999-12-13 16:37:25 +000010735static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010736conv_path_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010737{
10738 return conv_confname(arg, valuep, posix_constants_pathconf,
10739 sizeof(posix_constants_pathconf)
10740 / sizeof(struct constdef));
10741}
10742#endif
10743
Larry Hastings2f936352014-08-05 14:04:04 +100010744
Fred Drakec9680921999-12-13 16:37:25 +000010745#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010746/*[clinic input]
10747os.fpathconf -> long
10748
10749 fd: int
10750 name: path_confname
10751 /
10752
10753Return the configuration limit name for the file descriptor fd.
10754
10755If there is no limit, return -1.
10756[clinic start generated code]*/
10757
Larry Hastings2f936352014-08-05 14:04:04 +100010758static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010759os_fpathconf_impl(PyObject *module, int fd, int name)
10760/*[clinic end generated code: output=d5b7042425fc3e21 input=5942a024d3777810]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010761{
10762 long limit;
10763
10764 errno = 0;
10765 limit = fpathconf(fd, name);
10766 if (limit == -1 && errno != 0)
10767 posix_error();
10768
10769 return limit;
10770}
10771#endif /* HAVE_FPATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010772
10773
10774#ifdef HAVE_PATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010775/*[clinic input]
10776os.pathconf -> long
10777 path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
10778 name: path_confname
10779
10780Return the configuration limit name for the file or directory path.
10781
10782If there is no limit, return -1.
10783On some platforms, path may also be specified as an open file descriptor.
10784 If this functionality is unavailable, using it raises an exception.
10785[clinic start generated code]*/
10786
Larry Hastings2f936352014-08-05 14:04:04 +100010787static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010788os_pathconf_impl(PyObject *module, path_t *path, int name)
10789/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010790{
Victor Stinner8c62be82010-05-06 00:08:46 +000010791 long limit;
Fred Drakec9680921999-12-13 16:37:25 +000010792
Victor Stinner8c62be82010-05-06 00:08:46 +000010793 errno = 0;
Georg Brandl306336b2012-06-24 12:55:33 +020010794#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010795 if (path->fd != -1)
10796 limit = fpathconf(path->fd, name);
Georg Brandl306336b2012-06-24 12:55:33 +020010797 else
10798#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010799 limit = pathconf(path->narrow, name);
Victor Stinner8c62be82010-05-06 00:08:46 +000010800 if (limit == -1 && errno != 0) {
10801 if (errno == EINVAL)
Stefan Krah99439262010-11-26 12:58:05 +000010802 /* could be a path or name problem */
10803 posix_error();
Fred Drakec9680921999-12-13 16:37:25 +000010804 else
Larry Hastings2f936352014-08-05 14:04:04 +100010805 path_error(path);
Victor Stinner8c62be82010-05-06 00:08:46 +000010806 }
Larry Hastings2f936352014-08-05 14:04:04 +100010807
10808 return limit;
Fred Drakec9680921999-12-13 16:37:25 +000010809}
Larry Hastings2f936352014-08-05 14:04:04 +100010810#endif /* HAVE_PATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010811
10812#ifdef HAVE_CONFSTR
10813static struct constdef posix_constants_confstr[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010814#ifdef _CS_ARCHITECTURE
Victor Stinner8c62be82010-05-06 00:08:46 +000010815 {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
Fred Draked86ed291999-12-15 15:34:33 +000010816#endif
Mark Dickinson876d7c82010-04-16 12:47:52 +000010817#ifdef _CS_GNU_LIBC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010818 {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010819#endif
10820#ifdef _CS_GNU_LIBPTHREAD_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010821 {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010822#endif
Fred Draked86ed291999-12-15 15:34:33 +000010823#ifdef _CS_HOSTNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010824 {"CS_HOSTNAME", _CS_HOSTNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010825#endif
10826#ifdef _CS_HW_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010827 {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010828#endif
10829#ifdef _CS_HW_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010830 {"CS_HW_SERIAL", _CS_HW_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010831#endif
10832#ifdef _CS_INITTAB_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010833 {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010834#endif
Fred Drakec9680921999-12-13 16:37:25 +000010835#ifdef _CS_LFS64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010836 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010837#endif
10838#ifdef _CS_LFS64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010839 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010840#endif
10841#ifdef _CS_LFS64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010842 {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010843#endif
10844#ifdef _CS_LFS64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010845 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010846#endif
10847#ifdef _CS_LFS_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010848 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010849#endif
10850#ifdef _CS_LFS_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010851 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010852#endif
10853#ifdef _CS_LFS_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010854 {"CS_LFS_LIBS", _CS_LFS_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010855#endif
10856#ifdef _CS_LFS_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010857 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010858#endif
Fred Draked86ed291999-12-15 15:34:33 +000010859#ifdef _CS_MACHINE
Victor Stinner8c62be82010-05-06 00:08:46 +000010860 {"CS_MACHINE", _CS_MACHINE},
Fred Draked86ed291999-12-15 15:34:33 +000010861#endif
Fred Drakec9680921999-12-13 16:37:25 +000010862#ifdef _CS_PATH
Victor Stinner8c62be82010-05-06 00:08:46 +000010863 {"CS_PATH", _CS_PATH},
Fred Drakec9680921999-12-13 16:37:25 +000010864#endif
Fred Draked86ed291999-12-15 15:34:33 +000010865#ifdef _CS_RELEASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010866 {"CS_RELEASE", _CS_RELEASE},
Fred Draked86ed291999-12-15 15:34:33 +000010867#endif
10868#ifdef _CS_SRPC_DOMAIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010869 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
Fred Draked86ed291999-12-15 15:34:33 +000010870#endif
10871#ifdef _CS_SYSNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010872 {"CS_SYSNAME", _CS_SYSNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010873#endif
10874#ifdef _CS_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010875 {"CS_VERSION", _CS_VERSION},
Fred Draked86ed291999-12-15 15:34:33 +000010876#endif
Fred Drakec9680921999-12-13 16:37:25 +000010877#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010878 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010879#endif
10880#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010881 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010882#endif
10883#ifdef _CS_XBS5_ILP32_OFF32_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010884 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010885#endif
10886#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010887 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010888#endif
10889#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010890 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010891#endif
10892#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010893 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010894#endif
10895#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010896 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010897#endif
10898#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010899 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010900#endif
10901#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010902 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010903#endif
10904#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010905 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010906#endif
10907#ifdef _CS_XBS5_LP64_OFF64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010908 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010909#endif
10910#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010911 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010912#endif
10913#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010914 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010915#endif
10916#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010917 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010918#endif
10919#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010920 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010921#endif
10922#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010923 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010924#endif
Fred Draked86ed291999-12-15 15:34:33 +000010925#ifdef _MIPS_CS_AVAIL_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010926 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010927#endif
10928#ifdef _MIPS_CS_BASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010929 {"MIPS_CS_BASE", _MIPS_CS_BASE},
Fred Draked86ed291999-12-15 15:34:33 +000010930#endif
10931#ifdef _MIPS_CS_HOSTID
Victor Stinner8c62be82010-05-06 00:08:46 +000010932 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
Fred Draked86ed291999-12-15 15:34:33 +000010933#endif
10934#ifdef _MIPS_CS_HW_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010935 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010936#endif
10937#ifdef _MIPS_CS_NUM_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010938 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010939#endif
10940#ifdef _MIPS_CS_OSREL_MAJ
Victor Stinner8c62be82010-05-06 00:08:46 +000010941 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
Fred Draked86ed291999-12-15 15:34:33 +000010942#endif
10943#ifdef _MIPS_CS_OSREL_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010944 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
Fred Draked86ed291999-12-15 15:34:33 +000010945#endif
10946#ifdef _MIPS_CS_OSREL_PATCH
Victor Stinner8c62be82010-05-06 00:08:46 +000010947 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
Fred Draked86ed291999-12-15 15:34:33 +000010948#endif
10949#ifdef _MIPS_CS_OS_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010950 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010951#endif
10952#ifdef _MIPS_CS_OS_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010953 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010954#endif
10955#ifdef _MIPS_CS_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010956 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010957#endif
10958#ifdef _MIPS_CS_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010959 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010960#endif
10961#ifdef _MIPS_CS_VENDOR
Victor Stinner8c62be82010-05-06 00:08:46 +000010962 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
Fred Draked86ed291999-12-15 15:34:33 +000010963#endif
Fred Drakec9680921999-12-13 16:37:25 +000010964};
10965
10966static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010967conv_confstr_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010968{
10969 return conv_confname(arg, valuep, posix_constants_confstr,
10970 sizeof(posix_constants_confstr)
10971 / sizeof(struct constdef));
10972}
10973
Larry Hastings2f936352014-08-05 14:04:04 +100010974
10975/*[clinic input]
10976os.confstr
10977
10978 name: confstr_confname
10979 /
10980
10981Return a string-valued system configuration variable.
10982[clinic start generated code]*/
10983
Larry Hastings2f936352014-08-05 14:04:04 +100010984static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010985os_confstr_impl(PyObject *module, int name)
10986/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
Fred Drakec9680921999-12-13 16:37:25 +000010987{
10988 PyObject *result = NULL;
Victor Stinnercb043522010-09-10 23:49:04 +000010989 char buffer[255];
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020010990 size_t len;
Fred Drakec9680921999-12-13 16:37:25 +000010991
Victor Stinnercb043522010-09-10 23:49:04 +000010992 errno = 0;
10993 len = confstr(name, buffer, sizeof(buffer));
10994 if (len == 0) {
10995 if (errno) {
10996 posix_error();
10997 return NULL;
Fred Drakec9680921999-12-13 16:37:25 +000010998 }
10999 else {
Victor Stinnercb043522010-09-10 23:49:04 +000011000 Py_RETURN_NONE;
Fred Drakec9680921999-12-13 16:37:25 +000011001 }
11002 }
Victor Stinnercb043522010-09-10 23:49:04 +000011003
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011004 if (len >= sizeof(buffer)) {
Victor Stinnercbc18f32014-12-05 22:51:51 +010011005 size_t len2;
Victor Stinnercb043522010-09-10 23:49:04 +000011006 char *buf = PyMem_Malloc(len);
11007 if (buf == NULL)
11008 return PyErr_NoMemory();
Victor Stinnercbc18f32014-12-05 22:51:51 +010011009 len2 = confstr(name, buf, len);
11010 assert(len == len2);
Christian Heimes8714cfd2015-04-21 10:57:41 +020011011 result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
Victor Stinnercb043522010-09-10 23:49:04 +000011012 PyMem_Free(buf);
11013 }
11014 else
11015 result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
Fred Drakec9680921999-12-13 16:37:25 +000011016 return result;
11017}
Larry Hastings2f936352014-08-05 14:04:04 +100011018#endif /* HAVE_CONFSTR */
Fred Drakec9680921999-12-13 16:37:25 +000011019
11020
11021#ifdef HAVE_SYSCONF
11022static struct constdef posix_constants_sysconf[] = {
11023#ifdef _SC_2_CHAR_TERM
Victor Stinner8c62be82010-05-06 00:08:46 +000011024 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
Fred Drakec9680921999-12-13 16:37:25 +000011025#endif
11026#ifdef _SC_2_C_BIND
Victor Stinner8c62be82010-05-06 00:08:46 +000011027 {"SC_2_C_BIND", _SC_2_C_BIND},
Fred Drakec9680921999-12-13 16:37:25 +000011028#endif
11029#ifdef _SC_2_C_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011030 {"SC_2_C_DEV", _SC_2_C_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011031#endif
11032#ifdef _SC_2_C_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011033 {"SC_2_C_VERSION", _SC_2_C_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011034#endif
11035#ifdef _SC_2_FORT_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011036 {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011037#endif
11038#ifdef _SC_2_FORT_RUN
Victor Stinner8c62be82010-05-06 00:08:46 +000011039 {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
Fred Drakec9680921999-12-13 16:37:25 +000011040#endif
11041#ifdef _SC_2_LOCALEDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000011042 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
Fred Drakec9680921999-12-13 16:37:25 +000011043#endif
11044#ifdef _SC_2_SW_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011045 {"SC_2_SW_DEV", _SC_2_SW_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011046#endif
11047#ifdef _SC_2_UPE
Victor Stinner8c62be82010-05-06 00:08:46 +000011048 {"SC_2_UPE", _SC_2_UPE},
Fred Drakec9680921999-12-13 16:37:25 +000011049#endif
11050#ifdef _SC_2_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011051 {"SC_2_VERSION", _SC_2_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011052#endif
Fred Draked86ed291999-12-15 15:34:33 +000011053#ifdef _SC_ABI_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011054 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
Fred Draked86ed291999-12-15 15:34:33 +000011055#endif
11056#ifdef _SC_ACL
Victor Stinner8c62be82010-05-06 00:08:46 +000011057 {"SC_ACL", _SC_ACL},
Fred Draked86ed291999-12-15 15:34:33 +000011058#endif
Fred Drakec9680921999-12-13 16:37:25 +000011059#ifdef _SC_AIO_LISTIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011060 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011061#endif
Fred Drakec9680921999-12-13 16:37:25 +000011062#ifdef _SC_AIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011063 {"SC_AIO_MAX", _SC_AIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011064#endif
11065#ifdef _SC_AIO_PRIO_DELTA_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011066 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011067#endif
11068#ifdef _SC_ARG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011069 {"SC_ARG_MAX", _SC_ARG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011070#endif
11071#ifdef _SC_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011072 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011073#endif
11074#ifdef _SC_ATEXIT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011075 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011076#endif
Fred Draked86ed291999-12-15 15:34:33 +000011077#ifdef _SC_AUDIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011078 {"SC_AUDIT", _SC_AUDIT},
Fred Draked86ed291999-12-15 15:34:33 +000011079#endif
Fred Drakec9680921999-12-13 16:37:25 +000011080#ifdef _SC_AVPHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011081 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011082#endif
11083#ifdef _SC_BC_BASE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011084 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011085#endif
11086#ifdef _SC_BC_DIM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011087 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011088#endif
11089#ifdef _SC_BC_SCALE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011090 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011091#endif
11092#ifdef _SC_BC_STRING_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011093 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011094#endif
Fred Draked86ed291999-12-15 15:34:33 +000011095#ifdef _SC_CAP
Victor Stinner8c62be82010-05-06 00:08:46 +000011096 {"SC_CAP", _SC_CAP},
Fred Draked86ed291999-12-15 15:34:33 +000011097#endif
Fred Drakec9680921999-12-13 16:37:25 +000011098#ifdef _SC_CHARCLASS_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011099 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011100#endif
11101#ifdef _SC_CHAR_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011102 {"SC_CHAR_BIT", _SC_CHAR_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011103#endif
11104#ifdef _SC_CHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011105 {"SC_CHAR_MAX", _SC_CHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011106#endif
11107#ifdef _SC_CHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011108 {"SC_CHAR_MIN", _SC_CHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011109#endif
11110#ifdef _SC_CHILD_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011111 {"SC_CHILD_MAX", _SC_CHILD_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011112#endif
11113#ifdef _SC_CLK_TCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011114 {"SC_CLK_TCK", _SC_CLK_TCK},
Fred Drakec9680921999-12-13 16:37:25 +000011115#endif
11116#ifdef _SC_COHER_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011117 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011118#endif
11119#ifdef _SC_COLL_WEIGHTS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011120 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011121#endif
11122#ifdef _SC_DCACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011123 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011124#endif
11125#ifdef _SC_DCACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011126 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011127#endif
11128#ifdef _SC_DCACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011129 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011130#endif
11131#ifdef _SC_DCACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011132 {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011133#endif
11134#ifdef _SC_DCACHE_TBLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011135 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011136#endif
11137#ifdef _SC_DELAYTIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011138 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011139#endif
11140#ifdef _SC_EQUIV_CLASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011141 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011142#endif
11143#ifdef _SC_EXPR_NEST_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011144 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011145#endif
11146#ifdef _SC_FSYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000011147 {"SC_FSYNC", _SC_FSYNC},
Fred Drakec9680921999-12-13 16:37:25 +000011148#endif
11149#ifdef _SC_GETGR_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011150 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011151#endif
11152#ifdef _SC_GETPW_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011153 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011154#endif
11155#ifdef _SC_ICACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011156 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011157#endif
11158#ifdef _SC_ICACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011159 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011160#endif
11161#ifdef _SC_ICACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011162 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011163#endif
11164#ifdef _SC_ICACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011165 {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011166#endif
Fred Draked86ed291999-12-15 15:34:33 +000011167#ifdef _SC_INF
Victor Stinner8c62be82010-05-06 00:08:46 +000011168 {"SC_INF", _SC_INF},
Fred Draked86ed291999-12-15 15:34:33 +000011169#endif
Fred Drakec9680921999-12-13 16:37:25 +000011170#ifdef _SC_INT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011171 {"SC_INT_MAX", _SC_INT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011172#endif
11173#ifdef _SC_INT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011174 {"SC_INT_MIN", _SC_INT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011175#endif
11176#ifdef _SC_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011177 {"SC_IOV_MAX", _SC_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011178#endif
Fred Draked86ed291999-12-15 15:34:33 +000011179#ifdef _SC_IP_SECOPTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011180 {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
Fred Draked86ed291999-12-15 15:34:33 +000011181#endif
Fred Drakec9680921999-12-13 16:37:25 +000011182#ifdef _SC_JOB_CONTROL
Victor Stinner8c62be82010-05-06 00:08:46 +000011183 {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
Fred Drakec9680921999-12-13 16:37:25 +000011184#endif
Fred Draked86ed291999-12-15 15:34:33 +000011185#ifdef _SC_KERN_POINTERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011186 {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
Fred Draked86ed291999-12-15 15:34:33 +000011187#endif
11188#ifdef _SC_KERN_SIM
Victor Stinner8c62be82010-05-06 00:08:46 +000011189 {"SC_KERN_SIM", _SC_KERN_SIM},
Fred Draked86ed291999-12-15 15:34:33 +000011190#endif
Fred Drakec9680921999-12-13 16:37:25 +000011191#ifdef _SC_LINE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011192 {"SC_LINE_MAX", _SC_LINE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011193#endif
11194#ifdef _SC_LOGIN_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011195 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011196#endif
11197#ifdef _SC_LOGNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011198 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011199#endif
11200#ifdef _SC_LONG_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011201 {"SC_LONG_BIT", _SC_LONG_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011202#endif
Fred Draked86ed291999-12-15 15:34:33 +000011203#ifdef _SC_MAC
Victor Stinner8c62be82010-05-06 00:08:46 +000011204 {"SC_MAC", _SC_MAC},
Fred Draked86ed291999-12-15 15:34:33 +000011205#endif
Fred Drakec9680921999-12-13 16:37:25 +000011206#ifdef _SC_MAPPED_FILES
Victor Stinner8c62be82010-05-06 00:08:46 +000011207 {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
Fred Drakec9680921999-12-13 16:37:25 +000011208#endif
11209#ifdef _SC_MAXPID
Victor Stinner8c62be82010-05-06 00:08:46 +000011210 {"SC_MAXPID", _SC_MAXPID},
Fred Drakec9680921999-12-13 16:37:25 +000011211#endif
11212#ifdef _SC_MB_LEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011213 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011214#endif
11215#ifdef _SC_MEMLOCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011216 {"SC_MEMLOCK", _SC_MEMLOCK},
Fred Drakec9680921999-12-13 16:37:25 +000011217#endif
11218#ifdef _SC_MEMLOCK_RANGE
Victor Stinner8c62be82010-05-06 00:08:46 +000011219 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
Fred Drakec9680921999-12-13 16:37:25 +000011220#endif
11221#ifdef _SC_MEMORY_PROTECTION
Victor Stinner8c62be82010-05-06 00:08:46 +000011222 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
Fred Drakec9680921999-12-13 16:37:25 +000011223#endif
11224#ifdef _SC_MESSAGE_PASSING
Victor Stinner8c62be82010-05-06 00:08:46 +000011225 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
Fred Drakec9680921999-12-13 16:37:25 +000011226#endif
Fred Draked86ed291999-12-15 15:34:33 +000011227#ifdef _SC_MMAP_FIXED_ALIGNMENT
Victor Stinner8c62be82010-05-06 00:08:46 +000011228 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
Fred Draked86ed291999-12-15 15:34:33 +000011229#endif
Fred Drakec9680921999-12-13 16:37:25 +000011230#ifdef _SC_MQ_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011231 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011232#endif
11233#ifdef _SC_MQ_PRIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011234 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011235#endif
Fred Draked86ed291999-12-15 15:34:33 +000011236#ifdef _SC_NACLS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011237 {"SC_NACLS_MAX", _SC_NACLS_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000011238#endif
Fred Drakec9680921999-12-13 16:37:25 +000011239#ifdef _SC_NGROUPS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011240 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011241#endif
11242#ifdef _SC_NL_ARGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011243 {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011244#endif
11245#ifdef _SC_NL_LANGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011246 {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011247#endif
11248#ifdef _SC_NL_MSGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011249 {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011250#endif
11251#ifdef _SC_NL_NMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011252 {"SC_NL_NMAX", _SC_NL_NMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011253#endif
11254#ifdef _SC_NL_SETMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011255 {"SC_NL_SETMAX", _SC_NL_SETMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011256#endif
11257#ifdef _SC_NL_TEXTMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011258 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011259#endif
11260#ifdef _SC_NPROCESSORS_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011261 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
Fred Drakec9680921999-12-13 16:37:25 +000011262#endif
11263#ifdef _SC_NPROCESSORS_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011264 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
Fred Drakec9680921999-12-13 16:37:25 +000011265#endif
Fred Draked86ed291999-12-15 15:34:33 +000011266#ifdef _SC_NPROC_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011267 {"SC_NPROC_CONF", _SC_NPROC_CONF},
Fred Draked86ed291999-12-15 15:34:33 +000011268#endif
11269#ifdef _SC_NPROC_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011270 {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
Fred Draked86ed291999-12-15 15:34:33 +000011271#endif
Fred Drakec9680921999-12-13 16:37:25 +000011272#ifdef _SC_NZERO
Victor Stinner8c62be82010-05-06 00:08:46 +000011273 {"SC_NZERO", _SC_NZERO},
Fred Drakec9680921999-12-13 16:37:25 +000011274#endif
11275#ifdef _SC_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011276 {"SC_OPEN_MAX", _SC_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011277#endif
11278#ifdef _SC_PAGESIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011279 {"SC_PAGESIZE", _SC_PAGESIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011280#endif
11281#ifdef _SC_PAGE_SIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011282 {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011283#endif
11284#ifdef _SC_PASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011285 {"SC_PASS_MAX", _SC_PASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011286#endif
11287#ifdef _SC_PHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011288 {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011289#endif
11290#ifdef _SC_PII
Victor Stinner8c62be82010-05-06 00:08:46 +000011291 {"SC_PII", _SC_PII},
Fred Drakec9680921999-12-13 16:37:25 +000011292#endif
11293#ifdef _SC_PII_INTERNET
Victor Stinner8c62be82010-05-06 00:08:46 +000011294 {"SC_PII_INTERNET", _SC_PII_INTERNET},
Fred Drakec9680921999-12-13 16:37:25 +000011295#endif
11296#ifdef _SC_PII_INTERNET_DGRAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011297 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
Fred Drakec9680921999-12-13 16:37:25 +000011298#endif
11299#ifdef _SC_PII_INTERNET_STREAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011300 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
Fred Drakec9680921999-12-13 16:37:25 +000011301#endif
11302#ifdef _SC_PII_OSI
Victor Stinner8c62be82010-05-06 00:08:46 +000011303 {"SC_PII_OSI", _SC_PII_OSI},
Fred Drakec9680921999-12-13 16:37:25 +000011304#endif
11305#ifdef _SC_PII_OSI_CLTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011306 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
Fred Drakec9680921999-12-13 16:37:25 +000011307#endif
11308#ifdef _SC_PII_OSI_COTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011309 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
Fred Drakec9680921999-12-13 16:37:25 +000011310#endif
11311#ifdef _SC_PII_OSI_M
Victor Stinner8c62be82010-05-06 00:08:46 +000011312 {"SC_PII_OSI_M", _SC_PII_OSI_M},
Fred Drakec9680921999-12-13 16:37:25 +000011313#endif
11314#ifdef _SC_PII_SOCKET
Victor Stinner8c62be82010-05-06 00:08:46 +000011315 {"SC_PII_SOCKET", _SC_PII_SOCKET},
Fred Drakec9680921999-12-13 16:37:25 +000011316#endif
11317#ifdef _SC_PII_XTI
Victor Stinner8c62be82010-05-06 00:08:46 +000011318 {"SC_PII_XTI", _SC_PII_XTI},
Fred Drakec9680921999-12-13 16:37:25 +000011319#endif
11320#ifdef _SC_POLL
Victor Stinner8c62be82010-05-06 00:08:46 +000011321 {"SC_POLL", _SC_POLL},
Fred Drakec9680921999-12-13 16:37:25 +000011322#endif
11323#ifdef _SC_PRIORITIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011324 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011325#endif
11326#ifdef _SC_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011327 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011328#endif
11329#ifdef _SC_REALTIME_SIGNALS
Victor Stinner8c62be82010-05-06 00:08:46 +000011330 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
Fred Drakec9680921999-12-13 16:37:25 +000011331#endif
11332#ifdef _SC_RE_DUP_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011333 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011334#endif
11335#ifdef _SC_RTSIG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011336 {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011337#endif
11338#ifdef _SC_SAVED_IDS
Victor Stinner8c62be82010-05-06 00:08:46 +000011339 {"SC_SAVED_IDS", _SC_SAVED_IDS},
Fred Drakec9680921999-12-13 16:37:25 +000011340#endif
11341#ifdef _SC_SCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011342 {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011343#endif
11344#ifdef _SC_SCHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011345 {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011346#endif
11347#ifdef _SC_SELECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011348 {"SC_SELECT", _SC_SELECT},
Fred Drakec9680921999-12-13 16:37:25 +000011349#endif
11350#ifdef _SC_SEMAPHORES
Victor Stinner8c62be82010-05-06 00:08:46 +000011351 {"SC_SEMAPHORES", _SC_SEMAPHORES},
Fred Drakec9680921999-12-13 16:37:25 +000011352#endif
11353#ifdef _SC_SEM_NSEMS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011354 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011355#endif
11356#ifdef _SC_SEM_VALUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011357 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011358#endif
11359#ifdef _SC_SHARED_MEMORY_OBJECTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011360 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
Fred Drakec9680921999-12-13 16:37:25 +000011361#endif
11362#ifdef _SC_SHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011363 {"SC_SHRT_MAX", _SC_SHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011364#endif
11365#ifdef _SC_SHRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011366 {"SC_SHRT_MIN", _SC_SHRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011367#endif
11368#ifdef _SC_SIGQUEUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011369 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011370#endif
11371#ifdef _SC_SIGRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011372 {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011373#endif
11374#ifdef _SC_SIGRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011375 {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011376#endif
Fred Draked86ed291999-12-15 15:34:33 +000011377#ifdef _SC_SOFTPOWER
Victor Stinner8c62be82010-05-06 00:08:46 +000011378 {"SC_SOFTPOWER", _SC_SOFTPOWER},
Fred Draked86ed291999-12-15 15:34:33 +000011379#endif
Fred Drakec9680921999-12-13 16:37:25 +000011380#ifdef _SC_SPLIT_CACHE
Victor Stinner8c62be82010-05-06 00:08:46 +000011381 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
Fred Drakec9680921999-12-13 16:37:25 +000011382#endif
11383#ifdef _SC_SSIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011384 {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011385#endif
11386#ifdef _SC_STACK_PROT
Victor Stinner8c62be82010-05-06 00:08:46 +000011387 {"SC_STACK_PROT", _SC_STACK_PROT},
Fred Drakec9680921999-12-13 16:37:25 +000011388#endif
11389#ifdef _SC_STREAM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011390 {"SC_STREAM_MAX", _SC_STREAM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011391#endif
11392#ifdef _SC_SYNCHRONIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011393 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011394#endif
11395#ifdef _SC_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011396 {"SC_THREADS", _SC_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011397#endif
11398#ifdef _SC_THREAD_ATTR_STACKADDR
Victor Stinner8c62be82010-05-06 00:08:46 +000011399 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
Fred Drakec9680921999-12-13 16:37:25 +000011400#endif
11401#ifdef _SC_THREAD_ATTR_STACKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011402 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011403#endif
11404#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011405 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011406#endif
11407#ifdef _SC_THREAD_KEYS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011408 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011409#endif
11410#ifdef _SC_THREAD_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011411 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011412#endif
11413#ifdef _SC_THREAD_PRIO_INHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011414 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
Fred Drakec9680921999-12-13 16:37:25 +000011415#endif
11416#ifdef _SC_THREAD_PRIO_PROTECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011417 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
Fred Drakec9680921999-12-13 16:37:25 +000011418#endif
11419#ifdef _SC_THREAD_PROCESS_SHARED
Victor Stinner8c62be82010-05-06 00:08:46 +000011420 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
Fred Drakec9680921999-12-13 16:37:25 +000011421#endif
11422#ifdef _SC_THREAD_SAFE_FUNCTIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011423 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011424#endif
11425#ifdef _SC_THREAD_STACK_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011426 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011427#endif
11428#ifdef _SC_THREAD_THREADS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011429 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011430#endif
11431#ifdef _SC_TIMERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011432 {"SC_TIMERS", _SC_TIMERS},
Fred Drakec9680921999-12-13 16:37:25 +000011433#endif
11434#ifdef _SC_TIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011435 {"SC_TIMER_MAX", _SC_TIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011436#endif
11437#ifdef _SC_TTY_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011438 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011439#endif
11440#ifdef _SC_TZNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011441 {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011442#endif
11443#ifdef _SC_T_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011444 {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011445#endif
11446#ifdef _SC_UCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011447 {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011448#endif
11449#ifdef _SC_UINT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011450 {"SC_UINT_MAX", _SC_UINT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011451#endif
11452#ifdef _SC_UIO_MAXIOV
Victor Stinner8c62be82010-05-06 00:08:46 +000011453 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
Fred Drakec9680921999-12-13 16:37:25 +000011454#endif
11455#ifdef _SC_ULONG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011456 {"SC_ULONG_MAX", _SC_ULONG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011457#endif
11458#ifdef _SC_USHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011459 {"SC_USHRT_MAX", _SC_USHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011460#endif
11461#ifdef _SC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011462 {"SC_VERSION", _SC_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011463#endif
11464#ifdef _SC_WORD_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011465 {"SC_WORD_BIT", _SC_WORD_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011466#endif
11467#ifdef _SC_XBS5_ILP32_OFF32
Victor Stinner8c62be82010-05-06 00:08:46 +000011468 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
Fred Drakec9680921999-12-13 16:37:25 +000011469#endif
11470#ifdef _SC_XBS5_ILP32_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011471 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011472#endif
11473#ifdef _SC_XBS5_LP64_OFF64
Victor Stinner8c62be82010-05-06 00:08:46 +000011474 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
Fred Drakec9680921999-12-13 16:37:25 +000011475#endif
11476#ifdef _SC_XBS5_LPBIG_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011477 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011478#endif
11479#ifdef _SC_XOPEN_CRYPT
Victor Stinner8c62be82010-05-06 00:08:46 +000011480 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
Fred Drakec9680921999-12-13 16:37:25 +000011481#endif
11482#ifdef _SC_XOPEN_ENH_I18N
Victor Stinner8c62be82010-05-06 00:08:46 +000011483 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
Fred Drakec9680921999-12-13 16:37:25 +000011484#endif
11485#ifdef _SC_XOPEN_LEGACY
Victor Stinner8c62be82010-05-06 00:08:46 +000011486 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
Fred Drakec9680921999-12-13 16:37:25 +000011487#endif
11488#ifdef _SC_XOPEN_REALTIME
Victor Stinner8c62be82010-05-06 00:08:46 +000011489 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
Fred Drakec9680921999-12-13 16:37:25 +000011490#endif
11491#ifdef _SC_XOPEN_REALTIME_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011492 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011493#endif
11494#ifdef _SC_XOPEN_SHM
Victor Stinner8c62be82010-05-06 00:08:46 +000011495 {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
Fred Drakec9680921999-12-13 16:37:25 +000011496#endif
11497#ifdef _SC_XOPEN_UNIX
Victor Stinner8c62be82010-05-06 00:08:46 +000011498 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
Fred Drakec9680921999-12-13 16:37:25 +000011499#endif
11500#ifdef _SC_XOPEN_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011501 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011502#endif
11503#ifdef _SC_XOPEN_XCU_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011504 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011505#endif
11506#ifdef _SC_XOPEN_XPG2
Victor Stinner8c62be82010-05-06 00:08:46 +000011507 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
Fred Drakec9680921999-12-13 16:37:25 +000011508#endif
11509#ifdef _SC_XOPEN_XPG3
Victor Stinner8c62be82010-05-06 00:08:46 +000011510 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
Fred Drakec9680921999-12-13 16:37:25 +000011511#endif
11512#ifdef _SC_XOPEN_XPG4
Victor Stinner8c62be82010-05-06 00:08:46 +000011513 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
Fred Drakec9680921999-12-13 16:37:25 +000011514#endif
11515};
11516
11517static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011518conv_sysconf_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011519{
11520 return conv_confname(arg, valuep, posix_constants_sysconf,
11521 sizeof(posix_constants_sysconf)
11522 / sizeof(struct constdef));
11523}
11524
Larry Hastings2f936352014-08-05 14:04:04 +100011525
11526/*[clinic input]
11527os.sysconf -> long
11528 name: sysconf_confname
11529 /
11530
11531Return an integer-valued system configuration variable.
11532[clinic start generated code]*/
11533
Larry Hastings2f936352014-08-05 14:04:04 +100011534static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011535os_sysconf_impl(PyObject *module, int name)
11536/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011537{
11538 long value;
11539
11540 errno = 0;
11541 value = sysconf(name);
11542 if (value == -1 && errno != 0)
11543 posix_error();
11544 return value;
11545}
11546#endif /* HAVE_SYSCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011547
11548
Fred Drakebec628d1999-12-15 18:31:10 +000011549/* This code is used to ensure that the tables of configuration value names
Serhiy Storchaka56a6d852014-12-01 18:28:43 +020011550 * are in sorted order as required by conv_confname(), and also to build
Fred Drakebec628d1999-12-15 18:31:10 +000011551 * the exported dictionaries that are used to publish information about the
11552 * names available on the host platform.
11553 *
11554 * Sorting the table at runtime ensures that the table is properly ordered
11555 * when used, even for platforms we're not able to test on. It also makes
11556 * it easier to add additional entries to the tables.
Fred Draked86ed291999-12-15 15:34:33 +000011557 */
Fred Drakebec628d1999-12-15 18:31:10 +000011558
11559static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011560cmp_constdefs(const void *v1, const void *v2)
Fred Drakebec628d1999-12-15 18:31:10 +000011561{
11562 const struct constdef *c1 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011563 (const struct constdef *) v1;
Fred Drakebec628d1999-12-15 18:31:10 +000011564 const struct constdef *c2 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011565 (const struct constdef *) v2;
Fred Drakebec628d1999-12-15 18:31:10 +000011566
11567 return strcmp(c1->name, c2->name);
11568}
11569
11570static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011571setup_confname_table(struct constdef *table, size_t tablesize,
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011572 const char *tablename, PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011573{
Fred Drakebec628d1999-12-15 18:31:10 +000011574 PyObject *d = NULL;
Barry Warsaw3155db32000-04-13 15:20:40 +000011575 size_t i;
Fred Drakebec628d1999-12-15 18:31:10 +000011576
11577 qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
11578 d = PyDict_New();
Barry Warsaw3155db32000-04-13 15:20:40 +000011579 if (d == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +000011580 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011581
Barry Warsaw3155db32000-04-13 15:20:40 +000011582 for (i=0; i < tablesize; ++i) {
Victor Stinner8c62be82010-05-06 00:08:46 +000011583 PyObject *o = PyLong_FromLong(table[i].value);
11584 if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
11585 Py_XDECREF(o);
11586 Py_DECREF(d);
11587 return -1;
11588 }
11589 Py_DECREF(o);
Fred Draked86ed291999-12-15 15:34:33 +000011590 }
Fred Drake4d1e64b2002-04-15 19:40:07 +000011591 return PyModule_AddObject(module, tablename, d);
Fred Draked86ed291999-12-15 15:34:33 +000011592}
11593
Fred Drakebec628d1999-12-15 18:31:10 +000011594/* Return -1 on failure, 0 on success. */
11595static int
Fred Drake4d1e64b2002-04-15 19:40:07 +000011596setup_confname_tables(PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011597{
11598#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
Fred Drakebec628d1999-12-15 18:31:10 +000011599 if (setup_confname_table(posix_constants_pathconf,
Fred Draked86ed291999-12-15 15:34:33 +000011600 sizeof(posix_constants_pathconf)
11601 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011602 "pathconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011603 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011604#endif
11605#ifdef HAVE_CONFSTR
Fred Drakebec628d1999-12-15 18:31:10 +000011606 if (setup_confname_table(posix_constants_confstr,
Fred Draked86ed291999-12-15 15:34:33 +000011607 sizeof(posix_constants_confstr)
11608 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011609 "confstr_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011610 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011611#endif
11612#ifdef HAVE_SYSCONF
Fred Drakebec628d1999-12-15 18:31:10 +000011613 if (setup_confname_table(posix_constants_sysconf,
Fred Draked86ed291999-12-15 15:34:33 +000011614 sizeof(posix_constants_sysconf)
11615 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011616 "sysconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011617 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011618#endif
Fred Drakebec628d1999-12-15 18:31:10 +000011619 return 0;
Fred Draked86ed291999-12-15 15:34:33 +000011620}
Fred Draked86ed291999-12-15 15:34:33 +000011621
11622
Larry Hastings2f936352014-08-05 14:04:04 +100011623/*[clinic input]
11624os.abort
11625
11626Abort the interpreter immediately.
11627
11628This function 'dumps core' or otherwise fails in the hardest way possible
11629on the hosting operating system. This function never returns.
11630[clinic start generated code]*/
11631
Larry Hastings2f936352014-08-05 14:04:04 +100011632static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011633os_abort_impl(PyObject *module)
11634/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011635{
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011636 abort();
11637 /*NOTREACHED*/
Victor Stinner9a2329f2016-12-05 17:56:36 +010011638#ifndef __clang__
11639 /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
11640 GCC emits a warning without "return NULL;" (compiler bug?), but Clang
11641 is smarter and emits a warning on the return. */
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011642 Py_FatalError("abort() called from Python code didn't abort!");
11643 return NULL;
Victor Stinner9a2329f2016-12-05 17:56:36 +010011644#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011645}
Fred Drakebec628d1999-12-15 18:31:10 +000011646
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011647#ifdef MS_WINDOWS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011648/* Grab ShellExecute dynamically from shell32 */
11649static int has_ShellExecute = -1;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011650static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
11651 LPCWSTR, INT);
11652static int
11653check_ShellExecute()
11654{
11655 HINSTANCE hShell32;
11656
11657 /* only recheck */
11658 if (-1 == has_ShellExecute) {
11659 Py_BEGIN_ALLOW_THREADS
Victor Stinnera9912152017-10-13 13:46:57 -070011660 /* Security note: this call is not vulnerable to "DLL hijacking".
11661 SHELL32 is part of "KnownDLLs" and so Windows always load
11662 the system SHELL32.DLL, even if there is another SHELL32.DLL
11663 in the DLL search path. */
Steve Dower7d0e0c92015-01-24 08:18:24 -080011664 hShell32 = LoadLibraryW(L"SHELL32");
Steve Dower7d0e0c92015-01-24 08:18:24 -080011665 if (hShell32) {
Steve Dower7d0e0c92015-01-24 08:18:24 -080011666 *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
11667 "ShellExecuteW");
Steve Dowercc16be82016-09-08 10:35:16 -070011668 has_ShellExecute = Py_ShellExecuteW != NULL;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011669 } else {
11670 has_ShellExecute = 0;
11671 }
Tony Roberts4860f012019-02-02 18:16:42 +010011672 Py_END_ALLOW_THREADS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011673 }
11674 return has_ShellExecute;
11675}
11676
11677
Steve Dowercc16be82016-09-08 10:35:16 -070011678/*[clinic input]
11679os.startfile
11680 filepath: path_t
11681 operation: Py_UNICODE = NULL
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +000011682
Steve Dowercc16be82016-09-08 10:35:16 -070011683Start a file with its associated application.
11684
11685When "operation" is not specified or "open", this acts like
11686double-clicking the file in Explorer, or giving the file name as an
11687argument to the DOS "start" command: the file is opened with whatever
11688application (if any) its extension is associated.
11689When another "operation" is given, it specifies what should be done with
11690the file. A typical operation is "print".
11691
11692startfile returns as soon as the associated application is launched.
11693There is no option to wait for the application to close, and no way
11694to retrieve the application's exit status.
11695
11696The filepath is relative to the current directory. If you want to use
11697an absolute path, make sure the first character is not a slash ("/");
11698the underlying Win32 ShellExecute function doesn't work if it is.
11699[clinic start generated code]*/
11700
11701static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +020011702os_startfile_impl(PyObject *module, path_t *filepath,
11703 const Py_UNICODE *operation)
Serhiy Storchaka279f4462019-09-14 12:24:05 +030011704/*[clinic end generated code: output=66dc311c94d50797 input=c940888a5390f039]*/
Steve Dowercc16be82016-09-08 10:35:16 -070011705{
11706 HINSTANCE rc;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011707
11708 if(!check_ShellExecute()) {
11709 /* If the OS doesn't have ShellExecute, return a
11710 NotImplementedError. */
11711 return PyErr_Format(PyExc_NotImplementedError,
11712 "startfile not available on this platform");
11713 }
11714
Victor Stinner8c62be82010-05-06 00:08:46 +000011715 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -070011716 rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
Steve Dower7d0e0c92015-01-24 08:18:24 -080011717 NULL, NULL, SW_SHOWNORMAL);
Victor Stinner8c62be82010-05-06 00:08:46 +000011718 Py_END_ALLOW_THREADS
11719
Victor Stinner8c62be82010-05-06 00:08:46 +000011720 if (rc <= (HINSTANCE)32) {
Steve Dowercc16be82016-09-08 10:35:16 -070011721 win32_error_object("startfile", filepath->object);
Victor Stinnereb5657a2011-09-30 01:44:27 +020011722 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000011723 }
Steve Dowercc16be82016-09-08 10:35:16 -070011724 Py_RETURN_NONE;
Tim Petersf58a7aa2000-09-22 10:05:54 +000011725}
Larry Hastings2f936352014-08-05 14:04:04 +100011726#endif /* MS_WINDOWS */
11727
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011728
Martin v. Löwis438b5342002-12-27 10:16:42 +000011729#ifdef HAVE_GETLOADAVG
Larry Hastings2f936352014-08-05 14:04:04 +100011730/*[clinic input]
11731os.getloadavg
11732
11733Return average recent system load information.
11734
11735Return the number of processes in the system run queue averaged over
11736the last 1, 5, and 15 minutes as a tuple of three floats.
11737Raises OSError if the load average was unobtainable.
11738[clinic start generated code]*/
11739
Larry Hastings2f936352014-08-05 14:04:04 +100011740static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011741os_getloadavg_impl(PyObject *module)
11742/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
Martin v. Löwis438b5342002-12-27 10:16:42 +000011743{
11744 double loadavg[3];
Martin v. Löwis438b5342002-12-27 10:16:42 +000011745 if (getloadavg(loadavg, 3)!=3) {
Stefan Krah0e803b32010-11-26 16:16:47 +000011746 PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
11747 return NULL;
Martin v. Löwis438b5342002-12-27 10:16:42 +000011748 } else
Stefan Krah0e803b32010-11-26 16:16:47 +000011749 return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
Martin v. Löwis438b5342002-12-27 10:16:42 +000011750}
Larry Hastings2f936352014-08-05 14:04:04 +100011751#endif /* HAVE_GETLOADAVG */
Martin v. Löwis438b5342002-12-27 10:16:42 +000011752
Larry Hastings2f936352014-08-05 14:04:04 +100011753
11754/*[clinic input]
11755os.device_encoding
11756 fd: int
11757
11758Return a string describing the encoding of a terminal's file descriptor.
11759
11760The file descriptor must be attached to a terminal.
11761If the device is not a terminal, return None.
11762[clinic start generated code]*/
11763
Larry Hastings2f936352014-08-05 14:04:04 +100011764static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011765os_device_encoding_impl(PyObject *module, int fd)
11766/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011767{
Brett Cannonefb00c02012-02-29 18:31:31 -050011768 return _Py_device_encoding(fd);
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +000011769}
11770
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011771
Larry Hastings2f936352014-08-05 14:04:04 +100011772#ifdef HAVE_SETRESUID
11773/*[clinic input]
11774os.setresuid
11775
11776 ruid: uid_t
11777 euid: uid_t
11778 suid: uid_t
11779 /
11780
11781Set the current process's real, effective, and saved user ids.
11782[clinic start generated code]*/
11783
Larry Hastings2f936352014-08-05 14:04:04 +100011784static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011785os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
11786/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011787{
Victor Stinner8c62be82010-05-06 00:08:46 +000011788 if (setresuid(ruid, euid, suid) < 0)
11789 return posix_error();
11790 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011791}
Larry Hastings2f936352014-08-05 14:04:04 +100011792#endif /* HAVE_SETRESUID */
11793
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011794
11795#ifdef HAVE_SETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011796/*[clinic input]
11797os.setresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011798
Larry Hastings2f936352014-08-05 14:04:04 +100011799 rgid: gid_t
11800 egid: gid_t
11801 sgid: gid_t
11802 /
11803
11804Set the current process's real, effective, and saved group ids.
11805[clinic start generated code]*/
11806
Larry Hastings2f936352014-08-05 14:04:04 +100011807static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011808os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
11809/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011810{
Victor Stinner8c62be82010-05-06 00:08:46 +000011811 if (setresgid(rgid, egid, sgid) < 0)
11812 return posix_error();
11813 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011814}
Larry Hastings2f936352014-08-05 14:04:04 +100011815#endif /* HAVE_SETRESGID */
11816
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011817
11818#ifdef HAVE_GETRESUID
Larry Hastings2f936352014-08-05 14:04:04 +100011819/*[clinic input]
11820os.getresuid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011821
Larry Hastings2f936352014-08-05 14:04:04 +100011822Return a tuple of the current process's real, effective, and saved user ids.
11823[clinic start generated code]*/
11824
Larry Hastings2f936352014-08-05 14:04:04 +100011825static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011826os_getresuid_impl(PyObject *module)
11827/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011828{
Victor Stinner8c62be82010-05-06 00:08:46 +000011829 uid_t ruid, euid, suid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011830 if (getresuid(&ruid, &euid, &suid) < 0)
11831 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011832 return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
11833 _PyLong_FromUid(euid),
11834 _PyLong_FromUid(suid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011835}
Larry Hastings2f936352014-08-05 14:04:04 +100011836#endif /* HAVE_GETRESUID */
11837
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011838
11839#ifdef HAVE_GETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011840/*[clinic input]
11841os.getresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011842
Larry Hastings2f936352014-08-05 14:04:04 +100011843Return a tuple of the current process's real, effective, and saved group ids.
11844[clinic start generated code]*/
11845
Larry Hastings2f936352014-08-05 14:04:04 +100011846static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011847os_getresgid_impl(PyObject *module)
11848/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011849{
11850 gid_t rgid, egid, sgid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011851 if (getresgid(&rgid, &egid, &sgid) < 0)
11852 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011853 return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
11854 _PyLong_FromGid(egid),
11855 _PyLong_FromGid(sgid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011856}
Larry Hastings2f936352014-08-05 14:04:04 +100011857#endif /* HAVE_GETRESGID */
11858
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011859
Benjamin Peterson9428d532011-09-14 11:45:52 -040011860#ifdef USE_XATTRS
Larry Hastings2f936352014-08-05 14:04:04 +100011861/*[clinic input]
11862os.getxattr
Benjamin Peterson799bd802011-08-31 22:15:17 -040011863
Larry Hastings2f936352014-08-05 14:04:04 +100011864 path: path_t(allow_fd=True)
11865 attribute: path_t
11866 *
11867 follow_symlinks: bool = True
11868
11869Return the value of extended attribute attribute on path.
11870
BNMetricsb9427072018-11-02 15:20:19 +000011871path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011872If follow_symlinks is False, and the last element of the path is a symbolic
11873 link, getxattr will examine the symbolic link itself instead of the file
11874 the link points to.
11875
11876[clinic start generated code]*/
11877
Larry Hastings2f936352014-08-05 14:04:04 +100011878static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011879os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011880 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011881/*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011882{
11883 Py_ssize_t i;
11884 PyObject *buffer = NULL;
11885
11886 if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
11887 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011888
Larry Hastings9cf065c2012-06-22 16:30:09 -070011889 for (i = 0; ; i++) {
11890 void *ptr;
11891 ssize_t result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020011892 static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
Larry Hastings9cf065c2012-06-22 16:30:09 -070011893 Py_ssize_t buffer_size = buffer_sizes[i];
11894 if (!buffer_size) {
Larry Hastings2f936352014-08-05 14:04:04 +100011895 path_error(path);
11896 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011897 }
11898 buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
11899 if (!buffer)
Larry Hastings2f936352014-08-05 14:04:04 +100011900 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011901 ptr = PyBytes_AS_STRING(buffer);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011902
Larry Hastings9cf065c2012-06-22 16:30:09 -070011903 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011904 if (path->fd >= 0)
11905 result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011906 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011907 result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011908 else
Larry Hastings2f936352014-08-05 14:04:04 +100011909 result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011910 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011911
Larry Hastings9cf065c2012-06-22 16:30:09 -070011912 if (result < 0) {
11913 Py_DECREF(buffer);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011914 if (errno == ERANGE)
11915 continue;
Larry Hastings2f936352014-08-05 14:04:04 +100011916 path_error(path);
11917 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011918 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011919
Larry Hastings9cf065c2012-06-22 16:30:09 -070011920 if (result != buffer_size) {
11921 /* Can only shrink. */
11922 _PyBytes_Resize(&buffer, result);
11923 }
11924 break;
11925 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011926
Larry Hastings9cf065c2012-06-22 16:30:09 -070011927 return buffer;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011928}
11929
Larry Hastings2f936352014-08-05 14:04:04 +100011930
11931/*[clinic input]
11932os.setxattr
11933
11934 path: path_t(allow_fd=True)
11935 attribute: path_t
11936 value: Py_buffer
11937 flags: int = 0
11938 *
11939 follow_symlinks: bool = True
11940
11941Set extended attribute attribute on path to value.
11942
BNMetricsb9427072018-11-02 15:20:19 +000011943path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011944If follow_symlinks is False, and the last element of the path is a symbolic
11945 link, setxattr will modify the symbolic link itself instead of the file
11946 the link points to.
11947
11948[clinic start generated code]*/
11949
Benjamin Peterson799bd802011-08-31 22:15:17 -040011950static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011951os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011952 Py_buffer *value, int flags, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011953/*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
Benjamin Peterson799bd802011-08-31 22:15:17 -040011954{
Larry Hastings2f936352014-08-05 14:04:04 +100011955 ssize_t result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011956
Larry Hastings2f936352014-08-05 14:04:04 +100011957 if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
Benjamin Peterson799bd802011-08-31 22:15:17 -040011958 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011959
Benjamin Peterson799bd802011-08-31 22:15:17 -040011960 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011961 if (path->fd > -1)
11962 result = fsetxattr(path->fd, attribute->narrow,
11963 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011964 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011965 result = setxattr(path->narrow, attribute->narrow,
11966 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011967 else
Larry Hastings2f936352014-08-05 14:04:04 +100011968 result = lsetxattr(path->narrow, attribute->narrow,
11969 value->buf, value->len, flags);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011970 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011971
Larry Hastings9cf065c2012-06-22 16:30:09 -070011972 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100011973 path_error(path);
11974 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011975 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011976
Larry Hastings2f936352014-08-05 14:04:04 +100011977 Py_RETURN_NONE;
11978}
11979
11980
11981/*[clinic input]
11982os.removexattr
11983
11984 path: path_t(allow_fd=True)
11985 attribute: path_t
11986 *
11987 follow_symlinks: bool = True
11988
11989Remove extended attribute attribute on path.
11990
BNMetricsb9427072018-11-02 15:20:19 +000011991path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011992If follow_symlinks is False, and the last element of the path is a symbolic
11993 link, removexattr will modify the symbolic link itself instead of the file
11994 the link points to.
11995
11996[clinic start generated code]*/
11997
Larry Hastings2f936352014-08-05 14:04:04 +100011998static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011999os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012000 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012001/*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012002{
12003 ssize_t result;
12004
12005 if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
12006 return NULL;
12007
12008 Py_BEGIN_ALLOW_THREADS;
12009 if (path->fd > -1)
12010 result = fremovexattr(path->fd, attribute->narrow);
12011 else if (follow_symlinks)
12012 result = removexattr(path->narrow, attribute->narrow);
12013 else
12014 result = lremovexattr(path->narrow, attribute->narrow);
12015 Py_END_ALLOW_THREADS;
12016
12017 if (result) {
12018 return path_error(path);
12019 }
12020
12021 Py_RETURN_NONE;
12022}
12023
12024
12025/*[clinic input]
12026os.listxattr
12027
12028 path: path_t(allow_fd=True, nullable=True) = None
12029 *
12030 follow_symlinks: bool = True
12031
12032Return a list of extended attributes on path.
12033
BNMetricsb9427072018-11-02 15:20:19 +000012034path may be either None, a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012035if path is None, listxattr will examine the current directory.
12036If follow_symlinks is False, and the last element of the path is a symbolic
12037 link, listxattr will examine the symbolic link itself instead of the file
12038 the link points to.
12039[clinic start generated code]*/
12040
Larry Hastings2f936352014-08-05 14:04:04 +100012041static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012042os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012043/*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012044{
Larry Hastings9cf065c2012-06-22 16:30:09 -070012045 Py_ssize_t i;
12046 PyObject *result = NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100012047 const char *name;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012048 char *buffer = NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012049
Larry Hastings2f936352014-08-05 14:04:04 +100012050 if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
Larry Hastings9cf065c2012-06-22 16:30:09 -070012051 goto exit;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012052
Larry Hastings2f936352014-08-05 14:04:04 +100012053 name = path->narrow ? path->narrow : ".";
12054
Larry Hastings9cf065c2012-06-22 16:30:09 -070012055 for (i = 0; ; i++) {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012056 const char *start, *trace, *end;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012057 ssize_t length;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012058 static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
Larry Hastings9cf065c2012-06-22 16:30:09 -070012059 Py_ssize_t buffer_size = buffer_sizes[i];
12060 if (!buffer_size) {
Christian Heimes3b9493b2012-09-23 16:11:15 +020012061 /* ERANGE */
Larry Hastings2f936352014-08-05 14:04:04 +100012062 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012063 break;
12064 }
12065 buffer = PyMem_MALLOC(buffer_size);
12066 if (!buffer) {
12067 PyErr_NoMemory();
12068 break;
12069 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012070
Larry Hastings9cf065c2012-06-22 16:30:09 -070012071 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012072 if (path->fd > -1)
12073 length = flistxattr(path->fd, buffer, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012074 else if (follow_symlinks)
12075 length = listxattr(name, buffer, buffer_size);
12076 else
12077 length = llistxattr(name, buffer, buffer_size);
12078 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012079
Larry Hastings9cf065c2012-06-22 16:30:09 -070012080 if (length < 0) {
Antoine Pitrou7f987392013-05-13 19:46:29 +020012081 if (errno == ERANGE) {
12082 PyMem_FREE(buffer);
Benjamin Petersondedac522013-05-13 19:55:40 -050012083 buffer = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012084 continue;
Antoine Pitrou7f987392013-05-13 19:46:29 +020012085 }
Larry Hastings2f936352014-08-05 14:04:04 +100012086 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012087 break;
12088 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012089
Larry Hastings9cf065c2012-06-22 16:30:09 -070012090 result = PyList_New(0);
12091 if (!result) {
12092 goto exit;
12093 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012094
Larry Hastings9cf065c2012-06-22 16:30:09 -070012095 end = buffer + length;
12096 for (trace = start = buffer; trace != end; trace++) {
12097 if (!*trace) {
12098 int error;
12099 PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
12100 trace - start);
12101 if (!attribute) {
12102 Py_DECREF(result);
12103 result = NULL;
12104 goto exit;
12105 }
12106 error = PyList_Append(result, attribute);
12107 Py_DECREF(attribute);
12108 if (error) {
12109 Py_DECREF(result);
12110 result = NULL;
12111 goto exit;
12112 }
12113 start = trace + 1;
12114 }
12115 }
12116 break;
12117 }
12118exit:
Larry Hastings9cf065c2012-06-22 16:30:09 -070012119 if (buffer)
12120 PyMem_FREE(buffer);
12121 return result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012122}
Benjamin Peterson9428d532011-09-14 11:45:52 -040012123#endif /* USE_XATTRS */
Benjamin Peterson799bd802011-08-31 22:15:17 -040012124
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012125
Larry Hastings2f936352014-08-05 14:04:04 +100012126/*[clinic input]
12127os.urandom
12128
12129 size: Py_ssize_t
12130 /
12131
12132Return a bytes object containing random bytes suitable for cryptographic use.
12133[clinic start generated code]*/
12134
Larry Hastings2f936352014-08-05 14:04:04 +100012135static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012136os_urandom_impl(PyObject *module, Py_ssize_t size)
12137/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012138{
12139 PyObject *bytes;
12140 int result;
12141
Georg Brandl2fb477c2012-02-21 00:33:36 +010012142 if (size < 0)
12143 return PyErr_Format(PyExc_ValueError,
12144 "negative argument not allowed");
Larry Hastings2f936352014-08-05 14:04:04 +100012145 bytes = PyBytes_FromStringAndSize(NULL, size);
12146 if (bytes == NULL)
Georg Brandl2fb477c2012-02-21 00:33:36 +010012147 return NULL;
12148
Victor Stinnere66987e2016-09-06 16:33:52 -070012149 result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
Larry Hastings2f936352014-08-05 14:04:04 +100012150 if (result == -1) {
12151 Py_DECREF(bytes);
Georg Brandl2fb477c2012-02-21 00:33:36 +010012152 return NULL;
12153 }
Larry Hastings2f936352014-08-05 14:04:04 +100012154 return bytes;
Georg Brandl2fb477c2012-02-21 00:33:36 +010012155}
12156
Zackery Spytz43fdbd22019-05-29 13:57:07 -060012157#ifdef HAVE_MEMFD_CREATE
12158/*[clinic input]
12159os.memfd_create
12160
12161 name: FSConverter
12162 flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
12163
12164[clinic start generated code]*/
12165
12166static PyObject *
12167os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
12168/*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
12169{
12170 int fd;
12171 const char *bytes = PyBytes_AS_STRING(name);
12172 Py_BEGIN_ALLOW_THREADS
12173 fd = memfd_create(bytes, flags);
12174 Py_END_ALLOW_THREADS
12175 if (fd == -1) {
12176 return PyErr_SetFromErrno(PyExc_OSError);
12177 }
12178 return PyLong_FromLong(fd);
12179}
12180#endif
12181
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012182/* Terminal size querying */
12183
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012184PyDoc_STRVAR(TerminalSize_docstring,
12185 "A tuple of (columns, lines) for holding terminal window size");
12186
12187static PyStructSequence_Field TerminalSize_fields[] = {
12188 {"columns", "width of the terminal window in characters"},
12189 {"lines", "height of the terminal window in characters"},
12190 {NULL, NULL}
12191};
12192
12193static PyStructSequence_Desc TerminalSize_desc = {
12194 "os.terminal_size",
12195 TerminalSize_docstring,
12196 TerminalSize_fields,
12197 2,
12198};
12199
12200#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
Larry Hastings2f936352014-08-05 14:04:04 +100012201/* AC 3.5: fd should accept None */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012202PyDoc_STRVAR(termsize__doc__,
12203 "Return the size of the terminal window as (columns, lines).\n" \
12204 "\n" \
12205 "The optional argument fd (default standard output) specifies\n" \
12206 "which file descriptor should be queried.\n" \
12207 "\n" \
12208 "If the file descriptor is not connected to a terminal, an OSError\n" \
12209 "is thrown.\n" \
12210 "\n" \
12211 "This function will only be defined if an implementation is\n" \
12212 "available for this system.\n" \
12213 "\n" \
oldkaa0735f2018-02-02 16:52:55 +080012214 "shutil.get_terminal_size is the high-level function which should\n" \
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012215 "normally be used, os.get_terminal_size is the low-level implementation.");
12216
12217static PyObject*
12218get_terminal_size(PyObject *self, PyObject *args)
12219{
12220 int columns, lines;
12221 PyObject *termsize;
12222
12223 int fd = fileno(stdout);
12224 /* Under some conditions stdout may not be connected and
12225 * fileno(stdout) may point to an invalid file descriptor. For example
12226 * GUI apps don't have valid standard streams by default.
12227 *
12228 * If this happens, and the optional fd argument is not present,
12229 * the ioctl below will fail returning EBADF. This is what we want.
12230 */
12231
12232 if (!PyArg_ParseTuple(args, "|i", &fd))
12233 return NULL;
12234
12235#ifdef TERMSIZE_USE_IOCTL
12236 {
12237 struct winsize w;
12238 if (ioctl(fd, TIOCGWINSZ, &w))
12239 return PyErr_SetFromErrno(PyExc_OSError);
12240 columns = w.ws_col;
12241 lines = w.ws_row;
12242 }
12243#endif /* TERMSIZE_USE_IOCTL */
12244
12245#ifdef TERMSIZE_USE_CONIO
12246 {
12247 DWORD nhandle;
12248 HANDLE handle;
12249 CONSOLE_SCREEN_BUFFER_INFO csbi;
12250 switch (fd) {
12251 case 0: nhandle = STD_INPUT_HANDLE;
12252 break;
12253 case 1: nhandle = STD_OUTPUT_HANDLE;
12254 break;
12255 case 2: nhandle = STD_ERROR_HANDLE;
12256 break;
12257 default:
12258 return PyErr_Format(PyExc_ValueError, "bad file descriptor");
12259 }
12260 handle = GetStdHandle(nhandle);
12261 if (handle == NULL)
12262 return PyErr_Format(PyExc_OSError, "handle cannot be retrieved");
12263 if (handle == INVALID_HANDLE_VALUE)
12264 return PyErr_SetFromWindowsErr(0);
12265
12266 if (!GetConsoleScreenBufferInfo(handle, &csbi))
12267 return PyErr_SetFromWindowsErr(0);
12268
12269 columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
12270 lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
12271 }
12272#endif /* TERMSIZE_USE_CONIO */
12273
Eddie Elizondob3966632019-11-05 07:16:14 -080012274 PyObject *TerminalSizeType = _posixstate(self)->TerminalSizeType;
12275 termsize = PyStructSequence_New((PyTypeObject *)TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012276 if (termsize == NULL)
12277 return NULL;
12278 PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
12279 PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
12280 if (PyErr_Occurred()) {
12281 Py_DECREF(termsize);
12282 return NULL;
12283 }
12284 return termsize;
12285}
12286#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
12287
Larry Hastings2f936352014-08-05 14:04:04 +100012288
12289/*[clinic input]
12290os.cpu_count
12291
Charles-François Natali80d62e62015-08-13 20:37:08 +010012292Return the number of CPUs in the system; return None if indeterminable.
12293
12294This number is not equivalent to the number of CPUs the current process can
12295use. The number of usable CPUs can be obtained with
12296``len(os.sched_getaffinity(0))``
Larry Hastings2f936352014-08-05 14:04:04 +100012297[clinic start generated code]*/
12298
Larry Hastings2f936352014-08-05 14:04:04 +100012299static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012300os_cpu_count_impl(PyObject *module)
Serhiy Storchaka2954f832016-07-07 18:20:03 +030012301/*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012302{
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012303 int ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012304#ifdef MS_WINDOWS
Steve Doweraa929272019-09-11 16:15:39 +010012305 ncpu = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012306#elif defined(__hpux)
12307 ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
12308#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
12309 ncpu = sysconf(_SC_NPROCESSORS_ONLN);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012310#elif defined(__DragonFly__) || \
12311 defined(__OpenBSD__) || \
12312 defined(__FreeBSD__) || \
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012313 defined(__NetBSD__) || \
12314 defined(__APPLE__)
Charles-Francois Natali7c4f8da2013-05-20 17:40:32 +020012315 int mib[2];
12316 size_t len = sizeof(ncpu);
12317 mib[0] = CTL_HW;
12318 mib[1] = HW_NCPU;
12319 if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
12320 ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012321#endif
12322 if (ncpu >= 1)
12323 return PyLong_FromLong(ncpu);
12324 else
12325 Py_RETURN_NONE;
12326}
12327
Victor Stinnerdaf45552013-08-28 00:53:59 +020012328
Larry Hastings2f936352014-08-05 14:04:04 +100012329/*[clinic input]
12330os.get_inheritable -> bool
12331
12332 fd: int
12333 /
12334
12335Get the close-on-exe flag of the specified file descriptor.
12336[clinic start generated code]*/
12337
Larry Hastings2f936352014-08-05 14:04:04 +100012338static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012339os_get_inheritable_impl(PyObject *module, int fd)
12340/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012341{
Steve Dower8fc89802015-04-12 00:26:27 -040012342 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -040012343 _Py_BEGIN_SUPPRESS_IPH
12344 return_value = _Py_get_inheritable(fd);
12345 _Py_END_SUPPRESS_IPH
12346 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +100012347}
12348
12349
12350/*[clinic input]
12351os.set_inheritable
12352 fd: int
12353 inheritable: int
12354 /
12355
12356Set the inheritable flag of the specified file descriptor.
12357[clinic start generated code]*/
12358
Larry Hastings2f936352014-08-05 14:04:04 +100012359static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012360os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
12361/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
Victor Stinnerdaf45552013-08-28 00:53:59 +020012362{
Steve Dower8fc89802015-04-12 00:26:27 -040012363 int result;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012364
Steve Dower8fc89802015-04-12 00:26:27 -040012365 _Py_BEGIN_SUPPRESS_IPH
12366 result = _Py_set_inheritable(fd, inheritable, NULL);
12367 _Py_END_SUPPRESS_IPH
12368 if (result < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +020012369 return NULL;
12370 Py_RETURN_NONE;
12371}
12372
12373
12374#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100012375/*[clinic input]
12376os.get_handle_inheritable -> bool
Benjamin Petersonca470632016-09-06 13:47:26 -070012377 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012378 /
Victor Stinnerdaf45552013-08-28 00:53:59 +020012379
Larry Hastings2f936352014-08-05 14:04:04 +100012380Get the close-on-exe flag of the specified file descriptor.
12381[clinic start generated code]*/
12382
Larry Hastings2f936352014-08-05 14:04:04 +100012383static int
Benjamin Petersonca470632016-09-06 13:47:26 -070012384os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
Victor Stinner581139c2016-09-06 15:54:20 -070012385/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012386{
12387 DWORD flags;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012388
12389 if (!GetHandleInformation((HANDLE)handle, &flags)) {
12390 PyErr_SetFromWindowsErr(0);
Larry Hastings2f936352014-08-05 14:04:04 +100012391 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012392 }
12393
Larry Hastings2f936352014-08-05 14:04:04 +100012394 return flags & HANDLE_FLAG_INHERIT;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012395}
12396
Victor Stinnerdaf45552013-08-28 00:53:59 +020012397
Larry Hastings2f936352014-08-05 14:04:04 +100012398/*[clinic input]
12399os.set_handle_inheritable
Benjamin Petersonca470632016-09-06 13:47:26 -070012400 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012401 inheritable: bool
12402 /
12403
12404Set the inheritable flag of the specified handle.
12405[clinic start generated code]*/
12406
Larry Hastings2f936352014-08-05 14:04:04 +100012407static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -070012408os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
Larry Hastings89964c42015-04-14 18:07:59 -040012409 int inheritable)
Victor Stinner581139c2016-09-06 15:54:20 -070012410/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012411{
12412 DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012413 if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
12414 PyErr_SetFromWindowsErr(0);
12415 return NULL;
12416 }
12417 Py_RETURN_NONE;
12418}
Larry Hastings2f936352014-08-05 14:04:04 +100012419#endif /* MS_WINDOWS */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012420
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012421#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012422/*[clinic input]
12423os.get_blocking -> bool
12424 fd: int
12425 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012426
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012427Get the blocking mode of the file descriptor.
12428
12429Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
12430[clinic start generated code]*/
12431
12432static int
12433os_get_blocking_impl(PyObject *module, int fd)
12434/*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012435{
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012436 int blocking;
12437
Steve Dower8fc89802015-04-12 00:26:27 -040012438 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012439 blocking = _Py_get_blocking(fd);
Steve Dower8fc89802015-04-12 00:26:27 -040012440 _Py_END_SUPPRESS_IPH
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012441 return blocking;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012442}
12443
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012444/*[clinic input]
12445os.set_blocking
12446 fd: int
12447 blocking: bool(accept={int})
12448 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012449
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012450Set the blocking mode of the specified file descriptor.
12451
12452Set the O_NONBLOCK flag if blocking is False,
12453clear the O_NONBLOCK flag otherwise.
12454[clinic start generated code]*/
12455
12456static PyObject *
12457os_set_blocking_impl(PyObject *module, int fd, int blocking)
12458/*[clinic end generated code: output=384eb43aa0762a9d input=bf5c8efdc5860ff3]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012459{
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012460 int result;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012461
Steve Dower8fc89802015-04-12 00:26:27 -040012462 _Py_BEGIN_SUPPRESS_IPH
12463 result = _Py_set_blocking(fd, blocking);
12464 _Py_END_SUPPRESS_IPH
12465 if (result < 0)
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012466 return NULL;
12467 Py_RETURN_NONE;
12468}
12469#endif /* !MS_WINDOWS */
12470
12471
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012472/*[clinic input]
Eddie Elizondob3966632019-11-05 07:16:14 -080012473class os.DirEntry "DirEntry *" "DirEntryType"
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012474[clinic start generated code]*/
Eddie Elizondob3966632019-11-05 07:16:14 -080012475/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3c18c7a448247980]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012476
12477typedef struct {
12478 PyObject_HEAD
12479 PyObject *name;
12480 PyObject *path;
12481 PyObject *stat;
12482 PyObject *lstat;
12483#ifdef MS_WINDOWS
12484 struct _Py_stat_struct win32_lstat;
Victor Stinner0f6d7332017-03-09 17:34:28 +010012485 uint64_t win32_file_index;
Victor Stinner6036e442015-03-08 01:58:04 +010012486 int got_file_index;
12487#else /* POSIX */
Victor Stinner35a97c02015-03-08 02:59:09 +010012488#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012489 unsigned char d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012490#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012491 ino_t d_ino;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012492 int dir_fd;
Victor Stinner6036e442015-03-08 01:58:04 +010012493#endif
12494} DirEntry;
12495
Eddie Elizondob3966632019-11-05 07:16:14 -080012496static PyObject *
12497_disabled_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
12498{
12499 PyErr_Format(PyExc_TypeError,
12500 "cannot create '%.100s' instances", _PyType_Name(type));
12501 return NULL;
12502}
12503
Victor Stinner6036e442015-03-08 01:58:04 +010012504static void
12505DirEntry_dealloc(DirEntry *entry)
12506{
Eddie Elizondob3966632019-11-05 07:16:14 -080012507 PyTypeObject *tp = Py_TYPE(entry);
Victor Stinner6036e442015-03-08 01:58:04 +010012508 Py_XDECREF(entry->name);
12509 Py_XDECREF(entry->path);
12510 Py_XDECREF(entry->stat);
12511 Py_XDECREF(entry->lstat);
Eddie Elizondob3966632019-11-05 07:16:14 -080012512 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
12513 free_func(entry);
12514 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010012515}
12516
12517/* Forward reference */
12518static int
12519DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits);
12520
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012521/*[clinic input]
12522os.DirEntry.is_symlink -> bool
12523
12524Return True if the entry is a symbolic link; cached per entry.
12525[clinic start generated code]*/
12526
Victor Stinner6036e442015-03-08 01:58:04 +010012527static int
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012528os_DirEntry_is_symlink_impl(DirEntry *self)
12529/*[clinic end generated code: output=42244667d7bcfc25 input=1605a1b4b96976c3]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012530{
12531#ifdef MS_WINDOWS
12532 return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
Victor Stinner35a97c02015-03-08 02:59:09 +010012533#elif defined(HAVE_DIRENT_D_TYPE)
12534 /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010012535 if (self->d_type != DT_UNKNOWN)
12536 return self->d_type == DT_LNK;
12537 else
12538 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner35a97c02015-03-08 02:59:09 +010012539#else
12540 /* POSIX without d_type */
12541 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner6036e442015-03-08 01:58:04 +010012542#endif
12543}
12544
12545static PyObject *
Victor Stinner6036e442015-03-08 01:58:04 +010012546DirEntry_fetch_stat(DirEntry *self, int follow_symlinks)
12547{
12548 int result;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012549 STRUCT_STAT st;
12550 PyObject *ub;
Victor Stinner6036e442015-03-08 01:58:04 +010012551
12552#ifdef MS_WINDOWS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012553 if (!PyUnicode_FSDecoder(self->path, &ub))
12554 return NULL;
12555 const wchar_t *path = PyUnicode_AsUnicode(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012556#else /* POSIX */
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012557 if (!PyUnicode_FSConverter(self->path, &ub))
12558 return NULL;
12559 const char *path = PyBytes_AS_STRING(ub);
12560 if (self->dir_fd != DEFAULT_DIR_FD) {
12561#ifdef HAVE_FSTATAT
12562 result = fstatat(self->dir_fd, path, &st,
12563 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
12564#else
12565 PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
12566 return NULL;
12567#endif /* HAVE_FSTATAT */
12568 }
12569 else
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012570#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012571 {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012572 if (follow_symlinks)
12573 result = STAT(path, &st);
12574 else
12575 result = LSTAT(path, &st);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012576 }
12577 Py_DECREF(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012578
12579 if (result != 0)
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012580 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012581
12582 return _pystat_fromstructstat(&st);
12583}
12584
12585static PyObject *
12586DirEntry_get_lstat(DirEntry *self)
12587{
12588 if (!self->lstat) {
12589#ifdef MS_WINDOWS
12590 self->lstat = _pystat_fromstructstat(&self->win32_lstat);
12591#else /* POSIX */
12592 self->lstat = DirEntry_fetch_stat(self, 0);
12593#endif
12594 }
12595 Py_XINCREF(self->lstat);
12596 return self->lstat;
12597}
12598
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012599/*[clinic input]
12600os.DirEntry.stat
12601 *
12602 follow_symlinks: bool = True
12603
12604Return stat_result object for the entry; cached per entry.
12605[clinic start generated code]*/
12606
Victor Stinner6036e442015-03-08 01:58:04 +010012607static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012608os_DirEntry_stat_impl(DirEntry *self, int follow_symlinks)
12609/*[clinic end generated code: output=008593b3a6d01305 input=280d14c1d6f1d00d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012610{
12611 if (!follow_symlinks)
12612 return DirEntry_get_lstat(self);
12613
12614 if (!self->stat) {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012615 int result = os_DirEntry_is_symlink_impl(self);
Victor Stinner6036e442015-03-08 01:58:04 +010012616 if (result == -1)
12617 return NULL;
12618 else if (result)
12619 self->stat = DirEntry_fetch_stat(self, 1);
12620 else
12621 self->stat = DirEntry_get_lstat(self);
12622 }
12623
12624 Py_XINCREF(self->stat);
12625 return self->stat;
12626}
12627
Victor Stinner6036e442015-03-08 01:58:04 +010012628/* Set exception and return -1 on error, 0 for False, 1 for True */
12629static int
12630DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
12631{
12632 PyObject *stat = NULL;
12633 PyObject *st_mode = NULL;
12634 long mode;
12635 int result;
Victor Stinner35a97c02015-03-08 02:59:09 +010012636#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012637 int is_symlink;
12638 int need_stat;
Victor Stinner35a97c02015-03-08 02:59:09 +010012639#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012640#ifdef MS_WINDOWS
12641 unsigned long dir_bits;
12642#endif
12643
12644#ifdef MS_WINDOWS
12645 is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
12646 need_stat = follow_symlinks && is_symlink;
Victor Stinner35a97c02015-03-08 02:59:09 +010012647#elif defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012648 is_symlink = self->d_type == DT_LNK;
12649 need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
12650#endif
12651
Victor Stinner35a97c02015-03-08 02:59:09 +010012652#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012653 if (need_stat) {
Victor Stinner35a97c02015-03-08 02:59:09 +010012654#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012655 stat = os_DirEntry_stat_impl(self, follow_symlinks);
Victor Stinner6036e442015-03-08 01:58:04 +010012656 if (!stat) {
12657 if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
12658 /* If file doesn't exist (anymore), then return False
12659 (i.e., say it's not a file/directory) */
12660 PyErr_Clear();
12661 return 0;
12662 }
12663 goto error;
12664 }
Eddie Elizondob3966632019-11-05 07:16:14 -080012665 st_mode = PyObject_GetAttr(stat, _posixstate_global->st_mode);
Victor Stinner6036e442015-03-08 01:58:04 +010012666 if (!st_mode)
12667 goto error;
12668
12669 mode = PyLong_AsLong(st_mode);
12670 if (mode == -1 && PyErr_Occurred())
12671 goto error;
12672 Py_CLEAR(st_mode);
12673 Py_CLEAR(stat);
12674 result = (mode & S_IFMT) == mode_bits;
Victor Stinner35a97c02015-03-08 02:59:09 +010012675#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012676 }
12677 else if (is_symlink) {
12678 assert(mode_bits != S_IFLNK);
12679 result = 0;
12680 }
12681 else {
12682 assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
12683#ifdef MS_WINDOWS
12684 dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
12685 if (mode_bits == S_IFDIR)
12686 result = dir_bits != 0;
12687 else
12688 result = dir_bits == 0;
12689#else /* POSIX */
12690 if (mode_bits == S_IFDIR)
12691 result = self->d_type == DT_DIR;
12692 else
12693 result = self->d_type == DT_REG;
12694#endif
12695 }
Victor Stinner35a97c02015-03-08 02:59:09 +010012696#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012697
12698 return result;
12699
12700error:
12701 Py_XDECREF(st_mode);
12702 Py_XDECREF(stat);
12703 return -1;
12704}
12705
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012706/*[clinic input]
12707os.DirEntry.is_dir -> bool
12708 *
12709 follow_symlinks: bool = True
Victor Stinner6036e442015-03-08 01:58:04 +010012710
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012711Return True if the entry is a directory; cached per entry.
12712[clinic start generated code]*/
12713
12714static int
12715os_DirEntry_is_dir_impl(DirEntry *self, int follow_symlinks)
12716/*[clinic end generated code: output=ad2e8d54365da287 input=0135232766f53f58]*/
12717{
12718 return DirEntry_test_mode(self, follow_symlinks, S_IFDIR);
Victor Stinner6036e442015-03-08 01:58:04 +010012719}
12720
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012721/*[clinic input]
12722os.DirEntry.is_file -> bool
12723 *
12724 follow_symlinks: bool = True
12725
12726Return True if the entry is a file; cached per entry.
12727[clinic start generated code]*/
12728
12729static int
12730os_DirEntry_is_file_impl(DirEntry *self, int follow_symlinks)
12731/*[clinic end generated code: output=8462ade481d8a476 input=0dc90be168b041ee]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012732{
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012733 return DirEntry_test_mode(self, follow_symlinks, S_IFREG);
Victor Stinner6036e442015-03-08 01:58:04 +010012734}
12735
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012736/*[clinic input]
12737os.DirEntry.inode
Victor Stinner6036e442015-03-08 01:58:04 +010012738
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012739Return inode of the entry; cached per entry.
12740[clinic start generated code]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012741
12742static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012743os_DirEntry_inode_impl(DirEntry *self)
12744/*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012745{
12746#ifdef MS_WINDOWS
12747 if (!self->got_file_index) {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012748 PyObject *unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012749 const wchar_t *path;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012750 STRUCT_STAT stat;
12751 int result;
Victor Stinner6036e442015-03-08 01:58:04 +010012752
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012753 if (!PyUnicode_FSDecoder(self->path, &unicode))
Victor Stinner6036e442015-03-08 01:58:04 +010012754 return NULL;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012755 path = PyUnicode_AsUnicode(unicode);
12756 result = LSTAT(path, &stat);
12757 Py_DECREF(unicode);
Victor Stinner6036e442015-03-08 01:58:04 +010012758
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012759 if (result != 0)
12760 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012761
12762 self->win32_file_index = stat.st_ino;
12763 self->got_file_index = 1;
12764 }
Victor Stinner0f6d7332017-03-09 17:34:28 +010012765 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->win32_file_index));
12766 return PyLong_FromUnsignedLongLong(self->win32_file_index);
Victor Stinner6036e442015-03-08 01:58:04 +010012767#else /* POSIX */
xdegaye50e86032017-05-22 11:15:08 +020012768 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->d_ino));
12769 return PyLong_FromUnsignedLongLong(self->d_ino);
Victor Stinner6036e442015-03-08 01:58:04 +010012770#endif
12771}
12772
12773static PyObject *
12774DirEntry_repr(DirEntry *self)
12775{
12776 return PyUnicode_FromFormat("<DirEntry %R>", self->name);
12777}
12778
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012779/*[clinic input]
12780os.DirEntry.__fspath__
12781
12782Returns the path for the entry.
12783[clinic start generated code]*/
12784
Brett Cannon96881cd2016-06-10 14:37:21 -070012785static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012786os_DirEntry___fspath___impl(DirEntry *self)
12787/*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
Brett Cannon96881cd2016-06-10 14:37:21 -070012788{
12789 Py_INCREF(self->path);
12790 return self->path;
12791}
12792
Victor Stinner6036e442015-03-08 01:58:04 +010012793static PyMemberDef DirEntry_members[] = {
12794 {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
12795 "the entry's base filename, relative to scandir() \"path\" argument"},
12796 {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
12797 "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
12798 {NULL}
12799};
12800
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012801#include "clinic/posixmodule.c.h"
12802
Victor Stinner6036e442015-03-08 01:58:04 +010012803static PyMethodDef DirEntry_methods[] = {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012804 OS_DIRENTRY_IS_DIR_METHODDEF
12805 OS_DIRENTRY_IS_FILE_METHODDEF
12806 OS_DIRENTRY_IS_SYMLINK_METHODDEF
12807 OS_DIRENTRY_STAT_METHODDEF
12808 OS_DIRENTRY_INODE_METHODDEF
12809 OS_DIRENTRY___FSPATH___METHODDEF
Victor Stinner6036e442015-03-08 01:58:04 +010012810 {NULL}
12811};
12812
Eddie Elizondob3966632019-11-05 07:16:14 -080012813static PyType_Slot DirEntryType_slots[] = {
12814 {Py_tp_new, _disabled_new},
12815 {Py_tp_dealloc, DirEntry_dealloc},
12816 {Py_tp_repr, DirEntry_repr},
12817 {Py_tp_methods, DirEntry_methods},
12818 {Py_tp_members, DirEntry_members},
12819 {0, 0},
Victor Stinner6036e442015-03-08 01:58:04 +010012820};
12821
Eddie Elizondob3966632019-11-05 07:16:14 -080012822static PyType_Spec DirEntryType_spec = {
12823 MODNAME ".DirEntry",
12824 sizeof(DirEntry),
12825 0,
12826 Py_TPFLAGS_DEFAULT,
12827 DirEntryType_slots
12828};
12829
12830
Victor Stinner6036e442015-03-08 01:58:04 +010012831#ifdef MS_WINDOWS
12832
12833static wchar_t *
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012834join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
Victor Stinner6036e442015-03-08 01:58:04 +010012835{
12836 Py_ssize_t path_len;
12837 Py_ssize_t size;
12838 wchar_t *result;
12839 wchar_t ch;
12840
12841 if (!path_wide) { /* Default arg: "." */
12842 path_wide = L".";
12843 path_len = 1;
12844 }
12845 else {
12846 path_len = wcslen(path_wide);
12847 }
12848
12849 /* The +1's are for the path separator and the NUL */
12850 size = path_len + 1 + wcslen(filename) + 1;
12851 result = PyMem_New(wchar_t, size);
12852 if (!result) {
12853 PyErr_NoMemory();
12854 return NULL;
12855 }
12856 wcscpy(result, path_wide);
12857 if (path_len > 0) {
12858 ch = result[path_len - 1];
12859 if (ch != SEP && ch != ALTSEP && ch != L':')
12860 result[path_len++] = SEP;
12861 wcscpy(result + path_len, filename);
12862 }
12863 return result;
12864}
12865
12866static PyObject *
12867DirEntry_from_find_data(path_t *path, WIN32_FIND_DATAW *dataW)
12868{
12869 DirEntry *entry;
12870 BY_HANDLE_FILE_INFORMATION file_info;
12871 ULONG reparse_tag;
12872 wchar_t *joined_path;
12873
Eddie Elizondob3966632019-11-05 07:16:14 -080012874 PyObject *DirEntryType = _posixstate_global->DirEntryType;
12875 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010012876 if (!entry)
12877 return NULL;
12878 entry->name = NULL;
12879 entry->path = NULL;
12880 entry->stat = NULL;
12881 entry->lstat = NULL;
12882 entry->got_file_index = 0;
12883
12884 entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
12885 if (!entry->name)
12886 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012887 if (path->narrow) {
12888 Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
12889 if (!entry->name)
12890 goto error;
12891 }
Victor Stinner6036e442015-03-08 01:58:04 +010012892
12893 joined_path = join_path_filenameW(path->wide, dataW->cFileName);
12894 if (!joined_path)
12895 goto error;
12896
12897 entry->path = PyUnicode_FromWideChar(joined_path, -1);
12898 PyMem_Free(joined_path);
12899 if (!entry->path)
12900 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012901 if (path->narrow) {
12902 Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
12903 if (!entry->path)
12904 goto error;
12905 }
Victor Stinner6036e442015-03-08 01:58:04 +010012906
Steve Dowercc16be82016-09-08 10:35:16 -070012907 find_data_to_file_info(dataW, &file_info, &reparse_tag);
Victor Stinner6036e442015-03-08 01:58:04 +010012908 _Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
12909
12910 return (PyObject *)entry;
12911
12912error:
12913 Py_DECREF(entry);
12914 return NULL;
12915}
12916
12917#else /* POSIX */
12918
12919static char *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012920join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
Victor Stinner6036e442015-03-08 01:58:04 +010012921{
12922 Py_ssize_t path_len;
12923 Py_ssize_t size;
12924 char *result;
12925
12926 if (!path_narrow) { /* Default arg: "." */
12927 path_narrow = ".";
12928 path_len = 1;
12929 }
12930 else {
12931 path_len = strlen(path_narrow);
12932 }
12933
12934 if (filename_len == -1)
12935 filename_len = strlen(filename);
12936
12937 /* The +1's are for the path separator and the NUL */
12938 size = path_len + 1 + filename_len + 1;
12939 result = PyMem_New(char, size);
12940 if (!result) {
12941 PyErr_NoMemory();
12942 return NULL;
12943 }
12944 strcpy(result, path_narrow);
12945 if (path_len > 0 && result[path_len - 1] != '/')
12946 result[path_len++] = '/';
12947 strcpy(result + path_len, filename);
12948 return result;
12949}
12950
12951static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012952DirEntry_from_posix_info(path_t *path, const char *name, Py_ssize_t name_len,
Victor Stinner35a97c02015-03-08 02:59:09 +010012953 ino_t d_ino
12954#ifdef HAVE_DIRENT_D_TYPE
12955 , unsigned char d_type
12956#endif
12957 )
Victor Stinner6036e442015-03-08 01:58:04 +010012958{
12959 DirEntry *entry;
12960 char *joined_path;
12961
Eddie Elizondob3966632019-11-05 07:16:14 -080012962 PyObject *DirEntryType = _posixstate_global->DirEntryType;
12963 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010012964 if (!entry)
12965 return NULL;
12966 entry->name = NULL;
12967 entry->path = NULL;
12968 entry->stat = NULL;
12969 entry->lstat = NULL;
12970
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012971 if (path->fd != -1) {
12972 entry->dir_fd = path->fd;
12973 joined_path = NULL;
12974 }
12975 else {
12976 entry->dir_fd = DEFAULT_DIR_FD;
12977 joined_path = join_path_filename(path->narrow, name, name_len);
12978 if (!joined_path)
12979 goto error;
12980 }
Victor Stinner6036e442015-03-08 01:58:04 +010012981
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +030012982 if (!path->narrow || !PyObject_CheckBuffer(path->object)) {
Victor Stinner6036e442015-03-08 01:58:04 +010012983 entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012984 if (joined_path)
12985 entry->path = PyUnicode_DecodeFSDefault(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010012986 }
12987 else {
12988 entry->name = PyBytes_FromStringAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012989 if (joined_path)
12990 entry->path = PyBytes_FromString(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010012991 }
12992 PyMem_Free(joined_path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012993 if (!entry->name)
12994 goto error;
12995
12996 if (path->fd != -1) {
12997 entry->path = entry->name;
12998 Py_INCREF(entry->path);
12999 }
13000 else if (!entry->path)
Victor Stinner6036e442015-03-08 01:58:04 +010013001 goto error;
13002
Victor Stinner35a97c02015-03-08 02:59:09 +010013003#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010013004 entry->d_type = d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010013005#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013006 entry->d_ino = d_ino;
13007
13008 return (PyObject *)entry;
13009
13010error:
13011 Py_XDECREF(entry);
13012 return NULL;
13013}
13014
13015#endif
13016
13017
13018typedef struct {
13019 PyObject_HEAD
13020 path_t path;
13021#ifdef MS_WINDOWS
13022 HANDLE handle;
13023 WIN32_FIND_DATAW file_data;
13024 int first_time;
13025#else /* POSIX */
13026 DIR *dirp;
13027#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013028#ifdef HAVE_FDOPENDIR
13029 int fd;
13030#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013031} ScandirIterator;
13032
13033#ifdef MS_WINDOWS
13034
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013035static int
13036ScandirIterator_is_closed(ScandirIterator *iterator)
13037{
13038 return iterator->handle == INVALID_HANDLE_VALUE;
13039}
13040
Victor Stinner6036e442015-03-08 01:58:04 +010013041static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013042ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013043{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013044 HANDLE handle = iterator->handle;
13045
13046 if (handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013047 return;
13048
Victor Stinner6036e442015-03-08 01:58:04 +010013049 iterator->handle = INVALID_HANDLE_VALUE;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013050 Py_BEGIN_ALLOW_THREADS
13051 FindClose(handle);
13052 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013053}
13054
13055static PyObject *
13056ScandirIterator_iternext(ScandirIterator *iterator)
13057{
13058 WIN32_FIND_DATAW *file_data = &iterator->file_data;
13059 BOOL success;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013060 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013061
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013062 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013063 if (iterator->handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013064 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013065
13066 while (1) {
13067 if (!iterator->first_time) {
13068 Py_BEGIN_ALLOW_THREADS
13069 success = FindNextFileW(iterator->handle, file_data);
13070 Py_END_ALLOW_THREADS
13071 if (!success) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013072 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013073 if (GetLastError() != ERROR_NO_MORE_FILES)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013074 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013075 break;
13076 }
13077 }
13078 iterator->first_time = 0;
13079
13080 /* Skip over . and .. */
13081 if (wcscmp(file_data->cFileName, L".") != 0 &&
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013082 wcscmp(file_data->cFileName, L"..") != 0) {
13083 entry = DirEntry_from_find_data(&iterator->path, file_data);
13084 if (!entry)
13085 break;
13086 return entry;
13087 }
Victor Stinner6036e442015-03-08 01:58:04 +010013088
13089 /* Loop till we get a non-dot directory or finish iterating */
13090 }
13091
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013092 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013093 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013094 return NULL;
13095}
13096
13097#else /* POSIX */
13098
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013099static int
13100ScandirIterator_is_closed(ScandirIterator *iterator)
13101{
13102 return !iterator->dirp;
13103}
13104
Victor Stinner6036e442015-03-08 01:58:04 +010013105static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013106ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013107{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013108 DIR *dirp = iterator->dirp;
13109
13110 if (!dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013111 return;
13112
Victor Stinner6036e442015-03-08 01:58:04 +010013113 iterator->dirp = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013114 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013115#ifdef HAVE_FDOPENDIR
13116 if (iterator->path.fd != -1)
13117 rewinddir(dirp);
13118#endif
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013119 closedir(dirp);
13120 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013121 return;
13122}
13123
13124static PyObject *
13125ScandirIterator_iternext(ScandirIterator *iterator)
13126{
13127 struct dirent *direntp;
13128 Py_ssize_t name_len;
13129 int is_dot;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013130 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013131
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013132 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013133 if (!iterator->dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013134 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013135
13136 while (1) {
13137 errno = 0;
13138 Py_BEGIN_ALLOW_THREADS
13139 direntp = readdir(iterator->dirp);
13140 Py_END_ALLOW_THREADS
13141
13142 if (!direntp) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013143 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013144 if (errno != 0)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013145 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013146 break;
13147 }
13148
13149 /* Skip over . and .. */
13150 name_len = NAMLEN(direntp);
13151 is_dot = direntp->d_name[0] == '.' &&
13152 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
13153 if (!is_dot) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013154 entry = DirEntry_from_posix_info(&iterator->path, direntp->d_name,
Victor Stinner35a97c02015-03-08 02:59:09 +010013155 name_len, direntp->d_ino
13156#ifdef HAVE_DIRENT_D_TYPE
13157 , direntp->d_type
13158#endif
13159 );
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013160 if (!entry)
13161 break;
13162 return entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013163 }
13164
13165 /* Loop till we get a non-dot directory or finish iterating */
13166 }
13167
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013168 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013169 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013170 return NULL;
13171}
13172
13173#endif
13174
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013175static PyObject *
13176ScandirIterator_close(ScandirIterator *self, PyObject *args)
13177{
13178 ScandirIterator_closedir(self);
13179 Py_RETURN_NONE;
13180}
13181
13182static PyObject *
13183ScandirIterator_enter(PyObject *self, PyObject *args)
13184{
13185 Py_INCREF(self);
13186 return self;
13187}
13188
13189static PyObject *
13190ScandirIterator_exit(ScandirIterator *self, PyObject *args)
13191{
13192 ScandirIterator_closedir(self);
13193 Py_RETURN_NONE;
13194}
13195
Victor Stinner6036e442015-03-08 01:58:04 +010013196static void
Victor Stinner7bfa4092016-03-23 00:43:54 +010013197ScandirIterator_finalize(ScandirIterator *iterator)
13198{
13199 PyObject *error_type, *error_value, *error_traceback;
13200
13201 /* Save the current exception, if any. */
13202 PyErr_Fetch(&error_type, &error_value, &error_traceback);
13203
13204 if (!ScandirIterator_is_closed(iterator)) {
13205 ScandirIterator_closedir(iterator);
13206
13207 if (PyErr_ResourceWarning((PyObject *)iterator, 1,
13208 "unclosed scandir iterator %R", iterator)) {
13209 /* Spurious errors can appear at shutdown */
13210 if (PyErr_ExceptionMatches(PyExc_Warning)) {
13211 PyErr_WriteUnraisable((PyObject *) iterator);
13212 }
13213 }
13214 }
13215
Victor Stinner7bfa4092016-03-23 00:43:54 +010013216 path_cleanup(&iterator->path);
13217
13218 /* Restore the saved exception. */
13219 PyErr_Restore(error_type, error_value, error_traceback);
13220}
13221
13222static void
Victor Stinner6036e442015-03-08 01:58:04 +010013223ScandirIterator_dealloc(ScandirIterator *iterator)
13224{
Eddie Elizondob3966632019-11-05 07:16:14 -080013225 PyTypeObject *tp = Py_TYPE(iterator);
Victor Stinner7bfa4092016-03-23 00:43:54 +010013226 if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
13227 return;
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013228
Eddie Elizondob3966632019-11-05 07:16:14 -080013229 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
13230 free_func(iterator);
13231 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010013232}
13233
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013234static PyMethodDef ScandirIterator_methods[] = {
13235 {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
13236 {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
13237 {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
13238 {NULL}
13239};
13240
Eddie Elizondob3966632019-11-05 07:16:14 -080013241static PyType_Slot ScandirIteratorType_slots[] = {
13242 {Py_tp_new, _disabled_new},
13243 {Py_tp_dealloc, ScandirIterator_dealloc},
13244 {Py_tp_finalize, ScandirIterator_finalize},
13245 {Py_tp_iter, PyObject_SelfIter},
13246 {Py_tp_iternext, ScandirIterator_iternext},
13247 {Py_tp_methods, ScandirIterator_methods},
13248 {0, 0},
13249};
13250
13251static PyType_Spec ScandirIteratorType_spec = {
13252 MODNAME ".ScandirIterator",
13253 sizeof(ScandirIterator),
13254 0,
13255 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE,
13256 ScandirIteratorType_slots
Victor Stinner6036e442015-03-08 01:58:04 +010013257};
13258
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013259/*[clinic input]
13260os.scandir
13261
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013262 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013263
13264Return an iterator of DirEntry objects for given path.
13265
BNMetricsb9427072018-11-02 15:20:19 +000013266path can be specified as either str, bytes, or a path-like object. If path
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013267is bytes, the names of yielded DirEntry objects will also be bytes; in
13268all other circumstances they will be str.
13269
13270If path is None, uses the path='.'.
13271[clinic start generated code]*/
13272
Victor Stinner6036e442015-03-08 01:58:04 +010013273static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013274os_scandir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +000013275/*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013276{
13277 ScandirIterator *iterator;
Victor Stinner6036e442015-03-08 01:58:04 +010013278#ifdef MS_WINDOWS
13279 wchar_t *path_strW;
13280#else
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013281 const char *path_str;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013282#ifdef HAVE_FDOPENDIR
13283 int fd = -1;
13284#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013285#endif
13286
Steve Dower60419a72019-06-24 08:42:54 -070013287 if (PySys_Audit("os.scandir", "O",
13288 path->object ? path->object : Py_None) < 0) {
13289 return NULL;
13290 }
13291
Eddie Elizondob3966632019-11-05 07:16:14 -080013292 PyObject *ScandirIteratorType = _posixstate(module)->ScandirIteratorType;
13293 iterator = PyObject_New(ScandirIterator, (PyTypeObject *)ScandirIteratorType);
Victor Stinner6036e442015-03-08 01:58:04 +010013294 if (!iterator)
13295 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013296
13297#ifdef MS_WINDOWS
13298 iterator->handle = INVALID_HANDLE_VALUE;
13299#else
13300 iterator->dirp = NULL;
13301#endif
13302
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013303 memcpy(&iterator->path, path, sizeof(path_t));
Serhiy Storchaka095ef732017-02-09 20:05:51 +020013304 /* Move the ownership to iterator->path */
13305 path->object = NULL;
13306 path->cleanup = NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013307
13308#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +010013309 iterator->first_time = 1;
13310
13311 path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
13312 if (!path_strW)
13313 goto error;
13314
13315 Py_BEGIN_ALLOW_THREADS
13316 iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
13317 Py_END_ALLOW_THREADS
13318
13319 PyMem_Free(path_strW);
13320
13321 if (iterator->handle == INVALID_HANDLE_VALUE) {
13322 path_error(&iterator->path);
13323 goto error;
13324 }
13325#else /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010013326 errno = 0;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013327#ifdef HAVE_FDOPENDIR
13328 if (path->fd != -1) {
13329 /* closedir() closes the FD, so we duplicate it */
13330 fd = _Py_dup(path->fd);
13331 if (fd == -1)
13332 goto error;
13333
13334 Py_BEGIN_ALLOW_THREADS
13335 iterator->dirp = fdopendir(fd);
13336 Py_END_ALLOW_THREADS
13337 }
13338 else
13339#endif
13340 {
13341 if (iterator->path.narrow)
13342 path_str = iterator->path.narrow;
13343 else
13344 path_str = ".";
13345
13346 Py_BEGIN_ALLOW_THREADS
13347 iterator->dirp = opendir(path_str);
13348 Py_END_ALLOW_THREADS
13349 }
Victor Stinner6036e442015-03-08 01:58:04 +010013350
13351 if (!iterator->dirp) {
13352 path_error(&iterator->path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013353#ifdef HAVE_FDOPENDIR
13354 if (fd != -1) {
13355 Py_BEGIN_ALLOW_THREADS
13356 close(fd);
13357 Py_END_ALLOW_THREADS
13358 }
13359#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013360 goto error;
13361 }
13362#endif
13363
13364 return (PyObject *)iterator;
13365
13366error:
13367 Py_DECREF(iterator);
13368 return NULL;
13369}
13370
Ethan Furman410ef8e2016-06-04 12:06:26 -070013371/*
13372 Return the file system path representation of the object.
13373
13374 If the object is str or bytes, then allow it to pass through with
13375 an incremented refcount. If the object defines __fspath__(), then
13376 return the result of that method. All other types raise a TypeError.
13377*/
13378PyObject *
13379PyOS_FSPath(PyObject *path)
13380{
Brett Cannon3f9183b2016-08-26 14:44:48 -070013381 /* For error message reasons, this function is manually inlined in
13382 path_converter(). */
Ethan Furman410ef8e2016-06-04 12:06:26 -070013383 PyObject *func = NULL;
13384 PyObject *path_repr = NULL;
13385
13386 if (PyUnicode_Check(path) || PyBytes_Check(path)) {
13387 Py_INCREF(path);
13388 return path;
13389 }
13390
13391 func = _PyObject_LookupSpecial(path, &PyId___fspath__);
13392 if (NULL == func) {
13393 return PyErr_Format(PyExc_TypeError,
13394 "expected str, bytes or os.PathLike object, "
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013395 "not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -080013396 _PyType_Name(Py_TYPE(path)));
Ethan Furman410ef8e2016-06-04 12:06:26 -070013397 }
13398
Victor Stinnerf17c3de2016-12-06 18:46:19 +010013399 path_repr = _PyObject_CallNoArg(func);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013400 Py_DECREF(func);
Brett Cannon044283a2016-07-15 10:41:49 -070013401 if (NULL == path_repr) {
13402 return NULL;
13403 }
13404
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013405 if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
13406 PyErr_Format(PyExc_TypeError,
13407 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -080013408 "not %.200s", _PyType_Name(Py_TYPE(path)),
13409 _PyType_Name(Py_TYPE(path_repr)));
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013410 Py_DECREF(path_repr);
13411 return NULL;
13412 }
13413
Ethan Furman410ef8e2016-06-04 12:06:26 -070013414 return path_repr;
13415}
13416
13417/*[clinic input]
13418os.fspath
13419
13420 path: object
13421
13422Return the file system path representation of the object.
13423
Brett Cannonb4f43e92016-06-09 14:32:08 -070013424If the object is str or bytes, then allow it to pass through as-is. If the
13425object defines __fspath__(), then return the result of that method. All other
13426types raise a TypeError.
Ethan Furman410ef8e2016-06-04 12:06:26 -070013427[clinic start generated code]*/
13428
13429static PyObject *
Serhiy Storchaka2954f832016-07-07 18:20:03 +030013430os_fspath_impl(PyObject *module, PyObject *path)
13431/*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
Ethan Furman410ef8e2016-06-04 12:06:26 -070013432{
13433 return PyOS_FSPath(path);
13434}
Victor Stinner6036e442015-03-08 01:58:04 +010013435
Victor Stinner9b1f4742016-09-06 16:18:52 -070013436#ifdef HAVE_GETRANDOM_SYSCALL
13437/*[clinic input]
13438os.getrandom
13439
13440 size: Py_ssize_t
13441 flags: int=0
13442
13443Obtain a series of random bytes.
13444[clinic start generated code]*/
13445
13446static PyObject *
13447os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
13448/*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
13449{
Victor Stinner9b1f4742016-09-06 16:18:52 -070013450 PyObject *bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013451 Py_ssize_t n;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013452
13453 if (size < 0) {
13454 errno = EINVAL;
13455 return posix_error();
13456 }
13457
Victor Stinnerec2319c2016-09-20 23:00:59 +020013458 bytes = PyBytes_FromStringAndSize(NULL, size);
13459 if (bytes == NULL) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013460 PyErr_NoMemory();
13461 return NULL;
13462 }
13463
13464 while (1) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013465 n = syscall(SYS_getrandom,
13466 PyBytes_AS_STRING(bytes),
13467 PyBytes_GET_SIZE(bytes),
13468 flags);
Victor Stinner9b1f4742016-09-06 16:18:52 -070013469 if (n < 0 && errno == EINTR) {
13470 if (PyErr_CheckSignals() < 0) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013471 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013472 }
Victor Stinnerec2319c2016-09-20 23:00:59 +020013473
13474 /* getrandom() was interrupted by a signal: retry */
Victor Stinner9b1f4742016-09-06 16:18:52 -070013475 continue;
13476 }
13477 break;
13478 }
13479
13480 if (n < 0) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013481 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerec2319c2016-09-20 23:00:59 +020013482 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013483 }
13484
Victor Stinnerec2319c2016-09-20 23:00:59 +020013485 if (n != size) {
13486 _PyBytes_Resize(&bytes, n);
13487 }
Victor Stinner9b1f4742016-09-06 16:18:52 -070013488
13489 return bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013490
13491error:
13492 Py_DECREF(bytes);
13493 return NULL;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013494}
13495#endif /* HAVE_GETRANDOM_SYSCALL */
13496
Steve Dower2438cdf2019-03-29 16:37:16 -070013497#ifdef MS_WINDOWS
13498/* bpo-36085: Helper functions for managing DLL search directories
13499 * on win32
13500 */
13501
13502typedef DLL_DIRECTORY_COOKIE (WINAPI *PAddDllDirectory)(PCWSTR newDirectory);
13503typedef BOOL (WINAPI *PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE cookie);
13504
13505/*[clinic input]
13506os._add_dll_directory
13507
13508 path: path_t
13509
13510Add a path to the DLL search path.
13511
13512This search path is used when resolving dependencies for imported
13513extension modules (the module itself is resolved through sys.path),
13514and also by ctypes.
13515
13516Returns an opaque value that may be passed to os.remove_dll_directory
13517to remove this directory from the search path.
13518[clinic start generated code]*/
13519
13520static PyObject *
13521os__add_dll_directory_impl(PyObject *module, path_t *path)
13522/*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
13523{
13524 HMODULE hKernel32;
13525 PAddDllDirectory AddDllDirectory;
13526 DLL_DIRECTORY_COOKIE cookie = 0;
13527 DWORD err = 0;
13528
13529 /* For Windows 7, we have to load this. As this will be a fairly
13530 infrequent operation, just do it each time. Kernel32 is always
13531 loaded. */
13532 Py_BEGIN_ALLOW_THREADS
13533 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13534 !(AddDllDirectory = (PAddDllDirectory)GetProcAddress(
13535 hKernel32, "AddDllDirectory")) ||
13536 !(cookie = (*AddDllDirectory)(path->wide))) {
13537 err = GetLastError();
13538 }
13539 Py_END_ALLOW_THREADS
13540
13541 if (err) {
13542 return win32_error_object_err("add_dll_directory",
13543 path->object, err);
13544 }
13545
13546 return PyCapsule_New(cookie, "DLL directory cookie", NULL);
13547}
13548
13549/*[clinic input]
13550os._remove_dll_directory
13551
13552 cookie: object
13553
13554Removes a path from the DLL search path.
13555
13556The parameter is an opaque value that was returned from
13557os.add_dll_directory. You can only remove directories that you added
13558yourself.
13559[clinic start generated code]*/
13560
13561static PyObject *
13562os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
13563/*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
13564{
13565 HMODULE hKernel32;
13566 PRemoveDllDirectory RemoveDllDirectory;
13567 DLL_DIRECTORY_COOKIE cookieValue;
13568 DWORD err = 0;
13569
13570 if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
13571 PyErr_SetString(PyExc_TypeError,
13572 "Provided cookie was not returned from os.add_dll_directory");
13573 return NULL;
13574 }
13575
13576 cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
13577 cookie, "DLL directory cookie");
13578
13579 /* For Windows 7, we have to load this. As this will be a fairly
13580 infrequent operation, just do it each time. Kernel32 is always
13581 loaded. */
13582 Py_BEGIN_ALLOW_THREADS
13583 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13584 !(RemoveDllDirectory = (PRemoveDllDirectory)GetProcAddress(
13585 hKernel32, "RemoveDllDirectory")) ||
13586 !(*RemoveDllDirectory)(cookieValue)) {
13587 err = GetLastError();
13588 }
13589 Py_END_ALLOW_THREADS
13590
13591 if (err) {
13592 return win32_error_object_err("remove_dll_directory",
13593 NULL, err);
13594 }
13595
13596 if (PyCapsule_SetName(cookie, NULL)) {
13597 return NULL;
13598 }
13599
13600 Py_RETURN_NONE;
13601}
13602
13603#endif
Larry Hastings31826802013-10-19 00:09:25 -070013604
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013605static PyMethodDef posix_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -070013606
13607 OS_STAT_METHODDEF
13608 OS_ACCESS_METHODDEF
13609 OS_TTYNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013610 OS_CHDIR_METHODDEF
13611 OS_CHFLAGS_METHODDEF
13612 OS_CHMOD_METHODDEF
13613 OS_FCHMOD_METHODDEF
13614 OS_LCHMOD_METHODDEF
13615 OS_CHOWN_METHODDEF
13616 OS_FCHOWN_METHODDEF
13617 OS_LCHOWN_METHODDEF
13618 OS_LCHFLAGS_METHODDEF
13619 OS_CHROOT_METHODDEF
13620 OS_CTERMID_METHODDEF
13621 OS_GETCWD_METHODDEF
13622 OS_GETCWDB_METHODDEF
13623 OS_LINK_METHODDEF
13624 OS_LISTDIR_METHODDEF
13625 OS_LSTAT_METHODDEF
13626 OS_MKDIR_METHODDEF
13627 OS_NICE_METHODDEF
13628 OS_GETPRIORITY_METHODDEF
13629 OS_SETPRIORITY_METHODDEF
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000013630 OS_POSIX_SPAWN_METHODDEF
Joannah Nanjekye92b83222019-01-16 16:29:26 +030013631 OS_POSIX_SPAWNP_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013632 OS_READLINK_METHODDEF
Pablo Galindoaac4d032019-05-31 19:39:47 +010013633 OS_COPY_FILE_RANGE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013634 OS_RENAME_METHODDEF
13635 OS_REPLACE_METHODDEF
13636 OS_RMDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013637 OS_SYMLINK_METHODDEF
13638 OS_SYSTEM_METHODDEF
13639 OS_UMASK_METHODDEF
13640 OS_UNAME_METHODDEF
13641 OS_UNLINK_METHODDEF
13642 OS_REMOVE_METHODDEF
13643 OS_UTIME_METHODDEF
13644 OS_TIMES_METHODDEF
13645 OS__EXIT_METHODDEF
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020013646 OS__FCOPYFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013647 OS_EXECV_METHODDEF
13648 OS_EXECVE_METHODDEF
13649 OS_SPAWNV_METHODDEF
13650 OS_SPAWNVE_METHODDEF
13651 OS_FORK1_METHODDEF
13652 OS_FORK_METHODDEF
Antoine Pitrou346cbd32017-05-27 17:50:54 +020013653 OS_REGISTER_AT_FORK_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013654 OS_SCHED_GET_PRIORITY_MAX_METHODDEF
13655 OS_SCHED_GET_PRIORITY_MIN_METHODDEF
13656 OS_SCHED_GETPARAM_METHODDEF
13657 OS_SCHED_GETSCHEDULER_METHODDEF
13658 OS_SCHED_RR_GET_INTERVAL_METHODDEF
13659 OS_SCHED_SETPARAM_METHODDEF
13660 OS_SCHED_SETSCHEDULER_METHODDEF
13661 OS_SCHED_YIELD_METHODDEF
13662 OS_SCHED_SETAFFINITY_METHODDEF
13663 OS_SCHED_GETAFFINITY_METHODDEF
13664 OS_OPENPTY_METHODDEF
13665 OS_FORKPTY_METHODDEF
13666 OS_GETEGID_METHODDEF
13667 OS_GETEUID_METHODDEF
13668 OS_GETGID_METHODDEF
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +020013669#ifdef HAVE_GETGROUPLIST
13670 {"getgrouplist", posix_getgrouplist, METH_VARARGS, posix_getgrouplist__doc__},
13671#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013672 OS_GETGROUPS_METHODDEF
13673 OS_GETPID_METHODDEF
13674 OS_GETPGRP_METHODDEF
13675 OS_GETPPID_METHODDEF
13676 OS_GETUID_METHODDEF
13677 OS_GETLOGIN_METHODDEF
13678 OS_KILL_METHODDEF
13679 OS_KILLPG_METHODDEF
13680 OS_PLOCK_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013681#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -070013682 OS_STARTFILE_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013683#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013684 OS_SETUID_METHODDEF
13685 OS_SETEUID_METHODDEF
13686 OS_SETREUID_METHODDEF
13687 OS_SETGID_METHODDEF
13688 OS_SETEGID_METHODDEF
13689 OS_SETREGID_METHODDEF
13690 OS_SETGROUPS_METHODDEF
Antoine Pitroub7572f02009-12-02 20:46:48 +000013691#ifdef HAVE_INITGROUPS
Victor Stinner8c62be82010-05-06 00:08:46 +000013692 {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__},
Antoine Pitroub7572f02009-12-02 20:46:48 +000013693#endif /* HAVE_INITGROUPS */
Larry Hastings2f936352014-08-05 14:04:04 +100013694 OS_GETPGID_METHODDEF
13695 OS_SETPGRP_METHODDEF
13696 OS_WAIT_METHODDEF
13697 OS_WAIT3_METHODDEF
13698 OS_WAIT4_METHODDEF
13699 OS_WAITID_METHODDEF
13700 OS_WAITPID_METHODDEF
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -080013701 OS_PIDFD_OPEN_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013702 OS_GETSID_METHODDEF
13703 OS_SETSID_METHODDEF
13704 OS_SETPGID_METHODDEF
13705 OS_TCGETPGRP_METHODDEF
13706 OS_TCSETPGRP_METHODDEF
13707 OS_OPEN_METHODDEF
13708 OS_CLOSE_METHODDEF
13709 OS_CLOSERANGE_METHODDEF
13710 OS_DEVICE_ENCODING_METHODDEF
13711 OS_DUP_METHODDEF
13712 OS_DUP2_METHODDEF
13713 OS_LOCKF_METHODDEF
13714 OS_LSEEK_METHODDEF
13715 OS_READ_METHODDEF
13716 OS_READV_METHODDEF
13717 OS_PREAD_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013718 OS_PREADV_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013719 OS_WRITE_METHODDEF
13720 OS_WRITEV_METHODDEF
13721 OS_PWRITE_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013722 OS_PWRITEV_METHODDEF
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013723#ifdef HAVE_SENDFILE
Serhiy Storchaka62be7422018-11-27 13:27:31 +020013724 {"sendfile", (PyCFunction)(void(*)(void))posix_sendfile, METH_VARARGS | METH_KEYWORDS,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013725 posix_sendfile__doc__},
13726#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013727 OS_FSTAT_METHODDEF
13728 OS_ISATTY_METHODDEF
13729 OS_PIPE_METHODDEF
13730 OS_PIPE2_METHODDEF
13731 OS_MKFIFO_METHODDEF
13732 OS_MKNOD_METHODDEF
13733 OS_MAJOR_METHODDEF
13734 OS_MINOR_METHODDEF
13735 OS_MAKEDEV_METHODDEF
13736 OS_FTRUNCATE_METHODDEF
13737 OS_TRUNCATE_METHODDEF
13738 OS_POSIX_FALLOCATE_METHODDEF
13739 OS_POSIX_FADVISE_METHODDEF
13740 OS_PUTENV_METHODDEF
13741 OS_UNSETENV_METHODDEF
13742 OS_STRERROR_METHODDEF
13743 OS_FCHDIR_METHODDEF
13744 OS_FSYNC_METHODDEF
13745 OS_SYNC_METHODDEF
13746 OS_FDATASYNC_METHODDEF
13747 OS_WCOREDUMP_METHODDEF
13748 OS_WIFCONTINUED_METHODDEF
13749 OS_WIFSTOPPED_METHODDEF
13750 OS_WIFSIGNALED_METHODDEF
13751 OS_WIFEXITED_METHODDEF
13752 OS_WEXITSTATUS_METHODDEF
13753 OS_WTERMSIG_METHODDEF
13754 OS_WSTOPSIG_METHODDEF
13755 OS_FSTATVFS_METHODDEF
13756 OS_STATVFS_METHODDEF
13757 OS_CONFSTR_METHODDEF
13758 OS_SYSCONF_METHODDEF
13759 OS_FPATHCONF_METHODDEF
13760 OS_PATHCONF_METHODDEF
13761 OS_ABORT_METHODDEF
Serhiy Storchakaf0b50152015-05-13 00:52:39 +030013762 OS__GETFULLPATHNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013763 OS__GETDISKUSAGE_METHODDEF
13764 OS__GETFINALPATHNAME_METHODDEF
13765 OS__GETVOLUMEPATHNAME_METHODDEF
13766 OS_GETLOADAVG_METHODDEF
13767 OS_URANDOM_METHODDEF
13768 OS_SETRESUID_METHODDEF
13769 OS_SETRESGID_METHODDEF
13770 OS_GETRESUID_METHODDEF
13771 OS_GETRESGID_METHODDEF
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000013772
Larry Hastings2f936352014-08-05 14:04:04 +100013773 OS_GETXATTR_METHODDEF
13774 OS_SETXATTR_METHODDEF
13775 OS_REMOVEXATTR_METHODDEF
13776 OS_LISTXATTR_METHODDEF
13777
Antoine Pitroubcf2b592012-02-08 23:28:36 +010013778#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
13779 {"get_terminal_size", get_terminal_size, METH_VARARGS, termsize__doc__},
13780#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013781 OS_CPU_COUNT_METHODDEF
13782 OS_GET_INHERITABLE_METHODDEF
13783 OS_SET_INHERITABLE_METHODDEF
13784 OS_GET_HANDLE_INHERITABLE_METHODDEF
13785 OS_SET_HANDLE_INHERITABLE_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013786#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013787 OS_GET_BLOCKING_METHODDEF
13788 OS_SET_BLOCKING_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013789#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013790 OS_SCANDIR_METHODDEF
Ethan Furman410ef8e2016-06-04 12:06:26 -070013791 OS_FSPATH_METHODDEF
Victor Stinner9b1f4742016-09-06 16:18:52 -070013792 OS_GETRANDOM_METHODDEF
Zackery Spytz43fdbd22019-05-29 13:57:07 -060013793 OS_MEMFD_CREATE_METHODDEF
Steve Dower2438cdf2019-03-29 16:37:16 -070013794#ifdef MS_WINDOWS
13795 OS__ADD_DLL_DIRECTORY_METHODDEF
13796 OS__REMOVE_DLL_DIRECTORY_METHODDEF
13797#endif
Victor Stinner8c62be82010-05-06 00:08:46 +000013798 {NULL, NULL} /* Sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013799};
13800
Barry Warsaw4a342091996-12-19 23:50:02 +000013801static int
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013802all_ins(PyObject *m)
Barry Warsaw4a342091996-12-19 23:50:02 +000013803{
Guido van Rossum94f6f721999-01-06 18:42:14 +000013804#ifdef F_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013805 if (PyModule_AddIntMacro(m, F_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013806#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013807#ifdef R_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013808 if (PyModule_AddIntMacro(m, R_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013809#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013810#ifdef W_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013811 if (PyModule_AddIntMacro(m, W_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013812#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013813#ifdef X_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013814 if (PyModule_AddIntMacro(m, X_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013815#endif
Fred Drakec9680921999-12-13 16:37:25 +000013816#ifdef NGROUPS_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013817 if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
Fred Drakec9680921999-12-13 16:37:25 +000013818#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013819#ifdef TMP_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013820 if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013821#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013822#ifdef WCONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013823 if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013824#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013825#ifdef WNOHANG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013826 if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013827#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013828#ifdef WUNTRACED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013829 if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013830#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013831#ifdef O_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013832 if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013833#endif
13834#ifdef O_WRONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013835 if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013836#endif
13837#ifdef O_RDWR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013838 if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013839#endif
13840#ifdef O_NDELAY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013841 if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013842#endif
13843#ifdef O_NONBLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013844 if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013845#endif
13846#ifdef O_APPEND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013847 if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013848#endif
13849#ifdef O_DSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013850 if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013851#endif
13852#ifdef O_RSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013853 if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013854#endif
13855#ifdef O_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013856 if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013857#endif
13858#ifdef O_NOCTTY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013859 if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013860#endif
13861#ifdef O_CREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013862 if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013863#endif
13864#ifdef O_EXCL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013865 if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013866#endif
13867#ifdef O_TRUNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013868 if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013869#endif
Guido van Rossum98d9d091997-08-08 21:48:51 +000013870#ifdef O_BINARY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013871 if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013872#endif
13873#ifdef O_TEXT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013874 if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013875#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013876#ifdef O_XATTR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013877 if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013878#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013879#ifdef O_LARGEFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013880 if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013881#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013882#ifndef __GNU__
Skip Montanaro5ff14922005-05-16 02:42:22 +000013883#ifdef O_SHLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013884 if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013885#endif
13886#ifdef O_EXLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013887 if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013888#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013889#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013890#ifdef O_EXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013891 if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013892#endif
13893#ifdef O_SEARCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013894 if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013895#endif
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013896#ifdef O_PATH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013897 if (PyModule_AddIntMacro(m, O_PATH)) return -1;
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013898#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013899#ifdef O_TTY_INIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013900 if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013901#endif
Christian Heimes177b3f92013-08-16 14:35:09 +020013902#ifdef O_TMPFILE
13903 if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
13904#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013905#ifdef PRIO_PROCESS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013906 if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013907#endif
13908#ifdef PRIO_PGRP
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013909 if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013910#endif
13911#ifdef PRIO_USER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013912 if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013913#endif
Charles-François Natali1e045b12011-05-22 20:42:32 +020013914#ifdef O_CLOEXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013915 if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
Charles-François Natali1e045b12011-05-22 20:42:32 +020013916#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013917#ifdef O_ACCMODE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013918 if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013919#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013920
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013921
Jesus Cea94363612012-06-22 18:32:07 +020013922#ifdef SEEK_HOLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013923 if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013924#endif
13925#ifdef SEEK_DATA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013926 if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013927#endif
13928
Tim Peters5aa91602002-01-30 05:46:57 +000013929/* MS Windows */
13930#ifdef O_NOINHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000013931 /* Don't inherit in child processes. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013932 if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013933#endif
13934#ifdef _O_SHORT_LIVED
Victor Stinner8c62be82010-05-06 00:08:46 +000013935 /* Optimize for short life (keep in memory). */
13936 /* MS forgot to define this one with a non-underscore form too. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013937 if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013938#endif
13939#ifdef O_TEMPORARY
Victor Stinner8c62be82010-05-06 00:08:46 +000013940 /* Automatically delete when last handle is closed. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013941 if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013942#endif
13943#ifdef O_RANDOM
Victor Stinner8c62be82010-05-06 00:08:46 +000013944 /* Optimize for random access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013945 if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013946#endif
13947#ifdef O_SEQUENTIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000013948 /* Optimize for sequential access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013949 if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013950#endif
13951
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013952/* GNU extensions. */
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013953#ifdef O_ASYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000013954 /* Send a SIGIO signal whenever input or output
13955 becomes available on file descriptor */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013956 if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013957#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013958#ifdef O_DIRECT
Victor Stinner8c62be82010-05-06 00:08:46 +000013959 /* Direct disk access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013960 if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013961#endif
13962#ifdef O_DIRECTORY
Victor Stinner8c62be82010-05-06 00:08:46 +000013963 /* Must be a directory. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013964 if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013965#endif
13966#ifdef O_NOFOLLOW
Victor Stinner8c62be82010-05-06 00:08:46 +000013967 /* Do not follow links. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013968 if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013969#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013970#ifdef O_NOLINKS
13971 /* Fails if link count of the named file is greater than 1 */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013972 if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013973#endif
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000013974#ifdef O_NOATIME
Victor Stinner8c62be82010-05-06 00:08:46 +000013975 /* Do not update the access time. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013976 if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000013977#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +000013978
Victor Stinner8c62be82010-05-06 00:08:46 +000013979 /* These come from sysexits.h */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013980#ifdef EX_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013981 if (PyModule_AddIntMacro(m, EX_OK)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013982#endif /* EX_OK */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013983#ifdef EX_USAGE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013984 if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013985#endif /* EX_USAGE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013986#ifdef EX_DATAERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013987 if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013988#endif /* EX_DATAERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013989#ifdef EX_NOINPUT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013990 if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013991#endif /* EX_NOINPUT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013992#ifdef EX_NOUSER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013993 if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013994#endif /* EX_NOUSER */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013995#ifdef EX_NOHOST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013996 if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013997#endif /* EX_NOHOST */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013998#ifdef EX_UNAVAILABLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013999 if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014000#endif /* EX_UNAVAILABLE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014001#ifdef EX_SOFTWARE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014002 if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014003#endif /* EX_SOFTWARE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014004#ifdef EX_OSERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014005 if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014006#endif /* EX_OSERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014007#ifdef EX_OSFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014008 if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014009#endif /* EX_OSFILE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014010#ifdef EX_CANTCREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014011 if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014012#endif /* EX_CANTCREAT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014013#ifdef EX_IOERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014014 if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014015#endif /* EX_IOERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014016#ifdef EX_TEMPFAIL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014017 if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014018#endif /* EX_TEMPFAIL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014019#ifdef EX_PROTOCOL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014020 if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014021#endif /* EX_PROTOCOL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014022#ifdef EX_NOPERM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014023 if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014024#endif /* EX_NOPERM */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014025#ifdef EX_CONFIG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014026 if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014027#endif /* EX_CONFIG */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014028#ifdef EX_NOTFOUND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014029 if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014030#endif /* EX_NOTFOUND */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014031
Amaury Forgeot d'Arc66d00ad2010-09-10 18:11:45 +000014032 /* statvfs */
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014033#ifdef ST_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014034 if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014035#endif /* ST_RDONLY */
14036#ifdef ST_NOSUID
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014037 if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014038#endif /* ST_NOSUID */
14039
doko@ubuntu.comca616a22013-12-08 15:23:07 +010014040 /* GNU extensions */
14041#ifdef ST_NODEV
14042 if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
14043#endif /* ST_NODEV */
14044#ifdef ST_NOEXEC
14045 if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
14046#endif /* ST_NOEXEC */
14047#ifdef ST_SYNCHRONOUS
14048 if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
14049#endif /* ST_SYNCHRONOUS */
14050#ifdef ST_MANDLOCK
14051 if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
14052#endif /* ST_MANDLOCK */
14053#ifdef ST_WRITE
14054 if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
14055#endif /* ST_WRITE */
14056#ifdef ST_APPEND
14057 if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
14058#endif /* ST_APPEND */
14059#ifdef ST_NOATIME
14060 if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
14061#endif /* ST_NOATIME */
14062#ifdef ST_NODIRATIME
14063 if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
14064#endif /* ST_NODIRATIME */
14065#ifdef ST_RELATIME
14066 if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
14067#endif /* ST_RELATIME */
14068
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014069 /* FreeBSD sendfile() constants */
14070#ifdef SF_NODISKIO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014071 if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014072#endif
14073#ifdef SF_MNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014074 if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014075#endif
14076#ifdef SF_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014077 if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014078#endif
14079
Ross Lagerwall7807c352011-03-17 20:20:30 +020014080 /* constants for posix_fadvise */
14081#ifdef POSIX_FADV_NORMAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014082 if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014083#endif
14084#ifdef POSIX_FADV_SEQUENTIAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014085 if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014086#endif
14087#ifdef POSIX_FADV_RANDOM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014088 if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014089#endif
14090#ifdef POSIX_FADV_NOREUSE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014091 if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014092#endif
14093#ifdef POSIX_FADV_WILLNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014094 if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014095#endif
14096#ifdef POSIX_FADV_DONTNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014097 if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014098#endif
14099
14100 /* constants for waitid */
14101#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014102 if (PyModule_AddIntMacro(m, P_PID)) return -1;
14103 if (PyModule_AddIntMacro(m, P_PGID)) return -1;
14104 if (PyModule_AddIntMacro(m, P_ALL)) return -1;
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080014105#ifdef P_PIDFD
14106 if (PyModule_AddIntMacro(m, P_PIDFD)) return -1;
14107#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014108#endif
14109#ifdef WEXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014110 if (PyModule_AddIntMacro(m, WEXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014111#endif
14112#ifdef WNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014113 if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014114#endif
14115#ifdef WSTOPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014116 if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014117#endif
14118#ifdef CLD_EXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014119 if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014120#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014121#ifdef CLD_KILLED
14122 if (PyModule_AddIntMacro(m, CLD_KILLED)) return -1;
14123#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014124#ifdef CLD_DUMPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014125 if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014126#endif
14127#ifdef CLD_TRAPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014128 if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014129#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014130#ifdef CLD_STOPPED
14131 if (PyModule_AddIntMacro(m, CLD_STOPPED)) return -1;
14132#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014133#ifdef CLD_CONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014134 if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014135#endif
14136
14137 /* constants for lockf */
14138#ifdef F_LOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014139 if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014140#endif
14141#ifdef F_TLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014142 if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014143#endif
14144#ifdef F_ULOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014145 if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014146#endif
14147#ifdef F_TEST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014148 if (PyModule_AddIntMacro(m, F_TEST)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014149#endif
14150
Pablo Galindo4defba32018-01-27 16:16:37 +000014151#ifdef RWF_DSYNC
14152 if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
14153#endif
14154#ifdef RWF_HIPRI
14155 if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
14156#endif
14157#ifdef RWF_SYNC
14158 if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
14159#endif
14160#ifdef RWF_NOWAIT
14161 if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
14162#endif
14163
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000014164/* constants for posix_spawn */
14165#ifdef HAVE_POSIX_SPAWN
14166 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
14167 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
14168 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
14169#endif
14170
pxinwrf2d7ac72019-05-21 18:46:37 +080014171#if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014172 if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
14173 if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014174 if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
pxinwrf2d7ac72019-05-21 18:46:37 +080014175#endif
14176#ifdef HAVE_SPAWNV
14177 if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014178 if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
Guido van Rossum246bc171999-02-01 23:54:31 +000014179#endif
14180
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014181#ifdef HAVE_SCHED_H
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014182#ifdef SCHED_OTHER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014183 if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014184#endif
14185#ifdef SCHED_FIFO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014186 if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014187#endif
14188#ifdef SCHED_RR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014189 if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014190#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014191#ifdef SCHED_SPORADIC
messi Liao0d322182017-06-13 22:30:43 +080014192 if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014193#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014194#ifdef SCHED_BATCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014195 if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014196#endif
14197#ifdef SCHED_IDLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014198 if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014199#endif
14200#ifdef SCHED_RESET_ON_FORK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014201 if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014202#endif
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014203#ifdef SCHED_SYS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014204 if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014205#endif
14206#ifdef SCHED_IA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014207 if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014208#endif
14209#ifdef SCHED_FSS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014210 if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014211#endif
14212#ifdef SCHED_FX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014213 if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014214#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014215#endif
14216
Benjamin Peterson9428d532011-09-14 11:45:52 -040014217#ifdef USE_XATTRS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014218 if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
14219 if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
14220 if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
Benjamin Peterson799bd802011-08-31 22:15:17 -040014221#endif
14222
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014223#if HAVE_DECL_RTLD_LAZY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014224 if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014225#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014226#if HAVE_DECL_RTLD_NOW
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014227 if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014228#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014229#if HAVE_DECL_RTLD_GLOBAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014230 if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014231#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014232#if HAVE_DECL_RTLD_LOCAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014233 if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014234#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014235#if HAVE_DECL_RTLD_NODELETE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014236 if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014237#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014238#if HAVE_DECL_RTLD_NOLOAD
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014239 if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014240#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014241#if HAVE_DECL_RTLD_DEEPBIND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014242 if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014243#endif
Michael Feltc5ae1692017-12-19 13:58:49 +010014244#if HAVE_DECL_RTLD_MEMBER
14245 if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
14246#endif
Victor Stinner8b905bd2011-10-25 13:34:04 +020014247
Victor Stinner9b1f4742016-09-06 16:18:52 -070014248#ifdef HAVE_GETRANDOM_SYSCALL
14249 if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
14250 if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
14251#endif
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014252#ifdef HAVE_MEMFD_CREATE
14253 if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
14254 if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
14255#ifdef MFD_HUGETLB
14256 if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014257#endif
14258#ifdef MFD_HUGE_SHIFT
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014259 if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014260#endif
14261#ifdef MFD_HUGE_MASK
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014262 if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014263#endif
14264#ifdef MFD_HUGE_64KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014265 if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014266#endif
14267#ifdef MFD_HUGE_512KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014268 if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014269#endif
14270#ifdef MFD_HUGE_1MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014271 if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014272#endif
14273#ifdef MFD_HUGE_2MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014274 if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014275#endif
14276#ifdef MFD_HUGE_8MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014277 if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014278#endif
14279#ifdef MFD_HUGE_16MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014280 if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014281#endif
14282#ifdef MFD_HUGE_32MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014283 if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014284#endif
14285#ifdef MFD_HUGE_256MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014286 if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014287#endif
14288#ifdef MFD_HUGE_512MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014289 if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014290#endif
14291#ifdef MFD_HUGE_1GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014292 if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014293#endif
14294#ifdef MFD_HUGE_2GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014295 if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014296#endif
14297#ifdef MFD_HUGE_16GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014298 if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
14299#endif
14300#endif
Victor Stinner9b1f4742016-09-06 16:18:52 -070014301
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020014302#if defined(__APPLE__)
14303 if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
14304#endif
14305
Steve Dower2438cdf2019-03-29 16:37:16 -070014306#ifdef MS_WINDOWS
14307 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
14308 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
14309 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
14310 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
14311 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
14312#endif
14313
Victor Stinner8c62be82010-05-06 00:08:46 +000014314 return 0;
Barry Warsaw4a342091996-12-19 23:50:02 +000014315}
14316
14317
Martin v. Löwis1a214512008-06-11 05:26:20 +000014318static struct PyModuleDef posixmodule = {
Victor Stinner8c62be82010-05-06 00:08:46 +000014319 PyModuleDef_HEAD_INIT,
14320 MODNAME,
14321 posix__doc__,
Eddie Elizondob3966632019-11-05 07:16:14 -080014322 sizeof(_posixstate),
Victor Stinner8c62be82010-05-06 00:08:46 +000014323 posix_methods,
14324 NULL,
Eddie Elizondob3966632019-11-05 07:16:14 -080014325 _posix_traverse,
14326 _posix_clear,
14327 _posix_free,
Martin v. Löwis1a214512008-06-11 05:26:20 +000014328};
14329
14330
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014331static const char * const have_functions[] = {
Larry Hastings9cf065c2012-06-22 16:30:09 -070014332
14333#ifdef HAVE_FACCESSAT
14334 "HAVE_FACCESSAT",
14335#endif
14336
14337#ifdef HAVE_FCHDIR
14338 "HAVE_FCHDIR",
14339#endif
14340
14341#ifdef HAVE_FCHMOD
14342 "HAVE_FCHMOD",
14343#endif
14344
14345#ifdef HAVE_FCHMODAT
14346 "HAVE_FCHMODAT",
14347#endif
14348
14349#ifdef HAVE_FCHOWN
14350 "HAVE_FCHOWN",
14351#endif
14352
Larry Hastings00964ed2013-08-12 13:49:30 -040014353#ifdef HAVE_FCHOWNAT
14354 "HAVE_FCHOWNAT",
14355#endif
14356
Larry Hastings9cf065c2012-06-22 16:30:09 -070014357#ifdef HAVE_FEXECVE
14358 "HAVE_FEXECVE",
14359#endif
14360
14361#ifdef HAVE_FDOPENDIR
14362 "HAVE_FDOPENDIR",
14363#endif
14364
Georg Brandl306336b2012-06-24 12:55:33 +020014365#ifdef HAVE_FPATHCONF
14366 "HAVE_FPATHCONF",
14367#endif
14368
Larry Hastings9cf065c2012-06-22 16:30:09 -070014369#ifdef HAVE_FSTATAT
14370 "HAVE_FSTATAT",
14371#endif
14372
14373#ifdef HAVE_FSTATVFS
14374 "HAVE_FSTATVFS",
14375#endif
14376
Steve Dowerfe0a41a2015-03-20 19:50:46 -070014377#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Georg Brandl306336b2012-06-24 12:55:33 +020014378 "HAVE_FTRUNCATE",
14379#endif
14380
Larry Hastings9cf065c2012-06-22 16:30:09 -070014381#ifdef HAVE_FUTIMENS
14382 "HAVE_FUTIMENS",
14383#endif
14384
14385#ifdef HAVE_FUTIMES
14386 "HAVE_FUTIMES",
14387#endif
14388
14389#ifdef HAVE_FUTIMESAT
14390 "HAVE_FUTIMESAT",
14391#endif
14392
14393#ifdef HAVE_LINKAT
14394 "HAVE_LINKAT",
14395#endif
14396
14397#ifdef HAVE_LCHFLAGS
14398 "HAVE_LCHFLAGS",
14399#endif
14400
14401#ifdef HAVE_LCHMOD
14402 "HAVE_LCHMOD",
14403#endif
14404
14405#ifdef HAVE_LCHOWN
14406 "HAVE_LCHOWN",
14407#endif
14408
14409#ifdef HAVE_LSTAT
14410 "HAVE_LSTAT",
14411#endif
14412
14413#ifdef HAVE_LUTIMES
14414 "HAVE_LUTIMES",
14415#endif
14416
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014417#ifdef HAVE_MEMFD_CREATE
14418 "HAVE_MEMFD_CREATE",
14419#endif
14420
Larry Hastings9cf065c2012-06-22 16:30:09 -070014421#ifdef HAVE_MKDIRAT
14422 "HAVE_MKDIRAT",
14423#endif
14424
14425#ifdef HAVE_MKFIFOAT
14426 "HAVE_MKFIFOAT",
14427#endif
14428
14429#ifdef HAVE_MKNODAT
14430 "HAVE_MKNODAT",
14431#endif
14432
14433#ifdef HAVE_OPENAT
14434 "HAVE_OPENAT",
14435#endif
14436
14437#ifdef HAVE_READLINKAT
14438 "HAVE_READLINKAT",
14439#endif
14440
14441#ifdef HAVE_RENAMEAT
14442 "HAVE_RENAMEAT",
14443#endif
14444
14445#ifdef HAVE_SYMLINKAT
14446 "HAVE_SYMLINKAT",
14447#endif
14448
14449#ifdef HAVE_UNLINKAT
14450 "HAVE_UNLINKAT",
14451#endif
14452
14453#ifdef HAVE_UTIMENSAT
14454 "HAVE_UTIMENSAT",
14455#endif
14456
14457#ifdef MS_WINDOWS
14458 "MS_WINDOWS",
14459#endif
14460
14461 NULL
14462};
14463
14464
Mark Hammondfe51c6d2002-08-02 02:27:13 +000014465PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +000014466INITFUNC(void)
Guido van Rossumb6775db1994-08-01 11:34:53 +000014467{
Victor Stinner8c62be82010-05-06 00:08:46 +000014468 PyObject *m, *v;
Larry Hastings9cf065c2012-06-22 16:30:09 -070014469 PyObject *list;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014470 const char * const *trace;
Tim Peters5aa91602002-01-30 05:46:57 +000014471
Eddie Elizondob3966632019-11-05 07:16:14 -080014472 m = PyState_FindModule(&posixmodule);
14473 if (m != NULL) {
14474 Py_INCREF(m);
14475 return m;
14476 }
14477
Victor Stinner8c62be82010-05-06 00:08:46 +000014478 m = PyModule_Create(&posixmodule);
14479 if (m == NULL)
14480 return NULL;
Tim Peters5aa91602002-01-30 05:46:57 +000014481
Victor Stinner8c62be82010-05-06 00:08:46 +000014482 /* Initialize environ dictionary */
14483 v = convertenviron();
14484 Py_XINCREF(v);
14485 if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
14486 return NULL;
14487 Py_DECREF(v);
Fred Drakec9680921999-12-13 16:37:25 +000014488
Victor Stinner8c62be82010-05-06 00:08:46 +000014489 if (all_ins(m))
14490 return NULL;
Barry Warsaw4a342091996-12-19 23:50:02 +000014491
Victor Stinner8c62be82010-05-06 00:08:46 +000014492 if (setup_confname_tables(m))
14493 return NULL;
Fred Drakebec628d1999-12-15 18:31:10 +000014494
Victor Stinner8c62be82010-05-06 00:08:46 +000014495 Py_INCREF(PyExc_OSError);
14496 PyModule_AddObject(m, "error", PyExc_OSError);
Fred Drake762e2061999-08-26 17:23:54 +000014497
Guido van Rossumb3d39562000-01-31 18:41:26 +000014498#ifdef HAVE_PUTENV
Eddie Elizondob3966632019-11-05 07:16:14 -080014499 /* Save putenv() parameters as values here, so we can collect them when they
14500 * get re-set with another call for the same key. */
14501 _posixstate(m)->posix_putenv_garbage = PyDict_New();
Guido van Rossumb3d39562000-01-31 18:41:26 +000014502#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +000014503
Ross Lagerwall7807c352011-03-17 20:20:30 +020014504#if defined(HAVE_WAITID) && !defined(__APPLE__)
Eddie Elizondob3966632019-11-05 07:16:14 -080014505 waitid_result_desc.name = MODNAME ".waitid_result";
14506 PyObject *WaitidResultType = (PyObject *)PyStructSequence_NewType(&waitid_result_desc);
14507 if (WaitidResultType == NULL) {
14508 return NULL;
14509 }
14510 Py_INCREF(WaitidResultType);
14511 PyModule_AddObject(m, "waitid_result", WaitidResultType);
14512 _posixstate(m)->WaitidResultType = WaitidResultType;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014513#endif
14514
Eddie Elizondob3966632019-11-05 07:16:14 -080014515 stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
14516 stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
14517 stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
14518 stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
14519 PyObject *StatResultType = (PyObject *)PyStructSequence_NewType(&stat_result_desc);
14520 if (StatResultType == NULL) {
14521 return NULL;
14522 }
14523 Py_INCREF(StatResultType);
14524 PyModule_AddObject(m, "stat_result", StatResultType);
14525 _posixstate(m)->StatResultType = StatResultType;
14526 structseq_new = ((PyTypeObject *)StatResultType)->tp_new;
14527 ((PyTypeObject *)StatResultType)->tp_new = statresult_new;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014528
Eddie Elizondob3966632019-11-05 07:16:14 -080014529 statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
14530 PyObject *StatVFSResultType = (PyObject *)PyStructSequence_NewType(&statvfs_result_desc);
14531 if (StatVFSResultType == NULL) {
14532 return NULL;
14533 }
14534 Py_INCREF(StatVFSResultType);
14535 PyModule_AddObject(m, "statvfs_result", StatVFSResultType);
14536 _posixstate(m)->StatVFSResultType = StatVFSResultType;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014537#ifdef NEED_TICKS_PER_SECOND
14538# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Eddie Elizondob3966632019-11-05 07:16:14 -080014539 ticks_per_second = sysconf(_SC_CLK_TCK);
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014540# elif defined(HZ)
Eddie Elizondob3966632019-11-05 07:16:14 -080014541 ticks_per_second = HZ;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014542# else
Eddie Elizondob3966632019-11-05 07:16:14 -080014543 ticks_per_second = 60; /* magic fallback value; may be bogus */
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014544# endif
14545#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014546
William Orr81574b82018-10-01 22:19:56 -070014547#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Eddie Elizondob3966632019-11-05 07:16:14 -080014548 sched_param_desc.name = MODNAME ".sched_param";
14549 PyObject *SchedParamType = (PyObject *)PyStructSequence_NewType(&sched_param_desc);
14550 if (SchedParamType == NULL) {
14551 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000014552 }
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014553 Py_INCREF(SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -080014554 PyModule_AddObject(m, "sched_param", SchedParamType);
14555 _posixstate(m)->SchedParamType = SchedParamType;
14556 ((PyTypeObject *)SchedParamType)->tp_new = os_sched_param;
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014557#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +000014558
Eddie Elizondob3966632019-11-05 07:16:14 -080014559 /* initialize TerminalSize_info */
14560 PyObject *TerminalSizeType = (PyObject *)PyStructSequence_NewType(&TerminalSize_desc);
14561 if (TerminalSizeType == NULL) {
14562 return NULL;
14563 }
14564 Py_INCREF(TerminalSizeType);
14565 PyModule_AddObject(m, "terminal_size", TerminalSizeType);
14566 _posixstate(m)->TerminalSizeType = TerminalSizeType;
14567
14568 /* initialize scandir types */
14569 PyObject *ScandirIteratorType = PyType_FromSpec(&ScandirIteratorType_spec);
14570 if (ScandirIteratorType == NULL) {
14571 return NULL;
14572 }
14573 _posixstate(m)->ScandirIteratorType = ScandirIteratorType;
14574
14575 PyObject *DirEntryType = PyType_FromSpec(&DirEntryType_spec);
14576 if (DirEntryType == NULL) {
14577 return NULL;
14578 }
14579 Py_INCREF(DirEntryType);
14580 PyModule_AddObject(m, "DirEntry", DirEntryType);
14581 _posixstate(m)->DirEntryType = DirEntryType;
14582
Larry Hastings605a62d2012-06-24 04:33:36 -070014583 times_result_desc.name = MODNAME ".times_result";
Eddie Elizondob3966632019-11-05 07:16:14 -080014584 PyObject *TimesResultType = (PyObject *)PyStructSequence_NewType(&times_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014585 if (TimesResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014586 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014587 }
Eddie Elizondob3966632019-11-05 07:16:14 -080014588 Py_INCREF(TimesResultType);
14589 PyModule_AddObject(m, "times_result", TimesResultType);
14590 _posixstate(m)->TimesResultType = TimesResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070014591
Eddie Elizondob3966632019-11-05 07:16:14 -080014592 PyTypeObject *UnameResultType = PyStructSequence_NewType(&uname_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014593 if (UnameResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014594 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014595 }
Eddie Elizondob3966632019-11-05 07:16:14 -080014596 Py_INCREF(UnameResultType);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014597 PyModule_AddObject(m, "uname_result", (PyObject *)UnameResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -080014598 _posixstate(m)->UnameResultType = (PyObject *)UnameResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070014599
Thomas Wouters477c8d52006-05-27 19:21:47 +000014600#ifdef __APPLE__
Victor Stinner8c62be82010-05-06 00:08:46 +000014601 /*
14602 * Step 2 of weak-linking support on Mac OS X.
14603 *
14604 * The code below removes functions that are not available on the
14605 * currently active platform.
14606 *
14607 * This block allow one to use a python binary that was build on
Larry Hastings9cf065c2012-06-22 16:30:09 -070014608 * OSX 10.4 on OSX 10.3, without losing access to new APIs on
Victor Stinner8c62be82010-05-06 00:08:46 +000014609 * OSX 10.4.
14610 */
Thomas Wouters477c8d52006-05-27 19:21:47 +000014611#ifdef HAVE_FSTATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014612 if (fstatvfs == NULL) {
14613 if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
14614 return NULL;
14615 }
14616 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014617#endif /* HAVE_FSTATVFS */
14618
14619#ifdef HAVE_STATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014620 if (statvfs == NULL) {
14621 if (PyObject_DelAttrString(m, "statvfs") == -1) {
14622 return NULL;
14623 }
14624 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014625#endif /* HAVE_STATVFS */
14626
14627# ifdef HAVE_LCHOWN
Victor Stinner8c62be82010-05-06 00:08:46 +000014628 if (lchown == NULL) {
14629 if (PyObject_DelAttrString(m, "lchown") == -1) {
14630 return NULL;
14631 }
14632 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014633#endif /* HAVE_LCHOWN */
14634
14635
14636#endif /* __APPLE__ */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014637
Eddie Elizondob3966632019-11-05 07:16:14 -080014638 if ((_posixstate(m)->billion = PyLong_FromLong(1000000000)) == NULL)
14639 return NULL;
14640#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
14641 _posixstate(m)->struct_rusage = PyUnicode_InternFromString("struct_rusage");
14642 if (_posixstate(m)->struct_rusage == NULL)
14643 return NULL;
14644#endif
14645 _posixstate(m)->st_mode = PyUnicode_InternFromString("st_mode");
14646 if (_posixstate(m)->st_mode == NULL)
Larry Hastings6fe20b32012-04-19 15:07:49 -070014647 return NULL;
14648
Larry Hastings9cf065c2012-06-22 16:30:09 -070014649 /* suppress "function not used" warnings */
14650 {
14651 int ignored;
14652 fd_specified("", -1);
14653 follow_symlinks_specified("", 1);
14654 dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
14655 dir_fd_converter(Py_None, &ignored);
14656 dir_fd_unavailable(Py_None, &ignored);
14657 }
14658
14659 /*
14660 * provide list of locally available functions
14661 * so os.py can populate support_* lists
14662 */
14663 list = PyList_New(0);
14664 if (!list)
14665 return NULL;
14666 for (trace = have_functions; *trace; trace++) {
14667 PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
14668 if (!unicode)
14669 return NULL;
14670 if (PyList_Append(list, unicode))
14671 return NULL;
14672 Py_DECREF(unicode);
14673 }
14674 PyModule_AddObject(m, "_have_functions", list);
Ned Deilyeb3be662016-08-15 14:40:38 -040014675
Victor Stinner8c62be82010-05-06 00:08:46 +000014676 return m;
Guido van Rossumb6775db1994-08-01 11:34:53 +000014677}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014678
14679#ifdef __cplusplus
14680}
14681#endif